branch_name
stringclasses 149
values | text
stringlengths 23
89.3M
| directory_id
stringlengths 40
40
| languages
listlengths 1
19
| num_files
int64 1
11.8k
| repo_language
stringclasses 38
values | repo_name
stringlengths 6
114
| revision_id
stringlengths 40
40
| snapshot_id
stringlengths 40
40
|
---|---|---|---|---|---|---|---|---|
refs/heads/master
|
<file_sep>import React, { Component } from 'react'
class Home extends Component {
constructor() {
super()
}
render() {
const imageStyle = {
width: 400
}
return (
<div style = {{padding: 30}}>
<h4>LET US MAKE IT HAPPEN</h4>
<img style={imageStyle} src="https://open.buffer.com/wp-content/uploads/2018/02/simone-hutsch-576365-unsplash-1024x1258.jpg" />
</div>
)
}
}
export default Home
<file_sep>import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import axios from 'axios'
let privilage = '';
class LoginForm extends Component {
constructor() {
super()
this.state = {
username: '',
password: '',
message: '',
error1: true,
redirect: false
}
this.handleSubmit = this.handleSubmit.bind(this)
this.handleChange = this.handleChange.bind(this)
}
setRedirect = () => {
this.setState({
redirect: true
})
}
renderRedirect = (privilages) => {
if (this.state.redirect) {
if (privilages === "posting") {
return <Redirect to = '/recruiterProfile' />
}
else
{
return <Redirect to = '/applicantProfile' />
}
}
}
handleChange(event) {
this.setState({
[event.target.name]: event.target.value
})
}
handleSubmit(event) {
event.preventDefault()
console.log('handleSubmit')
axios
.post('/user/login', {
username: this.state.username,
password: <PASSWORD>,
privilages: this.state.privilages
})
.then(response => {
console.log('login response: ')
console.log(response)
if (response.status === 200) {
// update App.js state
this.props.updateUser({
loggedIn: true,
username: response.data.username,
privilages: response.data.privilages,
firstName: response.data.firstName,
lastName: response.data.lastName
})
// update the state to redirect to home
this.setState({ message: '' });
privilage = response.data.privilages
this.setRedirect();
}
}).catch(error => {
this.setState ({
error1: false
});
console.log('login error: ')
console.log(error);
})
}
render() {
if (this.state.redirectTo) {
return <Redirect to={{ pathname: this.state.redirectTo }} />
} else {
return (
<div>
<h4>Login</h4>
<form className="form-horizontal">
<div className="form-group">
<div className="col-1 col-ml-auto">
<label className="form-label" htmlFor="username">Username: </label>
</div>
<div className="col-3 col-mr-auto">
<input className="form-input"
type="text"
id="username"
name="username"
placeholder="Username"
value={this.state.username}
onChange={this.handleChange}
/>
</div>
</div>
<div className="form-group">
<div className="col-1 col-ml-auto">
<label className="form-label" htmlFor="password">Password: </label>
</div>
<div className="col-3 col-mr-auto">
<input className="form-input"
placeholder="<PASSWORD>"
type="password"
name="password"
value={this.state.password}
onChange={this.handleChange}
/>
</div>
</div>
<div className="form-group ">
<div className="col-7"></div>
{this.renderRedirect(privilage)}
<button
className="btn btn-success col-1 col-mr-auto"
onClick={this.handleSubmit}
type="submit"
>Login</button>
</div>
<div className="error" style={{display: this.state.error1 ? 'none' : 'block'}}>Username or Password are Invalid
</div>
</form>
</div>
)
}
}
}
export default LoginForm
<file_sep>const mongoose = require('mongoose')
const Schema = mongoose.Schema
const bcrypt = require('bcryptjs');
mongoose.promise = Promise
const jobPostSchema = new Schema({
title: { type: String, unique: false, required: false},
description: { type: String, unique: false, required: false},
skillset: [{
skill: { type: String, unique: false, required: false} ,
proficiency: { type: String, unique: false, required: false},
years: { type: String, unique: false, required: false},
importance: { type: String, unique: false, required: false}
}]
})
const JobPost = mongoose.model("JobPost", jobPostSchema)
module.exports = JobPost;<file_sep>import React, { Component } from 'react';
import axios from 'axios'
import { Route, Link } from 'react-router-dom'
// components
import Signup from './components/sign-up'
import LoginForm from './components/login-form'
import ApplicantProfile from './components/applicant-profile'
import RecruiterProfile from './components/recruiter-profile'
import Navbar from './components/navbar'
import Home from './components/home'
import Posting from './components/job-posting';
class App extends Component {
constructor() {
super()
this.state = {
loggedIn: false,
username: null,
firstName: null,
lastName: null,
privilages: null
}
this.getUser = this.getUser.bind(this)
this.componentDidMount = this.componentDidMount.bind(this)
this.updateUser = this.updateUser.bind(this)
}
componentDidMount() {
this.getUser()
}
updateUser (userObject) {
this.setState(userObject)
}
getUser() {
axios.get('/user/').then(response => {
console.log('Get user response: ')
console.log(response.data)
if (response.data.user) {
this.setState({
loggedIn: true,
username: response.data.user.username,
firstName: response.data.user.firstName,
lastName: response.data.user.lastName,
privilages: response.data.user.privilages
})
} else {
console.log('Get user: no user');
this.setState({
loggedIn: false,
username: null
})
}
})
}
render() {
return (
<div className="App">
<Navbar updateUser={this.updateUser} loggedIn={this.state.loggedIn} />
{/* greet user if logged in: */}
{this.state.loggedIn &&
<p>Join the party, {this.state.firstName} {this.state.lastName} and you are {this.state.privilages}!</p>
}
{/* Routes to different components */}
<Route
exact path="/"
component={Home} />
<Route
path="/login"
render={() =>
<LoginForm
updateUser={this.updateUser}
/>}
/>
<Route
path="/signup"
render={() =>
<Signup
updateUser={this.updateUser}
/>}
/>
<Route
path="/applicantProfile"
render={() =>
<ApplicantProfile
/>}
/>
<Route
path="/recruiterProfile"
render={() =>
<RecruiterProfile
username={this.state.username}
skillset={this.state.skillset}
/>}
/>
<Route
path="/jobPosting"
render={() =>
<Posting
username={this.state.username}
skillset={this.state.skillset}
/>}
/>
</div>
);
}
}
export default App;
<file_sep>import React, { Component } from 'react'
import { Redirect } from 'react-router-dom'
import axios from 'axios'
import JobInputs from "./manage-jobs"
import Posting from "./job-posting"
class ApplicantProfile extends Component {
constructor() {
super();
this.state = {
username: '',
skillset: [{ username: '' }],
proficiency: [{ username: ''}],
yearsExperience: [{ username: ''}],
achievements: [{ username: ''}]
};
console.log("Applicant Skillset: ", Posting)
}
render() {
return (
<form>
<label
type="text"
value={this.props.username}
/>
<label>
Skill: {Posting}
<h2 value={Posting} />
</label>
<button>Submit Profile</button>
</form>
)
}
}
export default ApplicantProfile;
<file_sep>import React from "react"
const JobInputs = (props) => {
return (
props.skillset.map((val, jobId)=> {
let skillId = `skill-${jobId}`, proficiencyId = `proficiency-${jobId}`, yearsId = `years-${jobId}`, importanceId = `importance-${jobId}`
return (
<div key={jobId}>
<label htmlFor={skillId}>{`Skill #${jobId + 1}`}</label>
<input
type="text"
name={skillId}
data-id={jobId}
id={skillId}
value={props.skillset[jobId].skill}
className="skill"
/>
<label htmlFor={proficiencyId}>Proficiency</label>
<select className="proficiency"
type="text"
name={proficiencyId}
data-id={jobId}
id={proficiencyId}
value={props.skillset[jobId].proficiencyId}
>
<option value="beginner">Beginner</option>
<option value="intermediate">Intermediate</option>
<option value="expert">Expert</option>
</select>
<label htmlFor={yearsId}>Years of experience</label>
<select className="years"
type="text"
name={yearsId}
data-id={jobId}
id={yearsId}
value={props.skillset[jobId].years}
>
<option value="0-2">0-2</option>
<option value="2-3">2-3</option>
<option value="3-5">3-5</option>
<option value="5-10">5-10</option>
<option value="10+">10+</option>
</select>
<label htmlFor={importanceId}>Importance of Skill</label>
<select className="importance"
type="text"
name={importanceId}
data-id={jobId}
id={importanceId}
value={props.skillset[jobId].importance}
>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
)
})
)
}
export default JobInputs<file_sep>import React from "react"
import axios from "axios";
import JobInputs from "./manage-jobs"
class Posting extends React.Component {
state = {
skillset: [{
skill: "",
proficiency: "",
years: "",
importance: ""
}],
title: "",
description: ""
}
handleChange = (e) => {
if (["skill", "proficiency", "years", "importance"].includes(e.target.className) ) {
let skillset = [...this.state.skillset]
skillset[e.target.dataset.id][e.target.className] = e.target.value.toUpperCase()
this.setState({ skillset }, () => console.log(this.state.skillset))
} else {
this.setState({ [e.target.name]: e.target.value.toUpperCase() })
}
}
addSkill = (e) => {
this.setState((prevState) => ({
skillset: [...prevState.skillset, {skill:"", proficiency: "", years: "", importance: "" }],
}));
}
handleSubmit = (e) => {
e.preventDefault()
let data = {
username: this.props.username,
title: this.state.title,
description: this.state.description,
skillset: this.state.skillset
}
axios.post('/employer/recruiterProfile/addJob', data);
}
componentDidUpdate() {
console.log(this.state)
}
render() {
let {title, description, skillset} = this.state
return (
<form onSubmit={this.handleSubmit} onChange={this.handleChange} >
<label htmlFor="title">Title</label>
<input type="text" name="title" id="title"
value={title}/>
<label htmlFor="description">Description</label>
<input type="text" name="description" id="description"
value={description}/>
<button onClick={this.addSkill}>Add required skills</button>
<JobInputs skillset={skillset} />
<input type="submit" value="Submit" />
</form>
)
}
}
export default Posting;
|
d99f7f76e473293ba6191d76cb179f8d0558a4d4
|
[
"JavaScript"
] | 7 |
JavaScript
|
ramiwehbe/Hire-Sync
|
5b469d2b1a004557dba0b83724d1896f50d1b850
|
bc7cbfe925c8bb3d7901370a507955f15c72d760
|
refs/heads/master
|
<repo_name>gabzaide/bois1nem<file_sep>/onlineshop/admin/updateadminprofiling.php
<!-- == COURSE UPDATE MODAL ======== -->
<?php echo '<div id="updateadminprofiling'.$row['firstname'].'" class="modal fade">
<form method="post">
<div class="modal-dialog modal-sm" style="width:300px !important;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"> Update Admin Profiling </h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<input type="hidden" value="'.$row['adminid'].'" name="adminid" id="adminid"/>
<div class="form-group">
<label> Enter Updated First Name: </label>
<input name="firstname" id="firstname" class="form-control input-sm" type="text" value="'.$row['firstname'].'" />
</div>
<div class="form-group">
<label> Enter Updated Middle Name: </label>
<input name="middlename" id="middlename" class="form-control input-sm" type="text" value="'.$row['middlename'].'" />
</div>
<div class="form-group">
<label> Enter Updated Family Name: </label>
<input name="familyname" id="familyname" class="form-control input-sm" type="text" value="'.$row['familyname'].'" />
</div>
<div class="form-group">
<label> Enter Updated Email Address: </label>
<input name="emailaddress" id="emailaddress" class="form-control input-sm" type="email" value="'.$row['emailaddress'].'" />
</div>
<div class="form-group">
<label> Enter Updated Username: </label>
<input name="username" id="username" class="form-control input-sm" type="text" value="'.$row['username'].'" />
</div>
<div class="form-group">
<label> Enter Updated Password: </label>
<input name="<PASSWORD>" id="<PASSWORD>" class="form-control input-sm" type="password" value="'.$row['password'].'" />
</div>
<div class="form-group">
<label> Enter Updated Status: </label>
<input name="status" id="status" class="form-control input-sm" type="text" value="'.$row['status'].'" />
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default btn-sm" data-dismiss="modal" value="Cancel"/>
<input type="submit" class="btn btn-primary btn-sm" name="update_admin_profiling" value="Update Admin Profiling"/>
</div>
</div>
</div>
</form>
</div>';?>
<file_sep>/onlineshop/user/examresult.php
<?php
include('connection.php');
$annsql = "SELECT * FROM results";
$annquery = mysqli_query($con , $annsql);
while ($row = mysqli_fetch_assoc($annquery)) {
echo "<div class='ann-list'>
<p class='ann-title'>".$row['coursetaken']."</p>
<p class='ann-content'>".$row['result']."</p>
<p class='ann-date'>~".$row['dateposted']."</p>
</div>";
}
?><file_sep>/onlineshop/user/loginfunction.php
<?php
session_start();
include('connection.php');
if (isset($_POST["login"])) {
$accountnumber = $_POST['accountnumber'];
$password = $_POST['<PASSWORD>'];
$sql = "SELECT * FROM customer WHERE accountnumber = '$accountnumber' and password = '$<PASSWORD>'";
$sql = mysqli_query($con , $sql);
if (mysqli_num_rows($sql) !=1) {
$_SESSION['userlogged'] = $accountnumber;
header("location:user.php.");
}
else {
echo "<script>
alert('Account Doesn't Exist!!!');
</script>";
}
}
?><file_sep>/onlineshop/user/usersubj.php
<?php
session_start();
include('../admin/connection.php');
if (!isset($_SESSION['userlogged'])) {
header("location:../logout.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- TITLE -->
<title> TESDA Assesment Center </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- BOOTSTRAP AND CSS -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../assets/css/zabuto_calendar.css">
<link rel="stylesheet" type="text/css" href="../assets/lineicons/style.css">
<link href="../assets/css/style.css" rel="stylesheet">
<link href="../assets/css/style-responsive.css" rel="stylesheet">
<link href="../assets/css/bootstrap.min.css" rel="stylesheet">
<link href="../assets/css/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<script src="../assets/js/chart-master/Chart.js"></script>
</head>
<!-- ICON -->
<link rel="icon" type="image/png" href="../assets/images/TESDA Logo.png" />
<body>
<?php
ob_start();
include "../admin/connection.php";
?>
<section id="container" >
<header class="header black-bg">
<div class="sidebar-toggle-box">
<div class="fa fa-bars tooltips" data-placement="right" data-original-title="Toggle Navigation"></div>
</div>
<a href="index.php" class="logo"><b> TESDA </b></a>
<div class="nav notify-row" id="top_menu">
</div>
<div class="top-menu">
<ul class="nav pull-right top-menu">
<li><a class="logout" href="userlogin.php"> Log Out </a></li>
</ul>
</div>
</header>
<!-- ** MAIN SIDEBAR MENU ** -->
<!-- SIDEBAR MENU START -->
<aside>
<div id="sidebar" class="nav-collapse ">
<!-- sidebar menu start-->
<ul class="sidebar-menu" id="nav-accordion">
<p class="centered"><a href="#"><img src="../assets/images/Profile.png" class="img-circle" width="60"></a></p>
<h5 class="centered"> WELCOME! <br>
<?php
echo $_SESSION['userlogged'];
?></h5>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-group"></i>
<span> PROFILE </span>
</a>
<ul class="sub">
<li><a href="usersubj.php"><i class="fa fa-graduation-cap"> Subjects </i></li></a>
</ul>
</li>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-tasks"></i>
<span> EXAM RESULTS </span>
</a>
<ul class="sub">
<li><a href="resuts.php"><i class="fa fa-balance-scale"> Exam Results </i></a></li>
</ul>
</li>
<!-- SIDEBAR MENU END -->
</div>
</aside>
<!-- *** MAIN CONTENT *** -->
<!-- MAIN CONTENT START -->
<section id="main-content">
<section class="wrapper">
<div class="row"><br><br>
<div class="col-lg-12"><center>
<h1> PROFILE </h1>
<div class="alert alert-dismissable alert-warning">
SUBJECTS
<br/>
</div></center>
</div>
</div>
<div class="box">
<div class="box-header">
<div style="padding:10px;">
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addmodal"><h5><i class="fa fa-plus" aria-hidden="true"></i> Add Subject </h5></button>
</div>
<br>
</div><!-- /.box-header -->
<div class="box-body table-responsive">
<form method="post">
<table id="table" class="table table-bordered table-striped">
<label>
<thead>
<tr>
<th style="width: 30px !important;"><input type="checkbox" name="chk_delete[]" class="cbxMain" onchange="checkMain(this)" /></th>
<th> Course Number </th>
<th> Course Name </th>
<th> Course Objectives </th>
<th> Course Description </th>
<th> Course Mode </th>
<th> Course Duration </th>
</tr>
</thead>
<tbody>
<?php
$squery = mysqli_query($con, "select * from courses");
while($row = mysqli_fetch_array($squery))
{
echo '
<tr>
<td><input type="checkbox" name="chk_delete[]" class="chk_delete" value="'.$row['courseid'].'" /></td>
<td>'.$row['coursenumber'].'</td>
<td>'.$row['coursename'].'</td>
<td>'.$row['courseobjective'].'</td>
<td>'.$row['coursedescription'].'</td>
<td>'.$row['coursemode'].'</td>
<td>'.$row['courseduration'].'</td>
</tr>
';
include "../admin/updatemodal.php";
}
?>
</tbody>
</table>
</form>
</div>
</div>
<?php include "addsubj.php"; ?>
<br><br><br>
<!-- FOOTER START -->
<footer class="site-footer">
<div class="text-center">
ยฉ 2018 All Rights Reserved
<a href="index.php" class="go-top">
<i class="fa fa-angle-up"></i>
</a>
</div>
</footer>
<!-- FOOTER END -->
</section>
<!-- JAVASCRIPT -->
<script type="text/javascript">
$(function() {
$("#table").dataTable({
"aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0,3 ] } ],"aaSorting": []
});
});
</script>
<script type="text/javascript">
function checkMain(x) {
var checked = $(x).prop('checked');
$('.cbxMain').prop('checked', checked)
$('tr:visible').each(function () {
$(this).find('.chk_delete').each(function () {
this.checked = checked;
});
});
}
$(document).ready(function (){
$('.chk_delete').click(function () {
if ($('.chk_delete:checked').length == $('.chk_delete').length) {
$('.cbxMain').prop('checked', true);
}
else {
$('.cbxMain').prop('checked', false);
}
$('#check-all').click(function(){
$("input:checkbox").attr('checked', true);
});
});
$('.no-print').hide();
});
</script>
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/jquery-1.8.3.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script class="include" type="text/javascript" src="../assets/js/jquery.dcjqaccordion.2.7.js"></script>
<script src="../assets/js/jquery.scrollTo.min.js"></script>
<script src="../assets/js/jquery.nicescroll.js" type="text/javascript"></script>
<script src="../assets/js/jquery.sparkline.js"></script>
<script src="../assets/js/common-scripts.js"></script>
<script src="../assets/js/sparkline-chart.js"></script>
<script src="../assets/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="../assets/js/dataTables.buttons.min.js" type="text/javascript"></script>
<script src="../assets/js/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<!-- JAVASCRIPT END -->
</body>
</html>
<file_sep>/onlineshop/admin/courses.php
<?php
session_start();
include('connection.php');
if (!isset($_SESSION['adminlogged'])) {
header("location:logout.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- TITLE -->
<title> TESDA Assesment Center </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CASCADING STYLE SHEET -->
<link href="../assets/css/style.css" rel="stylesheet"/>
<link href="../assets/css/bootstrap.css" rel="stylesheet"/>
<link href="../assets/css/style-responsive.css" rel="stylesheet"/>
<link href="../assets/css/bootstrap.min.css" rel="stylesheet"/>
<link href="../assets/css/ionicons.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="../assets/css/lineicons/style.css"/>
<link rel="stylesheet" type="text/css" href="../assets/css/zabuto_calendar.css"/>
<link href="../assets/css/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<!-- FONTS -->
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<!-- JAVASCRIPT -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/common-scripts.js"></script>
<script src="../assets/js/jquery-1.8.3.min.js"></script>
<script src="../assets/js/chart-master/Chart.js"></script>
<script src="../assets/js/alert.js" type="text/javascript"></script>
<script src="../assets/js/jquery-1.12.3.js" type="text/javascript"></script>
<script src="../assets/js/jquery.nicescroll.js" type="text/javascript"></script>
<script src="../assets/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="../assets/js/dataTables.buttons.min.js" type="text/javascript"></script>
<script src="../assets/js/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<script src="../assets/js/plugins/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<script class="include" type="text/javascript" src="../assets/js/jquery.dcjqaccordion.2.7.js"></script>
</head>
<!-- ICON -->
<link rel="icon" type="image/png" href="../assets/images/TESDA Logo.png" />
<body>
<?php
ob_start();
include "connection.php";
?>
<section id="container" >
<header class="header black-bg">
<div class="sidebar-toggle-box">
<div class="fa fa-bars tooltips" data-placement="right" data-original-title="Toggle Navigation"></div>
</div>
<a href="index.php" class="logo"><b> TESDA ASSESMENT CENTER DASHBOARD </b></a>
<div class="nav notify-row" id="top_menu">
<!-- NOTIFICATION START -->
<ul class="nav top-menu">
<!-- PERCENTEGE DETAILS START -->
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="courses.php">
<i class="fa fa-tasks"></i>
<span class="badge bg-theme"><I></I>2</span>
</a>
<ul class="dropdown-menu extended tasks-bar">
<div class="notify-arrow notify-arrow-green"></div>
<li>
<p class="green"> PERCENTAGE DETAILS </p>
</li>
<li>
<a href="#">
<div class="task-info">
<div class="desc">Students Panel</div>
<div class="percent">40%</div>
</div>
<div class="progress progress-striped">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
</a>
</li>
<li>
<a href="#">
<div class="task-info">
<div class="desc">Programs & Services Panel</div>
<div class="percent">60%</div>
</div>
<div class="progress progress-striped">
<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">
<span class="sr-only">60% Complete (warning)</span>
</div>
</div>
</a>
</li>
<li class="external">
<a href="#"> See All Details </a>
</li>
</ul>
</li>
<!--PERCENTAGE DETAILS END -->
<!-- MESSAGES DROPDOWN START-->
<li id="header_inbox_bar" class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="courses.php">
<i class="fa fa-envelope-o"></i>
<span class="badge bg-theme">1</span>
</a>
<ul class="dropdown-menu extended inbox">
<div class="notify-arrow notify-arrow-green"></div>
<li>
<p class="green"> MESSAGES </p>
</li>
<li>
<a href="#">
<span class="photo"><img alt="avatar" src="../assets/images/Profile.png"></span>
<span class="subject">
<span class="from"> <NAME> </span>
<span class="time"> Just now </span>
</span>
<span class="message">
Hi Mate, How is Everything?
</span>
</a>
</li>
<li>
<a href="#"> See All Messages </a>
</li>
</ul>
</li>
<!-- MESSAGES DROPDOWN END -->
</ul>
<!-- NOTIFICATION END -->
</div>
<div class="top-menu">
<ul class="nav pull-right top-menu">
<li><a class="logout" href="logout.php"> Log Out </a></li>
</ul>
</div>
</header>
<!-- ** MAIN SIDEBAR MENU ** -->
<!-- SIDEBAR MENU START -->
<aside>
<div id="sidebar" class="nav-collapse ">
<!-- sidebar menu start-->
<ul class="sidebar-menu" id="nav-accordion">
<p class="centered"><a href="#"><img src="../assets/images/Profile.png" class="img-circle" width="60"></a></p>
<h5 class="centered"> WELCOME ADMIN!! </h5>
<li class="mt">
<a href="index.php">
<i class="fa fa-dashboard"></i>
<span> DASHBOARD </span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-group"></i>
<span> ADMIN PROFILING </span>
</a>
<ul class="sub">
<li><a href="adminprofiling.php"><i class="fa fa-user"> Accounts </i></li></a>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-group"></i>
<span> STUDENT PROFILING </span>
</a>
<ul class="sub">
<li><a href="studentsprofiling.php"><i class="fa fa-graduation-cap"> Students </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-book"></i>
<span> COURSES </span>
</a>
<ul class="sub">
<li><a class="active" href="courses.php"><i class="fa fa-briefcase"> Programs & Services </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-tasks"></i>
<span> RESULTS </span>
</a>
<ul class="sub">
<li><a href="results.php"><i class="fa fa-balance-scale"> Exam Results </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-calendar"></i>
<span> EVENT SCHEDULING </span>
</a>
<ul class="sub">
<li><a href="calendar.php"><i class="fa fa-calendar"> Calendar </i></a></li>
</ul>
</li>
</ul>
<!-- SIDEBAR MENU END -->
</div>
</aside>
<!-- *** MAIN CONTENT *** -->
<!-- MAIN CONTENT START -->
<section id="main-content">
<section class="wrapper">
<div class="row"><br><br>
<div class="col-lg-12"><center>
<div class="alert alert-dismissable alert-warning">
<button data-dismiss="alert" class="close" type="button">×</button>
Welcome In Courses Panel, Admin!!
<br/>
</div></center>
</div>
</div>
<div class="box">
<div class="box-header">
<div style="padding:10px;">
<button class="btn btn-primary btn-sm" data-toggle="modal" data-target="#addcourse"><h5><i class="fa fa-plus" aria-hidden="true"></i> Add Programs & Services </h5></button>
<button class="btn btn-danger btn-sm" data-toggle="modal" data-target="#deletecourse"><h6><i class="fa fa-trash-o" aria-hidden="true"></i> Delete Programs & Services </h6></button>
</div>
<br>
</div><!-- /.box-header -->
<div class="box-body table-responsive">
<form method="post">
<table id="table" class="table table-bordered table-striped">
<thead>
<tr>
<th style="width: 30px !important;"><input type="checkbox" name="chk_delete[]" class="cbxMain" onchange="checkMain(this)" /></th>
<th class="sorting" tabindex="0" aria-controls="table" rowspan="1" colspan="1" aria-label="Course Number: activate to sort column ascending" style="width: 255px;"> Course Number </th>
<th class="sorting" tabindex="0" aria-controls="table" rowspan="1" colspan="1" aria-label="Course Name: activate to sort column ascending" style="width: 255px;"> Course Name </th>
<th class="sorting" tabindex="0" aria-controls="table" rowspan="1" colspan="1" aria-label="Unit Number: activate to sort column ascending" style="width: 255px;"> Course Objectives </th>
<th class="sorting" tabindex="0" aria-controls="table" rowspan="1" colspan="1" aria-label="Unit Number: activate to sort column ascending" style="width: 255px;"> Course Description </th>
<th class="sorting" tabindex="0" aria-controls="table" rowspan="1" colspan="1" aria-label="Unit Number: activate to sort column ascending" style="width: 255px;"> Course Mode </th>
<th class="sorting" tabindex="0" aria-controls="table" rowspan="1" colspan="1" aria-label="Unit Number: activate to sort column ascending" style="width: 255px;"> Course Duration </th>
<th style="width: 40px !important;">Option</th>
</tr>
</thead>
<tbody>
<?php
$squery = mysqli_query($con, "select * from courses");
while($row = mysqli_fetch_array($squery))
{
echo '
<tr>
<td><input type="checkbox" name="chk_delete[]" class="chk_delete" value="'.$row['courseid'].'" /></td>
<td>'.$row['coursenumber'].'</td>
<td>'.$row['coursename'].'</td>
<td>'.$row['courseobjective'].'</td>
<td>'.$row['coursedescription'].'</td>
<td>'.$row['coursemode'].'</td>
<td>'.$row['courseduration'].'</td>
<td><button class="btn btn-primary btn-sm" data-target="#updatecourse'.$row['courseid'].'" data-toggle="modal"><i class="fa fa-pencil-square-o" aria-hidden="true"></i> Update </button></td>
</tr>
';
include "updatemodalcourse.php";
}
?>
</tbody>
</table>
<?php include "deletemodal.php"; ?>
</form>
</div>
</div>
<?php include "notification.php"; ?>
<?php include "addmodal.php"; ?>
<?php include "addfunction.php"; ?>
<?php include "updatefunction.php"; ?>
<?php include "deletefunction.php"; ?>
<?php include "footer.php"; ?>
<br><br><br>
<!-- FOOTER START -->
<footer class="site-footer">
<div class="text-center">
ยฉ 2018 All Rights Reserved
<a href="courses.php" class="go-top">
<i class="fa fa-angle-up"></i>
</a>
</div>
</footer>
<!-- FOOTER END -->
</section>
<!-- JAVASCRIPT -->
<script type="text/javascript">
$(function() {
$("#table").dataTable({
"aoColumnDefs": [ { "bSortable": false, "aTargets": [ 0,3 ] } ],"aaSorting": []
});
});
</script>
<script type="text/javascript">
function checkMain(x) {
var checked = $(x).prop('checked');
$('.cbxMain').prop('checked', checked)
$('tr:visible').each(function () {
$(this).find('.chk_delete').each(function () {
this.checked = checked;
});
});
}
$(document).ready(function (){
$('.chk_delete').click(function () {
if ($('.chk_delete:checked').length == $('.chk_delete').length) {
$('.cbxMain').prop('checked', true);
}
else {
$('.cbxMain').prop('checked', false);
}
$('#check-all').click(function(){
$("input:checkbox").attr('checked', true);
});
});
$('.no-print').hide();
});
</script>
<!-- JAVASCRIPT END -->
</body>
</html>
<file_sep>/onlineshop/admin/register.php
<?php
include('connection.php');
include('registerfunction.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- TITLE -->
<title> TESDA Assesment Center </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- BOOTSTRAP AND CSS -->
<link href="../assets/css/style.css" rel="stylesheet">
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<link href="../assets/css/style-responsive.css" rel="stylesheet">
<!-- FONTS -->
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
</head>
<!-- ICON -->
<link rel="icon" type="image/png" href="../assets/images/TESDA Logo.png" />
<body>
<div id="login-page">
<div class="container">
<form class="form-login" action="" method="post">
<h2 class="form-login-heading"> REGISTER NOW </h2>
<div class="login-wrap">
<input type="hidden" class="form-control" value="Pending" name="status" readonly>
<br>
<label for=""><b> Enter Your First Name </b></label>
<input type="text" class="form-control" placeholder="First Name" name="firstname" required>
<br>
<label for=""><b> Enter Your Middle Name </b></label>
<input type="text" class="form-control" placeholder="Middle Name" name="middlename" required>
<br>
<label for=""><b> Enter Your Family Name </b></label>
<input type="text" class="form-control" placeholder="First Name" name="lastname" required>
<br>
<label for=""><b> Enter Your Email Address </b></label>
<input type="email" class="form-control" placeholder="Email Address" name="emailaddress" required>
<br>
<label for=""><b> Enter Your Username </b></label>
<input type="text" class="form-control" placeholder="Username" name="username" required>
<br>
<label for=""><b> Enter Your Password </b></label>
<input type="password" class="form-control" placeholder="<PASSWORD>" name="password" required>
<br><br>
<button class="btn btn-theme btn-block" name="register" type="submit"><i class="fa fa-lock"></i> REGISTER </button><br>
<a href="login.php"><button class="btn btn-theme btn-block"><i class="fa fa-lock"></i> SIGN IN </a></button>
</div>
</form>
<br><br><br><br>
</div>
</div>
<!-- JAVASCRIPT BACKSTRETCH -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/jquery.backstretch.min.js"></script>
<script>
$.backstretch("../assets/images/Login Background.jpg", {speed: 500});
</script>
</body>
</html>
<file_sep>/onlineshop/admin/calendar.php
<?php
session_start();
include('connection.php');
if (!isset($_SESSION['adminlogged'])) {
header("location:logout.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- TITLE -->
<title> TESDA Assesment Center </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- CASCADING STYLE SHEET -->
<link href="../assets/css/style.css" rel="stylesheet"/>
<link href="../assets/css/bootstrap.css" rel="stylesheet"/>
<link href="../assets/css/style-responsive.css" rel="stylesheet"/>
<link href="../assets/css/bootstrap.min.css" rel="stylesheet"/>
<link href="../assets/css/ionicons.min.css" rel="stylesheet" type="text/css" />
<link rel="stylesheet" type="text/css" href="../assets/css/lineicons/style.css"/>
<link rel="stylesheet" type="text/css" href="../assets/css/zabuto_calendar.css"/>
<link href="../assets/css/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<!-- FONTS -->
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<!-- JAVASCRIPT -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script src="../assets/js/common-scripts.js"></script>
<script src="../assets/js/jquery-1.8.3.min.js"></script>
<script src="../assets/js/chart-master/Chart.js"></script>
<script src="../assets/js/alert.js" type="text/javascript"></script>
<script src="../assets/js/jquery-1.12.3.js" type="text/javascript"></script>
<script src="../assets/js/jquery.nicescroll.js" type="text/javascript"></script>
<script src="../assets/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="../assets/js/dataTables.buttons.min.js" type="text/javascript"></script>
<script src="../assets/js/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<script src="../assets/js/plugins/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<script class="include" type="text/javascript" src="../assets/js/jquery.dcjqaccordion.2.7.js"></script>
</head>
<!-- ICON -->
<link rel="icon" type="image/png" href="../assets/images/TESDA Logo.png" />
<body>
<?php
ob_start();
include "connection.php";
?>
<section id="container" >
<header class="header black-bg">
<div class="sidebar-toggle-box">
<div class="fa fa-bars tooltips" data-placement="right" data-original-title="Toggle Navigation"></div>
</div>
<a href="index.php" class="logo"><b> TESDA ASSESMENT CENTER DASHBOARD </b></a>
<div class="nav notify-row" id="top_menu">
<!-- NOTIFICATION START -->
<ul class="nav top-menu">
<!-- PERCENTEGE DETAILS START -->
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="courses.php">
<i class="fa fa-tasks"></i>
<span class="badge bg-theme"><I></I>2</span>
</a>
<ul class="dropdown-menu extended tasks-bar">
<div class="notify-arrow notify-arrow-green"></div>
<li>
<p class="green"> PERCENTAGE DETAILS </p>
</li>
<li>
<a href="#">
<div class="task-info">
<div class="desc">Students Panel</div>
<div class="percent">40%</div>
</div>
<div class="progress progress-striped">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
</a>
</li>
<li>
<a href="#">
<div class="task-info">
<div class="desc">Programs & Services Panel</div>
<div class="percent">60%</div>
</div>
<div class="progress progress-striped">
<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">
<span class="sr-only">60% Complete (warning)</span>
</div>
</div>
</a>
</li>
<li class="external">
<a href="#"> See All Details </a>
</li>
</ul>
</li>
<!--PERCENTAGE DETAILS END -->
<!-- MESSAGES DROPDOWN START-->
<li id="header_inbox_bar" class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="courses.php">
<i class="fa fa-envelope-o"></i>
<span class="badge bg-theme">1</span>
</a>
<ul class="dropdown-menu extended inbox">
<div class="notify-arrow notify-arrow-green"></div>
<li>
<p class="green"> MESSAGES </p>
</li>
<li>
<a href="#">
<span class="photo"><img alt="avatar" src="../assets/images/Profile.png"></span>
<span class="subject">
<span class="from"> <NAME> </span>
<span class="time"> Just now </span>
</span>
<span class="message">
Hi Mate, How is Everything?
</span>
</a>
</li>
<li>
<a href="#"> See All Messages </a>
</li>
</ul>
</li>
<!-- MESSAGES DROPDOWN END -->
</ul>
<!-- NOTIFICATION END -->
</div>
<div class="top-menu">
<ul class="nav pull-right top-menu">
<li><a class="logout" href="logout.php"> Log Out </a></li>
</ul>
</div>
</header>
<!-- ** MAIN SIDEBAR MENU ** -->
<!-- SIDEBAR MENU START -->
<aside>
<div id="sidebar" class="nav-collapse ">
<!-- sidebar menu start-->
<ul class="sidebar-menu" id="nav-accordion">
<p class="centered"><a href="#"><img src="../assets/images/Profile.png" class="img-circle" width="60"></a></p>
<h5 class="centered"> WELCOME ADMIN!! </h5>
<li class="mt">
<a href="index.php">
<i class="fa fa-dashboard"></i>
<span> DASHBOARD </span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-group"></i>
<span> ADMIN PROFILING </span>
</a>
<ul class="sub">
<li><a href="adminprofiling.php"><i class="fa fa-user"> Accounts </i></li></a>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-group"></i>
<span> STUDENT PROFILING </span>
</a>
<ul class="sub">
<li><a href="studentsprofiling.php"><i class="fa fa-graduation-cap"> Students </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-book"></i>
<span> COURSES </span>
</a>
<ul class="sub">
<li><a class="active" href="courses.php"><i class="fa fa-briefcase"> Programs & Services </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-tasks"></i>
<span> RESULTS </span>
</a>
<ul class="sub">
<li><a href="results.php"><i class="fa fa-balance-scale"> Exam Results </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-calendar"></i>
<span> EVENT SCHEDULING </span>
</a>
<ul class="sub">
<li><a href="calendar.php"><i class="fa fa-calendar"> Calendar </i></a></li>
</ul>
</li>
</ul>
<!-- SIDEBAR MENU END -->
</div>
</aside>
<!-- *** MAIN CONTENT *** -->
<!-- MAIN CONTENT START -->
<section id="main-content">
<section class="wrapper">
<div class="row"><br><br>
<div class="col-lg-12"><center>
<div class="alert alert-dismissable alert-warning">
<button data-dismiss="alert" class="close" type="button">×</button>
Welcome In Calendar Panel, Admin!!
<br/>
</div></center>
</div>
</div>
<section id="main-content">
<section class="wrapper">
<h3><i class="fa fa-angle-right"></i> Calendar</h3>
<!-- page start-->
<div class="row mt">
<aside class="col-lg-3 mt">
<h4><i class="fa fa-angle-right"></i> Draggable Events</h4>
<div id="external-events">
<div class="external-event label label-theme">My Event 1</div>
<div class="external-event label label-success">My Event 2</div>
<div class="external-event label label-info">My Event 3</div>
<div class="external-event label label-warning">My Event 4</div>
<div class="external-event label label-danger">My Event 5</div>
<div class="external-event label label-default">My Event 6</div>
<div class="external-event label label-theme">My Event 7</div>
<div class="external-event label label-info">My Event 8</div>
<div class="external-event label label-success">My Event 9</div>
<p class="drop-after">
<input type="checkbox" id="drop-remove">
Remove After Drop
</p>
</div>
</aside>
<aside class="col-lg-9 mt">
<section class="panel">
<div class="panel-body">
<div idendar" class="has-toolbar"></div>
</div>
</section>
</aside>
</div>
<!-- page end-->
</section><! --/wrapper -->
</section><!-- /MAIN CONTENT -->
<br><br><br>
<!-- FOOTER START -->
<footer class="site-footer">
<div class="text-center">
ยฉ 2018 All Rights Reserved
<a href="calendar.php" class="go-top">
<i class="fa fa-angle-up"></i>
</a>
</div>
</footer>
<!-- FOOTER END -->
</section>
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/jquery-1.8.3.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script class="include" type="text/javascript" src="../assets/js/jquery.dcjqaccordion.2.7.js"></script>
<script src="../assets/js/jquery.scrollTo.min.js"></script>
<script src="../assets/js/jquery.nicescroll.js" type="text/javascript"></script>
<script src="../assets/js/jquery.sparkline.js"></script>
<script src="../assets/js/common-scripts.js"></script>
<script src="../assets/js/sparkline-chart.js"></script>
<script src="../assets/js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="../assets/js/dataTables.buttons.min.js" type="text/javascript"></script>
<script src="../assets/js/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<!-- JAVASCRIPT END -->
</body>
</html>
<file_sep>/onlineshop/admin/session.php
<?php
if (!isset($_SESSION['adminlogged'])) {
header("location:logout.php");
}
?><file_sep>/onlineshop/onlineshop.sql
-- phpMyAdmin SQL Dump
-- version 4.5.1
-- http://www.phpmyadmin.net
--
-- Host: 127.0.0.1
-- Generation Time: Nov 12, 2018 at 09:43 AM
-- Server version: 10.1.13-MariaDB
-- PHP Version: 5.5.35
SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!40101 SET NAMES utf8mb4 */;
--
-- Database: `onlineshop`
--
-- --------------------------------------------------------
--
-- Table structure for table `customer`
--
CREATE TABLE `customer` (
`accountnumber` int(100) NOT NULL,
`emailaddress` text NOT NULL,
`password` varchar(100) NOT NULL,
`firstname` varchar(100) NOT NULL,
`middlename` varchar(100) NOT NULL,
`familyname` varchar(100) NOT NULL,
`mobilenumber` int(100) NOT NULL,
`gender` varchar(100) NOT NULL,
`dateofbirth` date NOT NULL,
`placeofbirth` varchar(100) NOT NULL,
`address` varchar(100) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Indexes for dumped tables
--
--
-- Indexes for table `customer`
--
ALTER TABLE `customer`
ADD PRIMARY KEY (`accountnumber`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `customer`
--
ALTER TABLE `customer`
MODIFY `accountnumber` int(100) NOT NULL AUTO_INCREMENT;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
<file_sep>/onlineshop/user/login.php
<?php
include('connection.php');
include('loginfunction.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- TITLE -->
<title> Uniwards </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- BOOTSTRAP AND CSS -->
<link href="../assets/css/style.css" rel="stylesheet">
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<link href="../assets/css/style-responsive.css" rel="stylesheet">
<!-- FONTS -->
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
</head>
<!-- ICON -->
<link rel="icon" type="image/png" href="Images/UBP Logo.png" />
<body>
<div id="login-page">
<div class="container">
<form class="form-login" method="post" action="">
<h2 class="form-login-heading"> SIGN UP NOW </h2>
<div class="login-wrap">
<label for=""><b> Enter Your Account Number </b></label>
<input type="number" class="form-control" placeholder="Account Number" name="accountnumber" autofocus>
<br>
<label for=""><b> Enter Your Password </b></label>
<input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" required>
<br><br>
<label class="checkbox">
<span class="pull-center">
<center><a data-toggle="modal" href="Login#myModal"> Forgot Password? </a></center>
</span>
</label>
<button class="btn btn-theme btn-block" name="login" type="submit"><i class="fa fa-lock"></i> SIGN IN </button>
<hr>
<div class="registration">
Don't Have an Account Yet?<br/>
<a class="" href="register.php">
Create An Account
</a>
</div>
</div>
<!-- FORGET PASSWORD MODAL -->
<div aria-hidden="true" aria-labelledby="myModalLabel" role="dialog" tabindex="-1" id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Forgot Password ?</h4>
</div>
<div class="modal-body">
<p>Enter Your E-Mail Address Below To Reset Your Password.</p>
<input type="text" name="email" placeholder="Email" autocomplete="off" class="form-control placeholder-no-fix">
</div>
<div class="modal-footer">
<button data-dismiss="modal" class="btn btn-default" type="button">Cancel</button>
<button class="btn btn-theme" type="button">Submit</button>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
<!-- JAVASCRIPT BACKSTRETCH -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/jquery.backstretch.min.js"></script>
<script>
$.backstretch("../assets/images/Background.jpg", {speed: 500});
</script>
</body>
</html>
<file_sep>/onlineshop/admin/deletefunction.php
<!--============= DELETE FUNCTION PENDING ACCOUNTS ============ -->
<?php
if(isset($_POST['delete_admin_profiling']))
{
if(isset($_POST['chk_delete']))
{
foreach($_POST['chk_delete'] as $value)
{
$delete_query = mysqli_query($con,"DELETE from admin where firstname = '$value' ") or die('Error: ' . mysqli_error($con));
if($delete_query == true)
{
$_SESSION['delete'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
}
}
}
?>
<!--============= DELETE FUNCTION PENDING STUDENTS ============ -->
<?php
if(isset($_POST['delete_student_profiling']))
{
if(isset($_POST['chk_delete']))
{
foreach($_POST['chk_delete'] as $value)
{
$delete_query = mysqli_query($con,"DELETE from students where studentid = '$value' ") or die('Error: ' . mysqli_error($con));
if($delete_query == true)
{
$_SESSION['delete'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
}
}
}
?>
<!--============= DELETE FUNCTION COURSES ============ -->
<?php
if(isset($_POST['delete_course']))
{
if(isset($_POST['chk_delete']))
{
foreach($_POST['chk_delete'] as $value)
{
$delete_query = mysqli_query($con,"DELETE from courses where courseid = '$value' ") or die('Error: ' . mysqli_error($con));
if($delete_query == true)
{
$_SESSION['delete'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
}
}
}
?>
<!--============= DELETE FUNCTION COURSES ============ -->
<?php
if(isset($_POST['delete_exam_result']))
{
if(isset($_POST['chk_delete']))
{
foreach($_POST['chk_delete'] as $value)
{
$delete_query = mysqli_query($con,"DELETE from results where studentnumber = '$value' ") or die('Error: ' . mysqli_error($con));
if($delete_query == true)
{
$_SESSION['delete'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
}
}
}
?>
<file_sep>/README.md
# bois1nem
hackathon-ecommerce
this is a hackathon for NEM.
<file_sep>/onlineshop/admin/New folder/pendingmodal.php
<!-- == COURSE UPDATE MODAL ======== -->
<?php echo '<div id="pendingmodal'.$row['firstname'].'" class="modal fade">
<form method="post">
<div class="modal-dialog modal-sm" style="width:300px !important;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"> Update Status </h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<input type="hidden" value="'.$row['firstname'].'" name="firstname" id="firstname"/>
<div class="form-group">
<label> Status: </label>
<select name="status" id="status" class="form-control input-sm" value="'.$row['status'].'" />
<option> Pending </option>
<option> Approve </option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default btn-sm" data-dismiss="modal" value="Cancel"/>
<input type="submit" class="btn btn-primary btn-sm" name="btn_pen" value="Update"/>
</div>
</div>
</div>
</form>
</div>';?><file_sep>/onlineshop/admin/New folder/editfunction.php
<!-- ========= EDIT SCHOOLYEAR =========== -->
<?php
if(isset($_POST['btn_save']))
{
$txt_id = $_POST['hidden_id'];
$txt_edit_no = $_POST['txt_edit_no'];
$txt_edit_type = $_POST['txt_edit_type'];
$txt_edit_rf = $_POST['txt_edit_rf'];
$txt_edit_bn = $_POST['txt_edit_bn'];
$query = mysqli_query($con,"UPDATE apartment SET unit_no = '".$txt_edit_no."', unit_type = '".$txt_edit_type."', unit_rentfee = '".$txt_edit_rf."', unit_buildingname = '".$txt_edit_bn."' where id = '".$txt_id."' ");
if($query == true){
$_SESSION['edit'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
if(mysqli_error($con)){
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
<file_sep>/onlineshop/user/registerfunction.php
<?php
include('connection.php');
if (isset($_POST['register'])) {
$accountnumber = $_POST['accountnumber'];
$accounttype = $_POST['accounttype'];
$emailaddress = $_POST['emailaddress'];
$password = $_POST['password'];
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$familyname = $_POST['familyname'];
$mobilenumber = $_POST['mobilenumber'];
$gender = $_POST['gender'];
$dateofbirth = $_POST['dateofbirth'];
$placeofbirth = $_POST['placeofbirth'];
$address = $_POST['address'];
$sql = mysqli_query($con,"INSERT INTO customer (accountnumber,accounttype,emailaddress,password,firstname,middlename,familyname,mobilenumber,gender,dateofbirth,placeofbirth,address)
values ('".$accountnumber."','".$accounttype."','".$emailaddress."','".$password."','".$firstname."','".$middlename."','".$familyname."','".$mobilenumber."','".$gender."','".$dateofbirth."','".$placeofbirth."','".$address."')");
mysqli_query($con , $sql);
echo "<script>
alert(' Successfully Registered!!!');
</script>";
}
?>
<file_sep>/onlineshop/admin/updatefunction.php
<!-- ========= UPDATE COURSES FUNCTION =========== -->
<?php
if(isset($_POST['update_admin_profiling']))
{
$adminid = $_POST['adminid'];
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$familyname = $_POST['familyname'];
$emailaddress = $_POST['emailaddress'];
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$status = $_POST['status'];
$query = mysqli_query($con,"UPDATE admin SET firstname = '".$firstname."', middlename = '".$middlename."', familyname = '".$familyname."', emailaddress = '".$emailaddress."', username = '".$username."', password = '".$<PASSWORD>."', status = '".$status."' where firstname = '".$firstname."' ");
if($query == true){
$_SESSION['update'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
if(mysqli_error($con)){
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
<!-- ========= UPDATE COURSES FUNCTION =========== -->
<?php
if(isset($_POST['update_course']))
{
$courseid = $_POST['courseid'];
$coursenumber = $_POST['coursenumber'];
$coursename = $_POST['coursename'];
$courseobjective = $_POST['courseobjective'];
$coursedescription = $_POST['coursedescription'];
$coursemode = $_POST['coursemode'];
$courseduration = $_POST['courseduration'];
$query = mysqli_query($con,"UPDATE courses SET coursenumber = '".$coursenumber."', coursename = '".$coursename."', courseobjective = '".$courseobjective."', coursedescription = '".$coursedescription."', coursemode = '".$coursemode."', courseduration = '".$courseduration."' where courseid = '".$courseid."' ");
if($query == true){
$_SESSION['update'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
if(mysqli_error($con)){
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
<!-- ========= UPDATE COURSES FUNCTION =========== -->
<?php
if(isset($_POST['update_exam_result']))
{
$studentnumber = $_POST['resultid'];
$studentnumber = $_POST['studentnumber'];
$studentname = $_POST['studentname'];
$coursetaken = $_POST['coursetaken'];
$branch = $_POST['branch'];
$coursemode = $_POST['coursemode'];
$courseduration = $_POST['courseduration'];
$dateposted = $_POST['dateposted'];
$result = $_POST['result'];
$query = mysqli_query($con,"UPDATE results SET studentnumber = '".$studentnumber."', studentname = '".$studentname."', coursetaken = '".$coursetaken."', branch = '".$branch."', coursemode = '".$coursemode."', courseduration = '".$courseduration."', dateposted = '".$dateposted."', result = '".$result."' where resultid = '".$resultid."' ");
if($query == true){
$_SESSION['update'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
if(mysqli_error($con)){
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
<file_sep>/onlineshop/admin/index.php
<?php
session_start();
include('connection.php');
if (!isset($_SESSION['adminlogged'])) {
header("location:logout.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- TITLE -->
<title> TESDA Assesment Center </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- BOOTSTRAP AND CSS -->
<link href="../assets/css/style.css" rel="stylesheet">
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<link href="../assets/css/bootstrap.min.css" rel="stylesheet">
<link href="../assets/css/style-responsive.css" rel="stylesheet">
<link rel="stylesheet" type="text/css" href="../assets/css/lineicons/style.css">
<link rel="stylesheet" type="text/css" href="../assets/css/zabuto_calendar.css">
<link href="../assets/css/datatables/dataTables.bootstrap.css" rel="stylesheet" type="text/css" />
<!-- FONTS -->
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<!-- JAVASCRIPT -->
<script src="../assets/js/chart-master/Chart.js"></script>
</head>
<!-- ICON -->
<link rel="icon" type="image/png" href="../assets/images/TESDA Logo.png" />
<body>
<section id="container" >
<header class="header black-bg">
<div class="sidebar-toggle-box">
<div class="fa fa-bars tooltips" data-placement="right" data-original-title="Toggle Navigation"></div>
</div>
<a href="index.php" class="logo"><b> TESDA ASSESMENT CENTER DASHBOARD </b></a>
<div class="nav notify-row" id="top_menu">
<!-- NOTIFICATION START -->
<ul class="nav top-menu">
<!-- PERCENTEGE DETAILS START -->
<li class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="index.php">
<i class="fa fa-tasks"></i>
<span class="badge bg-theme"><I></I>2</span>
</a>
<ul class="dropdown-menu extended tasks-bar">
<div class="notify-arrow notify-arrow-green"></div>
<li>
<p class="green">PERCENTAGE DETAILS</p>
</li>
<li>
<a href="#">
<div class="task-info">
<div class="desc">Students Panel</div>
<div class="percent">40%</div>
</div>
<div class="progress progress-striped">
<div class="progress-bar progress-bar-success" role="progressbar" aria-valuenow="40" aria-valuemin="0" aria-valuemax="100" style="width: 40%">
<span class="sr-only">40% Complete (success)</span>
</div>
</div>
</a>
</li>
<li>
<a href="#">
<div class="task-info">
<div class="desc">Programs & Services Panel</div>
<div class="percent">60%</div>
</div>
<div class="progress progress-striped">
<div class="progress-bar progress-bar-warning" role="progressbar" aria-valuenow="60" aria-valuemin="0" aria-valuemax="100" style="width: 60%">
<span class="sr-only">60% Complete (warning)</span>
</div>
</div>
</a>
</li>
<li class="external">
<a href="#"> See All Details </a>
</li>
</ul>
</li>
<!--PERCENTAGE DETAILS END -->
<!-- MESSAGES DROPDOWN START-->
<li id="header_inbox_bar" class="dropdown">
<a data-toggle="dropdown" class="dropdown-toggle" href="index.php">
<i class="fa fa-envelope-o"></i>
<span class="badge bg-theme">1</span>
</a>
<ul class="dropdown-menu extended inbox">
<div class="notify-arrow notify-arrow-green"></div>
<li>
<p class="green"> MESSAGES </p>
</li>
<li>
<a href="#">
<span class="photo"><img alt="avatar" src="../assets/images/Profile.png"></span>
<span class="subject">
<span class="from"> <NAME> </span>
<span class="time"> Just now </span>
</span>
<span class="message">
Hi Mate, How is Everything?
</span>
</a>
</li>
<li>
<a href="#"> See All Messages </a>
</li>
</ul>
</li>
<!-- MESSAGES DROPDOWN END -->
</ul>
<!-- NOTIFICATION END -->
</div>
<div class="top-menu">
<ul class="nav pull-right top-menu">
<li><a class="logout" href="logout.php"> Log Out </a></li>
</ul>
</div>
</header>
<!-- ** MAIN SIDEBAR MENU ** -->
<!-- SIDEBAR MENU START -->
<aside>
<div id="sidebar" class="nav-collapse ">
<!-- sidebar menu start-->
<ul class="sidebar-menu" id="nav-accordion">
<p class="centered"><a href="#"><img src="../assets/images/Profile.png" class="img-circle" width="60"></a></p>
<h5 class="centered"> WELCOME ADMIN!! </h5>
<li class="mt">
<a href="index.php">
<i class="fa fa-dashboard"></i>
<span> DASHBOARD </span>
</a>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-group"></i>
<span> ADMIN PROFILING </span>
</a>
<ul class="sub">
<li><a href="adminprofiling.php"><i class="fa fa-user"> Accounts </i></li></a>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-group"></i>
<span> STUDENT PROFILING </span>
</a>
<ul class="sub">
<li><a href="studentsprofiling.php"><i class="fa fa-graduation-cap"> Students </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-book"></i>
<span> COURSES </span>
</a>
<ul class="sub">
<li><a class="active" href="courses.php"><i class="fa fa-briefcase"> Programs & Services </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-tasks"></i>
<span> RESULTS </span>
</a>
<ul class="sub">
<li><a href="results.php"><i class="fa fa-balance-scale"> Exam Results </i></a></li>
</ul>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-calendar"></i>
<span> EVENT SCHEDULING </span>
</a>
<ul class="sub">
<li><a href="calendar.php"><i class="fa fa-calendar"> Calendar </i></a></li>
</ul>
</li>
</ul>
<!-- SIDEBAR MENU END -->
</div>
</aside>
<!-- *** MAIN CONTENT *** -->
<!-- MAIN CONTENT START -->
<section id="main-content">
<section class="wrapper">
<div class="row">
<div class="col-lg-12"><center>
<h1> TESDA ASSESMENT CENTER </h1>
<div class="alert alert-dismissable alert-warning">
<button data-dismiss="alert" class="close" type="button">×</button>
Welcome In Our Dashboard, Admin!!
<br/>
</div></center>
</div>
</div>
<div class="row"><center>
<div class="col-lg-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-users"></i> NUMBER OF STUDENTS </h3>
</div>
<div class="panel-body">
<div id="shieldui-chart2">
<?php
$sql = "SELECT count(studentno) AS total FROM students";
$result = mysqli_query($con,$sql);
$values = mysqli_fetch_assoc($result);
$num_rows = $values['total'];
echo $num_rows;
?>
</div>
</div>
</div>
</div>
<div class="col-lg-4">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title"><i class="fa fa-briefcase"></i> NUMBER OF PROGRAMS & SERVICES </h3>
</div>
<div class="panel-body">
<div id="shieldui-chart2">
<?php
$sql = "SELECT count(coursenumber) AS total FROM courses";
$result = mysqli_query($con,$sql);
$values = mysqli_fetch_assoc($result);
$num_rows = $values['total'];
echo $num_rows;
?>
</div>
</div>
</div>
</div> </center>
</div>
<!-- BAR GRAPH START-->
<div class="row mt">
<div class="col-lg-10">
<div class="content-panel">
<div class="border-head">
<center><h2> MONTHLY VISITS </h2></center>
</div>
<div class="custom-bar-chart">
<ul class="y-axis">
<li><span>10.000</span></li>
<li><span>8.000</span></li>
<li><span>6.000</span></li>
<li><span>4.000</span></li>
<li><span>2.000</span></li>
<li><span>0</span></li>
</ul>
<div class="bar">
<div class="title"> JANUARY </div>
<div class="value tooltips" data-original-title="8.500" data-toggle="tooltip" data-placement="top">85%</div>
</div>
<div class="bar ">
<div class="title"> FEBRUARY </div>
<div class="value tooltips" data-original-title="5.000" data-toggle="tooltip" data-placement="top">50%</div>
</div>
<div class="bar ">
<div class="title"> MARCH </div>
<div class="value tooltips" data-original-title="6.000" data-toggle="tooltip" data-placement="top">60%</div>
</div>
<div class="bar ">
<div class="title"> APRIL </div>
<div class="value tooltips" data-original-title="4.500" data-toggle="tooltip" data-placement="top">45%</div>
</div>
<div class="bar">
<div class="title"> MAY </div>
<div class="value tooltips" data-original-title="3.200" data-toggle="tooltip" data-placement="top">32%</div>
</div>
<div class="bar ">
<div class="title"> JUNE </div>
<div class="value tooltips" data-original-title="6.200" data-toggle="tooltip" data-placement="top">62%</div>
</div>
<div class="bar">
<div class="title"> JULY </div>
<div class="value tooltips" data-original-title="7.500" data-toggle="tooltip" data-placement="top">75%</div>
</div>
</div>
</div>
</div>
</div>
<!-- BAR GRAPH ENDS -->
<br><br><br>
<!-- FOOTER START -->
<footer class="site-footer">
<div class="text-center">
ยฉ 2018 All Rights Reserved
<a href="index.php" class="go-top">
<i class="fa fa-angle-up"></i>
</a>
</div>
</footer>
<!-- FOOTER END -->
</section>
<!-- JAVASCRIPT -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/jquery-1.8.3.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script class="include" type="text/javascript" src="../assets/js/jquery.dcjqaccordion.2.7.js"></script>
<script src="../assets/js/jquery.scrollTo.min.js"></script>
<script src="../assets/js/jquery.nicescroll.js" type="text/javascript"></script>
<script src="../assets/js/jquery.sparkline.js"></script>
<script src="../assets/js/common-scripts.js"></script>
<script src="../assets/js/sparkline-chart.js"></script>
<!-- JAVASCRIPT END -->
</body>
</html>
<file_sep>/onlineshop/admin/loginfunction.php
<?php
session_start();
include('connection.php');
if (isset($_POST["login"])) {
$username = $_POST['emailaddress'];
$password = $_POST['<PASSWORD>'];
$sql = "SELECT * FROM admin WHERE username = '$username' and password = '$<PASSWORD>'";
$sql = mysqli_query($con , $sql);
if (mysqli_num_rows($sql) !=0) {
$_SESSION['adminlogged'] = $username;
header("location:index.php.");
}
else {
echo "Account Doesn't Exist!";
}
}
?><file_sep>/onlineshop/admin/notification.php
<?php if(isset($_SESSION['added'])){
echo '<script>$(document).ready(function (){save_success();});</script>';
unset($_SESSION['added']);
echo '<div class="alert alert-success alert-autocloseable-add" style=" position: fixed; top: 1em; right: 1em; z-index: 9999; display: none;">
Successfully Added!
</div>';
}
?>
<?php if(isset($_SESSION['update'])){
echo '<script>$(document).ready(function (){editsuccess();});</script>';
unset($_SESSION['update']);
echo '<div class="alert alert-success alert-autocloseable-editsuccess" style=" position: fixed; top: 1em; right: 1em; z-index: 9999; display: none;">
Updated Value Saved!
</div>';
}
?>
<?php if(isset($_SESSION['delete'])){
echo '<script>$(document).ready(function (){deleted();});</script>';
unset($_SESSION['delete']);
echo '<div class="alert alert-danger alert-autocloseable-danger" style=" position: fixed; top: 1em; right: 1em; z-index: 9999; display: none;">
Successfully Deleted!
</div>';
}
?>
<file_sep>/onlineshop/user/exam.php
<?php
session_start();
include('../admin/connection.php');
if (!isset($_SESSION['userlogged'])) {
header("location:../logout.php");
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- TITLE -->
<title> TESDA Assesment Center </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- BOOTSTRAP AND CSS -->
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
<link rel="stylesheet" type="text/css" href="../assets/css/zabuto_calendar.css">
<link rel="stylesheet" type="text/css" href="../assets/lineicons/style.css">
<link href="../assets/css/style.css" rel="stylesheet">
<link href="../assets/css/style-responsive.css" rel="stylesheet">
<script src="../assets/js/chart-master/Chart.js"></script>
</head>
<!-- ICON -->
<link rel="icon" type="image/png" href="../assets/images/TESDA Logo.png" />
<body>
<section id="container" >
<header class="header black-bg">
<div class="sidebar-toggle-box">
<div class="fa fa-bars tooltips" data-placement="right" data-original-title="Toggle Navigation"></div>
</div>
<a href="index.html" class="logo"><b> TESDA </b></a>
<div class="nav notify-row" id="top_menu">
</div>
<div class="top-menu">
<ul class="nav pull-right top-menu">
<li><a class="logout" href="../admin/logout.php"> Log Out </a></li>
</ul>
</div>
</header>
<!-- ** MAIN SIDEBAR MENU ** -->
<!-- SIDEBAR MENU START -->
<aside>
<div id="sidebar" class="nav-collapse ">
<!-- sidebar menu start-->
<ul class="sidebar-menu" id="nav-accordion">
<p class="centered"><a href="#"><img src="../assets/images/Profile.png" class="img-circle" width="60"></a></p>
<h5 class="centered"> WELCOME! <br>
<?php
echo $_SESSION['userlogged'];
?></h5>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-group"></i>
<span> PROFILE </span>
</a>
<ul class="sub">
<li><a href="usersubj.php"><i class="fa fa-graduation-cap"> Subjects </i></li></a>
</ul>
</li>
</li>
<li class="sub-menu">
<a href="javascript:;" >
<i class="fa fa-tasks"></i>
<span> EXAM RESULTS </span>
</a>
<ul class="sub">
<li><a href="exam.php"><i class="fa fa-balance-scale"> Exam Results </i></a></li>
</ul>
</li>
<!-- SIDEBAR MENU END -->
</div>
</aside>
<!-- *** MAIN CONTENT *** -->
<!-- MAIN CONTENT START -->
<section id="main-content">
<section class="wrapper">
<div class="row">
<div class="col-lg-12"><center>
<h1> EXAM </h1>
<div class="alert alert-dismissable alert-warning">
EXAM RESULT
<br/>
</div></center>
</div>
</div>
</div>
<?php
include('examresult.php');
?>
<br><br><br>
<!-- BODY START -->
<!-- FOOTER START -->
<footer class="site-footer">
<div class="text-center">
ยฉ 2018 All Rights Reserved
</div>
</footer>
<!-- FOOTER END -->
</section>
<!-- JAVASCRIPT -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/jquery-1.8.3.min.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script class="include" type="text/javascript" src="../assets/js/jquery.dcjqaccordion.2.7.js"></script>
<script src="../assets/js/jquery.scrollTo.min.js"></script>
<script src="../assets/js/jquery.nicescroll.js" type="text/javascript"></script>
<script src="../assets/js/jquery.sparkline.js"></script>
<script src="../assets/js/common-scripts.js"></script>
<script src="../assets/js/sparkline-chart.js"></script>
<!-- JAVASCRIPT END -->
</body>
</html>
<file_sep>/onlineshop/user/register.php
<?php
include('connection.php');
include('registerfunction.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<!-- TITLE -->
<title> Uniwards </title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- BOOTSTRAP AND CSS -->
<link href="../assets/css/style.css" rel="stylesheet">
<link href="../assets/css/bootstrap.css" rel="stylesheet">
<link href="../assets/css/style-responsive.css" rel="stylesheet">
<!-- FONTS -->
<link href="../assets/font-awesome/css/font-awesome.css" rel="stylesheet" />
</head>
<!-- ICON -->
<link rel="icon" type="image/png" href="../assets/images/UBP Logo.png" />
<body>
<div id="login-page">
<div class="container">
<form class="form-login" action="" method="post">
<h2 class="form-login-heading"> REGISTER NOW </h2>
<div class="login-wrap">
<label for=""><b> Your Account Number </b></label>
<input type="number" class="form-control" placeholder="Account Number" name="accountnumber" autofocus="">
<br>
<label for=""><b> Account Type </b></label>
<select name="accounttype" class="form-control" placeholder="Account Type" required>
<option value=""></option>
<option value="Debit Card"> Debit Card </option>
<option value="Credit Card"> Credit Card </option>
</select>
<br>
<label for=""><b> Enter Your Email Address </b></label>
<input type="email" class="form-control" placeholder="Email Address" name="emailaddress" required="">
<br>
<label for=""><b> Enter Your Password </b></label>
<input type="<PASSWORD>" class="form-control" placeholder="<PASSWORD>" name="password" required>
<br>
<label for=""><b> Enter Your First Name </b></label>
<input type="text" class="form-control" placeholder="First Name" name="firstname" required>
<br>
<label for=""><b> Enter Your Middle Name </b></label>
<input type="text" class="form-control" placeholder="Middle Name" name="middlename" required>
<br>
<label for=""><b> Enter Your Family Name </b></label>
<input type="text" class="form-control" placeholder="Family Name" name="familyname" required>
<br>
<label for=""><b> Enter Your Mobile Number </b></label>
<input type="number" class="form-control" placeholder="Mobile Number" name="mobilenumber" required>
<br>
<label for=""><b> Enter Your Gender </b></label>
<select name="gender" class="form-control" placeholder="Gender" required>
<option value=""></option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
<br>
<label for=""><b> Enter Your Date of Birth </b></label>
<input type="date" class="form-control" placeholder="Date of Birth" name="dateofbirth" required>
<br>
<label for=""><b> Enter Your Place of Birth </b></label>
<input type="text" class="form-control" placeholder="Place of Birth" name="placeofbirth" required>
<br>
<label for=""><b> Enter Your Address </b></label>
<input type="text" class="form-control" placeholder="Address" name="address" required>
<br>
<button class="btn btn-theme btn-block" name="register" type="submit"><i class="fa fa-lock"></i> REGISTER </button><br>
<a href="login.php"><button class="btn btn-theme btn-block"><i class="fa fa-lock"></i> SIGN IN </a></button>
</div>
</form>
<br><br><br><br>
</div>
</div>
<!-- JAVASCRIPT BACKSTRETCH -->
<script src="../assets/js/jquery.js"></script>
<script src="../assets/js/bootstrap.min.js"></script>
<script type="text/javascript" src="../assets/js/jquery.backstretch.min.js"></script>
<script>
$.backstretch("../assets/images/Background.jpg", {speed: 500});
</script>
</body>
</html>
<file_sep>/onlineshop/admin/footer.php
<!-- Bootstrap -->
<script src="../../../../js/alert.js" type="text/javascript"></script>
<script src="../../../../js/bootstrap.min.js" type="text/javascript"></script>
<script src="../../../../js/jquery.dataTables.min.js" type="text/javascript"></script>
<script src="../../../../js/dataTables.buttons.min.js" type="text/javascript"></script>
<script src="../../../../js/plugins/datatables/dataTables.bootstrap.js" type="text/javascript"></script>
<script type="text/javascript">
function checkMain(x) {
var checked = $(x).prop('checked');
$('.cbxMain').prop('checked', checked)
$('tr:visible').each(function () {
$(this).find('.chk_delete').each(function () {
this.checked = checked;
});
});
}
function editsuccess(){
$('#autoclosable-btn-editsuccess').prop('disabled', true);
$('.alert-autocloseable-editsuccess').show();
$('.alert-autocloseable-editsuccess').delay(3000).fadeOut( 'slow', function() {
// Animation complete.
$('#autoclosable-btn-editsuccess').prop('disabled', false);
});
}
function save_success(){
$('#autoclosable-btn-add').prop('disabled', true);
$('.alert-autocloseable-add').show();
$('.alert-autocloseable-add').delay(3000).fadeOut( 'slow', function() {
// Animation complete.
$('#autoclosable-btn-add').prop('disabled', false);
});
}
function deleted(){
$('#autoclosable-btn-danger').prop('disabled', true);
$('.alert-autocloseable-danger').show();
$('.alert-autocloseable-danger').delay(3000).fadeOut( 'slow', function() {
// Animation complete.
$('#autoclosable-btn-danger').prop('disabled', false);
});
}
function duplicate(){
$('#autoclosable-btn-duplicate').prop('disabled', true);
$('.alert-autocloseable-duplicate').show();
$('.alert-autocloseable-duplicate').delay(3000).fadeOut( 'slow', function() {
// Animation complete.
$('#autoclosable-btn-duplicate').prop('disabled', false);
});
}
</script>
<!-- page script -->
<file_sep>/onlineshop/admin/updatestudentprofiling.php
<!-- == COURSE UPDATE MODAL ======== -->
<?php echo '<div id="updatestudentprofiling'.$row['studentid'].'" class="modal fade">
<form method="post">
<div class="modal-dialog modal-sm" style="width:300px !important;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"> Update Student Profiing </h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<input type="hidden" value="'.$row['studentid'].'" name="studentid" id="studentid"/>
<div class="form-group">
<label> Enter Updated Student Number: </label>
<input name="studentno" id="studentno" class="form-control input-sm" type="number" value="'.$row['studentno'].'" />
</div>
<div class="form-group">
<label> Enter Updated Password: </label>
<input name="password" id="password" class="form-control input-sm" type="password" value="'.$row['password'].'" />
</div>
<div class="form-group">
<label> Enter Updated Course Taken: </label>
<select name="course" id="course" class="form-control input-sm" value="'.$row['course'].'" />
<option> Agricuture </option>
<option> Automotive </option>
<option> Communication Technoogy </option>
<option> Electronics </option>
<option> Entrepreneurship </option>
<option> Human Helath Care </option>
<option> Lifelong Learning Skills </option>
<option> Maritime </option>
<option> Tourism </option>
</select>
</div>
<div class="form-group">
<label> Enter Updated First Name: </label>
<input name="firstname" id="firstname" class="form-control input-sm" type="text" value="'.$row['firstname'].'" />
</div>
<div class="form-group">
<label> Enter Updated Middle Name: </label>
<input name="middlename" id="middlename" class="form-control input-sm" type="text" value="'.$row['middlename'].'" />
</div>
<div class="form-group">
<label> Enter Updated Family Name: </label>
<input name="familyname" id="familyname" class="form-control input-sm" type="text" value="'.$row['familyname'].'" />
</div>
<div class="form-group">
<label> Enter Updated Age: </label>
<input name="age" id="age" class="form-control input-sm" type="number" value="'.$row['age'].'" />
</div>
<div class="form-group">
<label> Enter Updated Gender: </label>
<select name="gender" id="gender" class="form-control input-sm" value="'.$row['gender'].'" />
<option> Male </option>
<option> Female </option>
</select>
</div>
<div class="form-group">
<label> Enter Updated Religiom: </label>
<input name="religion" id="religion" class="form-control input-sm" type="text" value="'.$row['religion'].'" />
</div>
<div class="form-group">
<label> Enter Updated Citizenship: </label>
<input name="citizenship" id="citizenship" class="form-control input-sm" type="email" value="'.$row['citizenship'].'" />
</div>
<div class="form-group">
<label> Enter Updated Civil Status: </label>
<select name="civilstatus" id="civilstatus" class="form-control input-sm" value="'.$row['civilstatus'].'" />
<option> Single </option>
<option> Married </option>
<option> Widowed </option>
<option> Separated </option>
</select>
</div>
<div class="form-group">
<label> Enter Updated Date Of Birth: </label>
<input name="dateofbirth" id="dateofbirth" class="form-control input-sm" type="date" value="'.$row['dateofbirth'].'" />
</div>
<div class="form-group">
<label> Enter Updated Place Of Birth: </label>
<input name="placeofbirth" id="placeofbirth" class="form-control input-sm" type="text" value="'.$row['placeofbirth'].'" />
</div>
<div class="form-group">
<label> Enter Updated Contact Number: </label>
<input name="contactno" id="contactno" class="form-control input-sm" type="date" value="'.$row['contactno'].'" />
</div>
<div class="form-group">
<label> Enter Updated Address: </label>
<input name="address" id="address" class="form-control input-sm" type="text" value="'.$row['address'].'" />
</div>
<div class="form-group">
<label> Enter Updated Email Address: </label>
<input name="emailaddress" id="emailaddress" class="form-control input-sm" type="email" value="'.$row['emailaddress'].'" />
</div>
<div class="form-group">
<label> Enter Updated Status: </label>
<select name="status" id="status" class="form-control input-sm" value="'.$row['status'].'" />
<option> Approved </option>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default btn-sm" data-dismiss="modal" value="Cancel"/>
<input type="submit" class="btn btn-primary btn-sm" name="update_student_profiling" value="Update Course"/>
</div>
</div>
</div>
</form>
</div>';?>
<file_sep>/onlineshop/admin/New folder/editmodal.php
<!-- ========= YEARLEVEL MODAL ======== -->
<?php echo '<div id="editModal'.$row['courseid'].'" class="modal fade">
<form method="post">
<div class="modal-dialog modal-sm" style="width:300px !important;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Edit Apartment Unit</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<input type="hidden" value="'.$row['courseid'].'" name="courseid" id="courseid"/>
<div class="form-group">
<label>Edit Course Number: </label>
<input name="coursenumber" id="coursenumber" class="form-control input-sm" type="text" value="'.$row['coursenumber'].'" />
</div>
<div class="form-group">
<label>Edit Course Name: </label>
<select name="coursename" id="coursename" class="form-control input-sm" value="'.$row['coursename'].'" />
<option>Agriculture</option>
<option>Automotive</option>
<option>Communication Technology</option>
<option>Electronics</option>
<option>Entrepreneurship</option>
<option>Human Health Care</option>
</select>
</div>
<div class="form-group">
<label>Edit Course Objective: </label>
<input name="courseobjective" class="form-control input-sm" type="text" value="'.$row['courseobjective'].'" />
</div>
<div class="form-group">
<label>Edit Course Description: </label>
<input name="coursedescription" class="form-control input-sm" type="text" value="'.$row['coursedescription'].'" />
</div>
<div class="form-group">
<label>Edit Course Mode: </label>
<select name="coursemode" id="coursemode" class="form-control input-sm" value="'.$row['coursemode'].'" />
<option>Online</option>
<option>Offline</option>
</select>
</div>
<div class="form-group">
<label>Edit Course Duration: </label>
<select name="courseduration" id="courseduration" class="form-control input-sm" value="'.$row['courseduration'].'" />
<option>3 Months</option>
<option>6 Months</option>
<option>9 Months</option>
<option>1 Year</option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default btn-sm" data-dismiss="modal" value="Cancel"/>
<input type="submit" class="btn btn-primary btn-sm" name="btn_save" value="Save"/>
</div>
</div>
</div>
</form>
</div>';?>7:55 AM 17/03/2018<file_sep>/onlineshop/admin/updatemodalresult.php
<!-- == COURSE UPDATE MODAL ======== -->
<?php echo '<div id="updateexamresult'.$row['studentnumber'].'" class="modal fade">
<form method="post">
<div class="modal-dialog modal-sm" style="width:300px !important;">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title"> Update Exam Result </h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-12">
<input type="hidden" value="'.$row['resultid'].'" name="resultid" id="resultid"/>
<div class="form-group">
<label> Enter Updated Student Number: </label>
<input name="studentnumber" id="studentnumber" class="form-control input-sm" type="number" value="'.$row['studentnumber'].'" />
</div>
<div class="form-group">
<label> Enter Updated Student Name: </label>
<input name="studentname" id="studentname" class="form-control input-sm" type="text" value="'.$row['studentname'].'" />
</div>
<div class="form-group">
<label> Enter Updated Course Name: </label>
<select name="coursetaken" id="coursetaken" class="form-control input-sm" value="'.$row['coursetaken'].'" />
<option> Agricuture </option>
<option> Automotive </option>
<option> Communication Technoogy </option>
<option> Electronics </option>
<option> Entrepreneurship </option>
<option> Human Helath Care </option>
<option> Lifelong Learning Skills </option>
<option> Maritime </option>
<option> Tourism </option>
</select>
</div>
<div class="form-group">
<label> Enter Your Chosen Branch:</label>
<select name="branch" id="branch" class="form-control input-sm" value="'.$row['branch'].'" />
<option> Cubao </option>
<option> Fairview </option>
<option> Novailches </option>
</select>
</div>
<div class="form-group">
<label>Enter Your Course Mode:</label>
<select name="coursemode" id="coursemode" class="form-control input-sm" value="'.$row['coursemode'].'" />
<option> Online </option>
<option> Offine </option>
</select>
</div>
<div class="form-group">
<label>Enter Your Course Duration:</label>
<select name="courseduration" id="courseduration" class="form-control input-sm" value="'.$row['courseduration'].'" />
<option> 3 Months </option>
<option> 6 Months </option>
<option> 9 Months </option>
<option> 1 Year </option>
</select>
</div>
<div class="form-group">
<label><b> Enter Your Date Posted: </b></label>
<input name="dateposted" id="dateposted" class="form-control input-sm" type="date" value="'.$row['dateposted'].'" />
</div>
<div class="form-group">
<label> Enter Your Result: </label>
<select name="result" id="result" class="form-control input-sm" value="'.$row['result'].'" />
<option> Passed </option>
<option> Failed </option>
</select>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<input type="button" class="btn btn-default btn-sm" data-dismiss="modal" value="Cancel"/>
<input type="submit" class="btn btn-primary btn-sm" name="update_exam_result" value="Update Course"/>
</div>
</div>
</div>
</form>
</div>';?>
<file_sep>/onlineshop/admin/registerfunction.php
<?php
include('connection.php');
if (isset($_POST['register'])) {
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$familyname = $_POST['familyname'];
$emailaddress = $_POST['emailaddress'];
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$status = $_POST['status'];
$sql = "INSERT INTO admin (firstname , middlename , familyname , emailaddress , username , password , status)
VALUES ('$firstname' , '$middlename', '$familyname', '$emailaddress', '$username', '$password', '$status')";
mysqli_query($con , $sql);
echo "<script>
alert(' Successfully Registered!!!');
</script>";
}
?>
<file_sep>/onlineshop/user/session.php
<?php
if (!isset($_SESSION['userlogged'])) {
header("location:logout.php");
}
?><file_sep>/onlineshop/admin/New folder/pendingfunction.php
<!-- ========= UPDATE COURSES FUNCTION =========== -->
<?php
if(isset($_POST['btn_pen']))
{
$studentid = $_POST['studentid'];
$status = $_POST['status'];
$query = mysqli_query($con,"UPDATE courses SET status = '".$status."' where studentid = '".$studentid."' ");
if($query == true){
$_SESSION['update'] = 1;
header("location: ".$_SERVER['REQUEST_URI']);
}
if(mysqli_error($con)){
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
<file_sep>/onlineshop/admin/addfunction.php
<!-- ========= ADD MODAL PENDING ACCOUNTS ============== -->
<?php
if(isset($_POST['add_admin_profiling'])){
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$familyname = $_POST['familyname'];
$emailaddress = $_POST['emailaddress'];
$username = $_POST['username'];
$password = $_POST['<PASSWORD>'];
$status = $_POST['status'];
$chk = mysqli_query($con,"SELECT * from admin where firstname = '$firstname',middlename = '$middlename',familyname = '$familyname',emailaddress = '$emailaddress',username = '$username',password = <PASSWORD>' and status = '$status' ");
$ct = mysqli_num_rows($chk);
if($ct == 0){
$query = mysqli_query($con,"INSERT INTO admin (firstname,middlename,familyname,emailaddress,username,password,status)
values ('".$firstname."','".$middlename."','".$familyname."','".$emailaddress."','".$username."','".$password."','".$status."')");
if($query == true){
$_SESSION['added'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
else{
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
<!-- ========= ADD MODAL PENDING STUUDENTS ============== -->
<?php
if(isset($_POST['add_student_profiling'])){
$studentno = $_POST['studentno'];
$password = $_POST['<PASSWORD>'];
$course = $_POST['course'];
$branch = $_POST['branch'];
$firstname = $_POST['firstname'];
$middlename = $_POST['middlename'];
$familyname = $_POST['familyname'];
$age = $_POST['age'];
$gender = $_POST['gender'];
$religion = $_POST['religion'];
$citizenship = $_POST['citizenship'];
$civilstatus = $_POST['civilstatus'];
$dateofbirth = $_POST['dateofbirth'];
$placeofbirth = $_POST['placeofbirth'];
$contactno = $_POST['contactno'];
$address = $_POST['address'];
$emailaddress = $_POST['emailaddress'];
$status = $_POST['status'];
$chk = mysqli_query($con,"SELECT * from students where studentno = '$studentno',password = '$<PASSWORD>',course = '$course',branch = '$branch',firstname = '$firstname',middlename = '$middlename',familyname = '$familyname',age = '$age',gender = '$gender',religion = '$'religion,citizenship = '$citizenship',civilstatus = '$civilstatus',dateofbirth = '$dateofbirth',placeofbirth = '$placeofbirth',contactno = '$contactno',address = '$address', emailaddress = '$emailaddress', and status = '$status' ");
$ct = mysqli_num_rows($chk);
if($ct == 0){
$query = mysqli_query($con,"INSERT INTO students (studentno,password,course,branch,firstname,middlename,familyname,age,gender,religion,citizenship,civilstatus,dateofbirth,placeofbirth,contactno,address,emaiaddress,status)
values ('".$studentno."','".$password."','".$course."','".$branch."','".$firstname."','".$middlename."','".$familyname."','".$age."','".$gender."','".$religion."','".$citizenship."','".$civilstatus."','".$dateofbirth."','".$placeofbirth."','".$contactno."','".$address."','".$emailaddress."','".$status."')");
if($query == true){
$_SESSION['added'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
else{
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
<!-- ========= ADD MODAL COUURSE ============== -->
<?php
if(isset($_POST['add_course'])){
$coursenumber = $_POST['coursenumber'];
$coursename = $_POST['coursename'];
$courseobjective = $_POST['courseobjective'];
$coursedescription = $_POST['coursedescription'];
$coursemode = $_POST['coursemode'];
$courseduration = $_POST['courseduration'];
$chk = mysqli_query($con,"SELECT * from courses where coursenumber = '$coursenumber',coursename = '$coursename',courseobjective = '$courseobjective',coursedescription = '$coursedescription',coursemode = '$coursemode' and courseduration = '$courseduration' ");
$ct = mysqli_num_rows($chk);
if($ct == 0){
$query = mysqli_query($con,"INSERT INTO courses (coursenumber,coursename,courseobjective,coursedescription,coursemode,courseduration)
values ('".$coursenumber."','".$coursename."','".$courseobjective."','".$coursedescription."','".$coursemode."','".$courseduration."')");
if($query == true){
$_SESSION['added'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
else{
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
<!-- ========= ADD MODAL RESULTS ============== -->
<?php
if(isset($_POST['add_exam_result'])){
$studentnumber = $_POST['studentnumber'];
$studentname = $_POST['studentname'];
$coursetaken = $_POST['coursetaken'];
$branch = $_POST['branch'];
$coursemode = $_POST['coursemode'];
$courseduration = $_POST['courseduration'];
$dateposted = $_POST['dateposted'];
$result = $_POST['result'];
$chk = mysqli_query($con,"SELECT * from results where studentnumber = '$studentnumber',studentname = '$studentname',coursetaken = '$coursetaken',branch = '$branch',coursemode = '$coursemode',courseduration = '$courseduration', dateposted = '$dateposted' and result = '$result'");
$ct = mysqli_num_rows($chk);
if($ct == 0){
$query = mysqli_query($con,"INSERT INTO results (studentnumber,studentname,coursetaken,branch,coursemode,courseduration,dateposted,result)
values ('".$studentnumber."','".$studentname."','".$coursetaken."','".$branch."','".$coursemode."','".$courseduration."','".$dateposted."','".$result."')");
if($query == true){
$_SESSION['added'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
else{
$_SESSION['duplicate'] = 1;
header ("location: ".$_SERVER['REQUEST_URI']);
}
}
?>
|
f2d27b8fb3b63e5d85b8ec57a4e31eb73f26c469
|
[
"Markdown",
"SQL",
"PHP"
] | 29 |
PHP
|
gabzaide/bois1nem
|
8b586a2b00b3aff744f9d941f877861ffcd65b82
|
236db9958ad1f5b1febfb9c43d179aa27004005e
|
refs/heads/master
|
<repo_name>fleishma2363/CTI110<file_sep>/README.md
# CTI 110 Repository
Created for P2LAB1
<NAME>
2/13/2018
<file_sep>/P2HW1_DistanceTraveled_Fleishman.py
speed = 70
print ( " in 6 hours, the car will tarvel " + str ( ( speed * 6) ) + " miles " )
print ( " in 10 hours, the car will travel " + str ( ( speed * 10) ) + " mile " )
print ( " in 15 hours, the car will travel " + str ( ( speed * 15) ) + " mile" )
<file_sep>/P2T1_SalesPrediction_Fleishman.py
print("CTI110")
print("P2T1-Sales Prediction")
print("<NAME>")
print("2/16/18")
projectedTotalSales = float (input("Please enter the projected amount" + \
"of total sales: ") )
profit = 0.23 * projectedTotalSales
print( "The profit is $" + format( profit, ",.2f"))
<file_sep>/P1T1_AaronFleishman.py
# P1T1
# Hello world
# <NAME>
# 2/12/2018
print ('Hello world')
<file_sep>/P2HW2_TIp,Tax,Total_Fleishman.py
foodCharge = float( input( "Please enterr the charge of the food: " ) )
tip = 0.18 * foodCharge
salesTax = 0.07 * foodCharge
total = foodCharge + tip + salesTax
print( "Food Charge: $" + format( foodCharge, ",.2f"), "Tip: $" + \
format( tip, ",.2f"), "Sales Tax: $" + format( salesTax, ",.2f"), \
"Total: $" + format( total, ",.2f"), sep = "\n" )
|
3e6d31ac54f068c34c02c576865489bc182e6196
|
[
"Markdown",
"Python"
] | 5 |
Markdown
|
fleishma2363/CTI110
|
0c8d3a0de903d1c4afc75a2bd9504195886a9fba
|
48c65616ddc65ecdb920c82eceab83ad40cb08da
|
refs/heads/main
|
<repo_name>Acidburn0zzz/finnix-live-build<file_sep>/hooks/5000-finnix-1000-diskinfo.hook.binary.in
#!/bin/sh
set -e
# This replaces live-build's file (which always says Debian but
# conflates our VERSION)
cat <<"EOM" >.disk/info
{{ PRODUCT }} {{ VERSION }}{% if VERSION == 'dev' %} ({{ DATETIME }}{% if GIT_DESC %} {{ GIT_DESC }}{% endif %}){% endif %}
EOM
# This is specific to finnix-live-build
cat <<"EOM" >.disk/build_info
PRODUCT="{{ PRODUCT }}"
PRODUCT_ID="{{ PRODUCT_ID }}"
VERSION="{{ VERSION }}"
CODENAME="{{ CODENAME }}"
ARCH="{{ ARCH }}"
DATETIME="{{ DATETIME }}"
GIT_DESC="{{ GIT_DESC }}"
LIVE_BUILD_GIT_DESC="{{ LIVE_BUILD_GIT_DESC }}"
EOM
<file_sep>/hooks/0005-finnix-1000-machine-id.hook.chroot.in
#!/bin/sh
# live-build hook positioning doesn't really matter on this;
# update-initramfs has almost certainly run before this, but is
# guaranteed to run after the hooks.
set -e
mkdir -p /etc/initramfs-tools/scripts/live-bottom
cat <<"EOM" >/etc/initramfs-tools/scripts/live-bottom/machine-id
#!/bin/sh
set -e
PREREQS=""
rootmnt="${rootmnt:-}" # Set by initrd environment
prereqs() { echo "$PREREQS"; }
case "$1" in
prereqs)
prereqs
exit 0
;;
esac
is_usable_product_uuid() {
[ -e /sys/class/dmi/id/sys_vendor ] || return 1
[ -e /sys/class/dmi/id/product_uuid ] || return 1
[ "$(cat /sys/class/dmi/id/sys_vendor)" = "QEMU" ] || return 1
return 0
}
rm -f "${rootmnt}/etc/machine-id"
if is_usable_product_uuid; then
# We can trust these vendors' product_uuid to be decent.
sed -e 's/-//g' </sys/class/dmi/id/product_uuid >"${rootmnt}/etc/machine-id"
elif [ -e /sys/firmware/dmi/tables/DMI ]; then
# product_uuid is available, but isn't guaranteed to be decent on
# all systems, so let's just hash the entire DMI.
# Note that this isn't wise on a permanent machine, as it's
# possible two exact machines (with broken vendor UUIDs/serials)
# could have the exact same DMI, but it's fine in a live
# environment.
md5sum /sys/firmware/dmi/tables/DMI | cut -d' ' -f1 >"${rootmnt}/etc/machine-id"
elif [ -e /proc/sys/kernel/random/boot_id ]; then
# Kernel boot ID (random per-boot)
sed -e 's/-//g' </proc/sys/kernel/random/boot_id >"${rootmnt}/etc/machine-id"
else
# Random ID
sed -e 's/-//g' </proc/sys/kernel/random/uuid >"${rootmnt}/etc/machine-id"
fi
rm -f "${rootmnt}/var/lib/dbus/machine-id"
mkdir -p "${rootmnt}/var/lib/dbus"
ln -s /etc/machine-id "${rootmnt}/var/lib/dbus/machine-id"
EOM
chmod 0755 /etc/initramfs-tools/scripts/live-bottom/machine-id
<file_sep>/hooks/0005-finnix-0100-systemd.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
# Set up our custom target
cat <<"EOM" >"/etc/systemd/system/${PRODUCT_ID}.target"
[Unit]
Description={{ PRODUCT }} System
Requires=basic.target
Conflicts=rescue.service rescue.target
After=basic.target rescue.service rescue.target
AllowIsolate=yes
EOM
systemctl set-default "${PRODUCT_ID}.target"
# Clear unwanted targets below our custom target
for target in basic.target sysinit.target timers.target default.target network.target network-online.target multi-user.target graphical.target; do
rm -rf "/etc/systemd/system/${target}.wants"
mkdir -p "/lib/systemd/diverted-system/${target}.wants"
for i in "/lib/systemd/system/${target}.wants"/*.timer; do
[ -e "${i}" ] || continue
dpkg-divert --add --rename --divert "/lib/systemd/diverted-system/${target}.wants/$(basename "${i}")" "${i}"
done
done
rm -f /etc/rc?.d/*
# Add needed services to our custom target
systemctl add-wants "${PRODUCT_ID}.target" systemd-user-sessions.service
# Show service startup/shutdown statuses
mkdir -p "/etc/systemd/system.conf.d"
cat <<"EOM" >"/etc/systemd/system.conf.d/${PRODUCT_ID}.conf"
[Manager]
ShowStatus=yes
EOM
<file_sep>/hooks/5000-finnix-1000-systemd.hook.chroot.in
#!/bin/sh
set -e
# Create any remaining systemd users/groups which would be created
# at runtime. (Just "systemd-coredump" as of this writing.)
systemd-sysusers
<file_sep>/hooks/0005-finnix-1000-strace.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
mkdir -p "/lib/${PRODUCT_ID}"
cat >"/lib/${PRODUCT_ID}/strace-init" <<"EOM"
#!/bin/sh
# finnix-strace-init
# Copyright (C) 2012-2020 <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
set -e
PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin"
strace -v -qq -yy -s 65535 -p $$ -f -e open,openat,execve -z -o /var/log/strace-init.trace &
sleep 3
if [ -n "$1" ]; then
exec "$@"
else
exec /sbin/init
fi
EOM
chmod 0755 "/lib/${PRODUCT_ID}/strace-init"
<file_sep>/hooks/0005-finnix-1000-live-config.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
apt-get -y --purge remove live-config live-config-systemd
systemctl add-wants "${PRODUCT_ID}.target" live-tools.service
useradd \
--create-home \
--comment "{{ PRODUCT }} user" \
--password '*' \
--shell /bin/bash \
--groups audio,cdrom,dip,floppy,video,plugdev,adm,sudo \
"${PRODUCT_ID}"
mkdir -p /etc/sudoers.d
cat <<EOM >"/etc/sudoers.d/${PRODUCT_ID}"
{{ PRODUCT_ID }} ALL=(ALL) NOPASSWD: ALL
EOM
chmod 0440 "/etc/sudoers.d/${PRODUCT_ID}"
echo 'Etc/UTC' >/etc/timezone
rm -f /etc/localtime
dpkg-reconfigure -f noninteractive -p critical tzdata
<file_sep>/hooks/0005-finnix-1000-wifi-connect.hook.chroot.in
#!/bin/sh
set -e
cat <<"HOOKEOM" >/usr/local/sbin/wifi-connect
#!/bin/sh
# wifi-connect - Handy wrapper around wpa_supplicant/networkd
set -e
interface=""
while getopts ":i:" opt; do
case "${opt}" in
i)
interface="$OPTARG"
;;
*)
echo "Usage: $0 [-i interface] \"access point\" \"passphrase\""
exit 1
;;
esac
done
shift $((OPTIND -1))
ap="$1"
passphrase="$2"
if [ -z "${interface}" ]; then
interfaces=""
multiple_interfaces="no"
for p in /sys/class/net/*; do
[ -e "${p}" ] || continue
[ -e "${p}/phy80211" ] || [ -e "${p}/wireless" ] || continue
iname="$(basename "${p}")"
if [ -n "${interfaces}" ]; then
multiple_interfaces="yes"
interfaces="${interfaces} ${iname}"
else
interfaces="${iname}"
fi
done
if [ -z "${interfaces}" ]; then
echo "Sorry, no wireless interfaces found"
exit 1
elif [ "${multiple_interfaces}" = "yes" ]; then
echo "Multiple interfaces found: ${multiple_interfaces}"
echo "Usage: $0 -i interface \"access point\" \"passphrase\""
exit 1
fi
interface="${interfaces}"
fi
if [ ! -e "/sys/class/net/${interface}" ]; then
echo "Interface ${interface} not found"
exit 1
fi
if [ -z "${ap}" ] || [ -z "${passphrase}" ]; then
echo "Usage: $0 [-i interface] \"access point\" \"passphrase\""
exit 1
fi
mkdir -p /etc/wpa_supplicant
wpa_passphrase_block="$(wpa_passphrase "${ap}" "${passphrase}")"
rm -f "/etc/wpa_supplicant/wpa_supplicant-${interface}.conf"
touch "/etc/wpa_supplicant/wpa_supplicant-${interface}.conf"
chmod 0600 "/etc/wpa_supplicant/wpa_supplicant-${interface}.conf"
cat <<EOM >"/etc/wpa_supplicant/wpa_supplicant-${interface}.conf"
ctrl_interface=/run/wpa_supplicant
update_config=1
${wpa_passphrase_block}
EOM
mkdir -p /etc/systemd/network
rm -f "/etc/systemd/network/10-${interface}.network"
cat <<EOM >"/etc/systemd/network/10-${interface}.network"
[Match]
Name=${interface}
[Network]
DHCP=yes
EOM
systemctl restart "wpa_supplicant@${interface}.service" systemd-networkd.service systemd-resolved.service
rm -f /etc/resolv.conf
ln -sf /run/systemd/resolve/stub-resolv.conf /etc/resolv.conf
echo ""
echo "Interface ${interface} is now being managed by wpa_supplicant and networkd."
echo "To see the status of these services:"
echo " networkctl"
echo " journalctl -a -u wpa_supplicant@${interface}.service -u systemd-networkd.service"
echo ""
HOOKEOM
chmod 0755 /usr/local/sbin/wifi-connect
<file_sep>/finnix-live-build
#!/bin/sh
set -e
PRODUCT="${PRODUCT:-Finnix}"
PRODUCT_ID="${PRODUCT_ID:-finnix}"
VERSION="${VERSION:-dev}"
CODENAME="${CODENAME:-Winnebago}"
ARCH="${ARCH:-$(dpkg --print-architecture)}"
SOURCE_ISO="${SOURCE_ISO:-false}"
CACHE_FROZEN="${CACHE_FROZEN:-false}"
LINT="${LINT:-false}"
lock() {
_file=$1
exec 9>"${_file}"
if ! flock -x -w 1 9; then
echo "${_file} lock failed" >&2
exit 1
fi
}
render() {
env \
"PRODUCT=${PRODUCT}" \
"PRODUCT_ID=${PRODUCT_ID}" \
"VERSION=${VERSION}" \
"CODENAME=${CODENAME}" \
"ARCH=${ARCH}" \
"DATETIME=${DATETIME}" \
"DATE=${DATE}" \
"YEAR=${YEAR}" \
"GIT_DESC=${GIT_DESC}" \
"LIVE_BUILD_GIT_DESC=${LIVE_BUILD_GIT_DESC}" \
"${BASE_DIR}/tools/jinja2-render"
}
DATETIME="$(date -u +"%F %T")"
DATE="$(date -u +"%F")"
YEAR="$(date -u +"%Y")"
SQUASHFS_COMP="xz"
if [ "${ARCH}" = "amd64" ]; then
BINARY_IMAGES="iso-hybrid"
BOOTLOADERS="grub-efi,syslinux"
ISO_FILENAME="${PRODUCT_ID}-${ARCH}.hybrid.iso"
MEMTEST="memtest86+"
SQUASHFS_COMP="xz -Xbcj x86"
elif [ "${ARCH}" = "i386" ]; then
BINARY_IMAGES="iso-hybrid"
BOOTLOADERS="grub-efi,syslinux"
ISO_FILENAME="${PRODUCT_ID}-${ARCH}.hybrid.iso"
MEMTEST="memtest86+"
SQUASHFS_COMP="xz -Xbcj x86"
elif [ "${ARCH}" = "arm64" ]; then
BINARY_IMAGES="iso-hybrid"
BOOTLOADERS="grub-efi"
ISO_FILENAME="${PRODUCT_ID}-${ARCH}.hybrid.iso"
MEMTEST=""
else
BINARY_IMAGES="iso"
BOOTLOADERS=""
ISO_FILENAME="${PRODUCT_ID}-${ARCH}.iso"
MEMTEST=""
fi
if [ "$(dnsdomainname)" = "snowman.lan" ]; then
APT_HTTP_PROXY="http://deb-proxy.snowman.lan:8000"
fi
if [ "${LINT}" = "true" ]; then
LINT_DIR="$(mktemp -d)"
DATA_DIR="${DATA_DIR:-${LINT_DIR}}"
fi
BASE_DIR="${BASE_DIR:-$(dirname "$(readlink -f "$0")")}"
DATA_DIR="${DATA_DIR:-${BASE_DIR}/build}"
CACHE_DIR="${CACHE_DIR:-${DATA_DIR}/cache}"
LOCK_DIR="${LOCK_DIR:-${DATA_DIR}/lock}"
LOCK_NAME="${LOCK_NAME:-$(basename "$(readlink -f "$0")")}"
LB_DIR="${LB_DIR:-${DATA_DIR}/lb}"
LB_CACHE_DIR="${LB_CACHE_DIR:-${CACHE_DIR}/lb}"
LIVE_BUILD="${LIVE_BUILD:-${BASE_DIR}/live-build}"
if [ "${LIVE_BUILD}" = "-" ]; then
export LIVE_BUILD=""
else
export LIVE_BUILD
export PATH="${LIVE_BUILD}/frontend:${PATH}"
fi
GIT_DESC="$(git -C "${BASE_DIR}" describe --always --dirty 2>/dev/null || true)"
LIVE_BUILD_GIT_DESC="$(git -C "${LIVE_BUILD}" describe --always --dirty 2>/dev/null || true)"
mkdir -p "${LOCK_DIR}"
lock "${LOCK_DIR}/${LOCK_NAME}.lock"
if command -v shellcheck >/dev/null; then
shellcheck "${BASE_DIR}/finnix-live-build"
fi
cd /
rm -rf "${LB_DIR}"
mkdir -p "${LB_DIR}"
cd "${LB_DIR}"
# Note that --source true also requires --apt-source-archives true
lb config noauto \
--apt-http-proxy "${APT_HTTP_PROXY}" \
--apt-indices false \
--apt-recommends false \
--apt-source-archives true \
--architectures "${ARCH}" \
--archive-areas "main contrib non-free" \
--backports false \
--binary-images "${BINARY_IMAGES}" \
--bootappend-live "boot=live quiet" \
--bootloaders "${BOOTLOADERS}" \
--cache-indices true \
--chroot-squashfs-compression-type "${SQUASHFS_COMP}" \
--distribution testing \
--hdd-label "$(echo "${PRODUCT_ID}" | tr '[:lower:]' '[:upper:]')" \
--image-name "${PRODUCT_ID}" \
--iso-application "${PRODUCT}" \
--iso-preparer "${PRODUCT}" \
--iso-publisher "${PRODUCT}" \
--iso-volume "${PRODUCT} ${VERSION}" \
--memtest "${MEMTEST}" \
--security false \
--source "${SOURCE_ISO}" \
--source-images iso \
--updates false \
--zsync false \
--mode debian
mkdir -p "${LB_CACHE_DIR}"
if [ "${CACHE_FROZEN}" = "false" ]; then
if [ -e "${LB_CACHE_DIR}/bootstrap/etc/hostname" ]; then
if [ -n "$(find "${LB_CACHE_DIR}/bootstrap/etc/hostname" -mmin +1080)" ]; then
rm -rf "${LB_CACHE_DIR}/bootstrap"
fi
else
rm -rf "${LB_CACHE_DIR}/bootstrap"
fi
if [ -e "${LB_CACHE_DIR}/indices.bootstrap/pkgcache.bin" ]; then
if [ -n "$(find "${LB_CACHE_DIR}/indices.bootstrap/pkgcache.bin" -mmin +1080)" ]; then
rm -rf "${LB_CACHE_DIR}/indices.bootstrap" "${LB_CACHE_DIR}/contents.chroot"
fi
else
rm -rf "${LB_CACHE_DIR}/indices.bootstrap" "${LB_CACHE_DIR}/contents.chroot"
fi
find "${LB_CACHE_DIR}"/packages.* -name '*.deb' -mtime +30 -delete 2>/dev/null || true
fi
rm -rf "${LB_DIR}/cache"
ln -sf "${LB_CACHE_DIR}" "${LB_DIR}/cache"
for i in "${BASE_DIR}/hooks"/*.hook.*.in; do
basefn="$(basename "$i" .in)"
rm -f "${LB_DIR}/config/hooks/normal/${basefn}"
# False positive in earlier shellcheck
# shellcheck disable=SC2094
render <"${i}" >"${LB_DIR}/config/hooks/normal/${basefn}"
done
mkdir -p "${LB_DIR}/config/bootloaders/syslinux_common"
render <"${BASE_DIR}/syslinux/splash.svg" | rsvg-convert --format png --width 640 --height 480 >"${LB_DIR}/config/bootloaders/syslinux_common/splash.png"
cp "${BASE_DIR}/syslinux/isolinux.cfg" "${LB_DIR}/config/bootloaders/syslinux_common/"
mkdir -p "${LB_DIR}/config/bootloaders/grub-pc"
cp "${BASE_DIR}/grub"/*.cfg "${LB_DIR}/config/bootloaders/grub-pc/"
render <"${BASE_DIR}/grub/splash.svg" | rsvg-convert --format png --width 1920 --height 1080 >"${LB_DIR}/config/bootloaders/grub-pc/splash.png"
mkdir -p "${LB_DIR}/config/bootloaders/grub-pc/live-theme"
cp "${BASE_DIR}/grub/theme.txt" "${LB_DIR}/config/bootloaders/grub-pc/live-theme/"
cp "${BASE_DIR}/lists"/*.list.chroot "${LB_DIR}/config/package-lists/"
if [ -e "${BASE_DIR}/squashfs.sort" ]; then
mkdir -p "${LB_DIR}/config/rootfs"
cp "${BASE_DIR}/squashfs.sort" "${LB_DIR}/config/rootfs/squashfs.sort"
fi
# The in-squashfs initrds are unused; exclude them
mkdir -p "${LB_DIR}/config/rootfs"
cat <<"EOM" >"${LB_DIR}/config/rootfs/excludes"
boot/initrd.img*
initrd.img*
EOM
mkdir -p "${LB_DIR}/config/includes.chroot/etc"
echo "${PRODUCT_ID}" >"${LB_DIR}/config/includes.chroot/etc/hostname"
cat <<EOM >"${LB_DIR}/config/includes.chroot/etc/hosts"
127.0.0.1 localhost
127.0.1.1 ${PRODUCT_ID}
::1 ip6-localhost ip6-loopback
fdf8:f53e:61e4::18 ip6-localnet
fc00:db20:35b:7399::5 ip6-mcastprefix
fc00:e968:6179::de52:7100 ip6-allnodes
fc00:e968:6179::de52:7100 ip6-allrouters
EOM
if command -v shellcheck >/dev/null; then
grep -l '^#!/bin/sh' "${LB_DIR}/config/hooks/normal"/*-finnix-*.hook.chroot | xargs shellcheck
fi
if [ "${LINT}" = "true" ]; then
rm -rf "${LINT_DIR}"
exit 0
fi
lb build
ls -lsa "${LB_DIR}/${ISO_FILENAME}"
file "${LB_DIR}/${ISO_FILENAME}"
<file_sep>/hooks/0005-finnix-1000-ssh.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
mkdir -p "/lib/${PRODUCT_ID}"
cat <<"EOM" >"/lib/${PRODUCT_ID}/sshd-keygen"
#!/bin/sh
set -e
for keytype in ecdsa ed25519 rsa; do
if [ ! -e "/etc/ssh/ssh_host_${keytype}_key" ] && grep -qs "ssh_host_${keytype}_key" /etc/ssh/sshd_config; then
ssh-keygen -q -f "/etc/ssh/ssh_host_${keytype}_key" -N "" -t "${keytype}"
fi
done
EOM
chmod 0755 "/lib/${PRODUCT_ID}/sshd-keygen"
mkdir -p /etc/systemd/system/ssh.service.d
cat <<"EOM" >"/etc/systemd/system/ssh.service.d/${PRODUCT_ID}.conf"
[Service]
ExecStartPre=
ExecStartPre=/lib/{{ PRODUCT_ID }}/sshd-keygen
ExecStartPre=/usr/sbin/sshd -t
EOM
cat <<"EOM" >"/etc/ssh/sshd_config.d/${PRODUCT_ID}.conf"
# "Safe" for maintenance use since by default, the user needs to set a
# root password and start ssh.service.
PasswordAuthentication yes
PermitRootLogin yes
EOM
# Shared per-user SSH agent
mkdir -p "/lib/${PRODUCT_ID}"
cat <<"EOM" >"/lib/${PRODUCT_ID}/ssh-agent"
#!/bin/sh
[ -n "${HOME}" ] || exit 1
if [ ! -e "${HOME}/.ssh/ssh-agent.sh" ]; then
mkdir -p "${HOME}/.ssh"
ssh-agent -s | grep ^SSH >"${HOME}/.ssh/ssh-agent.sh"
. "${HOME}/.ssh/ssh-agent.sh"
echo "${SSH_AGENT_PID}" >"${HOME}/.ssh/ssh-agent.pid"
fi
. "${HOME}/.ssh/ssh-agent.sh"
EOM
chmod 0755 "/lib/${PRODUCT_ID}/ssh-agent"
cat <<"EOM" >/etc/systemd/system/shared-ssh-agent.service
[Unit]
Description=Shared SSH agent init
Before=getty.target
[Service]
Type=forking
ExecStart=/lib/{{ PRODUCT_ID }}/ssh-agent
PIDFile=/root/.ssh/ssh-agent.pid
Environment="USER=root"
Environment="HOME=/root"
EOM
systemctl add-wants "${PRODUCT_ID}.target" shared-ssh-agent.service
<file_sep>/hooks/0005-finnix-1000-gpm.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
cat <<EOM >/etc/systemd/system/gpm.service
[Unit]
Description=Console mouse daemon
ConditionPathExists=/dev/input/mice
[Service]
Type=forking
ExecStart=/usr/sbin/gpm -m /dev/input/mice -t exps2
PIDFile=/var/run/gpm.pid
EOM
systemctl add-wants "${PRODUCT_ID}.target" gpm.service
<file_sep>/hooks/0005-finnix-1000-bash-profile.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
cat <<"EOM" >"/etc/profile.d/${PRODUCT_ID}.sh"
export PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/local/games:/usr/games
EOM
if ! grep -q "^# {{ PRODUCT }} additions" /etc/skel/.bashrc >/dev/null 2>/dev/null; then
cat <<"EOM" >>/etc/skel/.bashrc
# {{ PRODUCT }} additions
if [ -f ~/.bash_{{ PRODUCT_ID }} ]; then
. ~/.bash_{{ PRODUCT_ID }}
fi
EOM
fi
cat <<"EOM" >>"/etc/skel/.bash_${PRODUCT_ID}"
__sh_exitcode() { ret=$?; if [[ $ret != 0 ]]; then echo "$ret "; fi }
if [ -x /usr/bin/tput ] && tput setaf 1 >&/dev/null; then
PS1='${debian_chroot:+($debian_chroot)}\[\033[1;31m\]$(__sh_exitcode)\[\033[1;37m\]\u\[\033[0;39m\]@\[\033[1;37m\]\l\[\033[0;39m\]:\[\033[1;37m\]\w\[\033[1;34m\]\$\[\033[0;39m\] '
else
PS1='${debian_chroot:+($debian_chroot)}$(__sh_exitcode)\u@\h:\w\$ '
fi
export GPG_TTY="$(tty)"
if [ -x "/lib/{{ PRODUCT_ID }}/ssh-agent" ]; then
. "/lib/{{ PRODUCT_ID }}/ssh-agent"
fi
#alias ls='ls --color=auto' # Conditionally set by .bashrc if color supported
alias l='ls -CF'
alias la='ls -A'
alias ll='ls -alF'
alias httpd='python3 -m http.server'
EOM
rsync -a /etc/skel/ /root/
chmod 0700 /root
<file_sep>/hooks/0005-finnix-1000-distro.hook.chroot.in
#!/bin/sh
set -e
dpkg-divert --add --rename --divert /usr/lib/os-release.debian /usr/lib/os-release
cat <<"EOM" >/usr/lib/os-release
PRETTY_NAME="{{ PRODUCT }} {{ VERSION }}{% if VERSION == 'dev' %} ({{ DATETIME }}{% if GIT_DESC %} {{ GIT_DESC }}{% endif %}){% endif %}"
NAME="{{ PRODUCT }}"
VERSION="{{ VERSION }}{% if VERSION == 'dev' %} ({{ DATETIME }}{% if GIT_DESC %} {{ GIT_DESC }}{% endif %}){% endif %}"
VERSION_ID="{{ VERSION }}"
VERSION_CODENAME="{{ CODENAME }}"
BUILD_ID="{{ DATETIME }}{% if GIT_DESC %} {{ GIT_DESC }}{% endif %}"
ID="{{ PRODUCT_ID }}"
ID_LIKE="debian"
ANSI_COLOR="1;34"
{% if PRODUCT_ID == 'finnix' %}HOME_URL="https://www.finnix.org/"
SUPPORT_URL="https://www.finnix.org/"
BUG_REPORT_URL="https://www.finnix.org/"{% endif %}
EOM
dpkg-divert --add --rename --divert /etc/issue.debian /etc/issue
cat <<"EOM" >/etc/issue
{{ PRODUCT }} {{ VERSION }}{% if VERSION == 'dev' %} ({{ DATETIME }}{% if GIT_DESC %} {{ GIT_DESC }}{% endif %}){% endif %} (\l)
EOM
dpkg-divert --add --rename --divert /etc/issue.net.debian /etc/issue.net
cat <<"EOM" >/etc/issue.net
{{ PRODUCT }} {{ VERSION }}{% if VERSION == 'dev' %} ({{ DATETIME }}{% if GIT_DESC %} {{ GIT_DESC }}{% endif %}){% endif %}
EOM
: >/etc/motd
<file_sep>/Makefile
.PHONY: all test lint
all:
test: lint
lint:
env LINT=true ./finnix-live-build
<file_sep>/hooks/0005-finnix-1000-network.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
mkdir -p "/lib/${PRODUCT_ID}"
cat <<"EOM" >"/lib/${PRODUCT_ID}/interfaces-convert"
#!/usr/bin/env python3
# interfaces-convert
# Copyright (C) 2021 <NAME>
# SPDX-License-Identifier: GPL-2.0+
# This program converts sections in /etc/network/interfaces to files in
# /etc/systemd/network/, and (if needed) from /etc/resolv.conf to
# /etc/systemd/resolved.conf, putting the systemd-resolved stub in its
# place.
#
# This must be run before anything uses e-n-i, namely before udevd as
# ifupdown installs rules which bring up allow-hotplug entries.
#
# Note that this was built to translate entries built by live-boot, and
# is not meant to be a general-purpose e-n-i converter.
import configparser
import io
import os
FILES_TO_WRITE = {}
REPLACE_RESOLVCONF = False
def systemd_config():
config = configparser.ConfigParser()
config.optionxform = str
return config
def process_section(section):
global FILES_TO_WRITE
if "iface" not in section:
return False
interface = section["iface"][0]
if section["iface"][2] == "loopback":
return False
if (section["iface"][1] != "inet") or (
section["iface"][2] not in ("dhcp", "static")
):
output = systemd_config()
output["Match"] = {"Name": interface}
output["Link"] = {"Unmanaged": "yes"}
with io.StringIO() as f:
output.write(f, space_around_delimiters=False)
FILES_TO_WRITE[
"/etc/systemd/network/10-{}.network".format(interface)
] = f.getvalue()
return False
output = systemd_config()
output["Match"] = {"Name": interface}
output["Link"] = {}
output["Network"] = {}
if ("address" in section) and ("netmask" in section):
output["Network"]["Address"] = "{}/{}".format(
section["address"][0], section["netmask"][0]
)
if "gateway" in section:
output["Network"]["Gateway"] = section["gateway"][0]
else:
output["Network"]["DHCP"] = "yes"
if "allow-hotplug" in section:
output["Link"]["RequiredForOnline"] = "no"
with io.StringIO() as f:
output.write(f, space_around_delimiters=False)
FILES_TO_WRITE[
"/etc/systemd/network/10-{}.network".format(interface)
] = f.getvalue()
return True
def convert_interfaces():
global FILES_TO_WRITE
if not os.path.exists("/etc/network/interfaces"):
return
rewritten_interfaces = ""
section = {}
section_text = ""
with open("/etc/network/interfaces") as f:
for raw_line in f:
line = raw_line.strip()
if line == "" and section:
if not process_section(section):
rewritten_interfaces += section_text + "\n"
section = {}
section_text = ""
continue
ls = line.split(" ")
if not ls[0].startswith("#"):
section[ls[0]] = ls[1:]
section_text += raw_line
if section:
if not process_section(section):
rewritten_interfaces += section_text + "\n"
FILES_TO_WRITE["/etc/network/interfaces"] = rewritten_interfaces
def convert_resolv():
global FILES_TO_WRITE
global REPLACE_RESOLVCONF
if not os.path.exists("/etc/systemd/resolved.conf"):
return
nameservers = []
domains = []
with open("/etc/resolv.conf") as f:
for line in f:
line = line.strip()
ls = line.split(" ")
if ls[0] == "nameserver":
if ls[1] == "127.0.0.53":
continue
nameservers.append(ls[1])
elif ls[0] in ("search", "domain"):
for s in ls[1:]:
if s == ".":
continue
domains.append(s)
if nameservers or domains:
resolved = systemd_config()
resolved.read("/etc/systemd/resolved.conf")
if "Resolve" not in resolved:
resolved["Resolve"] = {}
if nameservers:
resolved["Resolve"]["DNS"] = " ".join(nameservers)
if domains:
resolved["Resolve"]["Domains"] = " ".join(domains)
with io.StringIO() as f:
resolved.write(f, space_around_delimiters=False)
FILES_TO_WRITE["/etc/systemd/resolved.conf"] = f.getvalue()
REPLACE_RESOLVCONF = True
def write_files():
global FILES_TO_WRITE
global REPLACE_RESOLVCONF
for fn in FILES_TO_WRITE:
with open(fn, "w") as f:
f.write(FILES_TO_WRITE[fn])
if REPLACE_RESOLVCONF:
os.remove("/etc/resolv.conf")
os.symlink("/run/systemd/resolve/stub-resolv.conf", "/etc/resolv.conf")
if __name__ == "__main__":
convert_interfaces()
convert_resolv()
write_files()
EOM
chmod 0755 "/lib/${PRODUCT_ID}/interfaces-convert"
cat <<"EOM" >/etc/systemd/system/network-config-setup.service
[Unit]
Description=Set up network configurations
DefaultDependencies=no
# Before systemd-udevd becuase ifupdown will try to manage hotplug
# interfaces via udev
Before=network.target ifupdown-pre.service systemd-udevd.service
[Service]
Type=oneshot
ExecStart=/lib/{{ PRODUCT_ID }}/interfaces-convert
EOM
systemctl add-wants sysinit.target network-config-setup.service
systemctl add-wants network.target systemd-networkd.service
systemctl add-wants network.target systemd-resolved.service
systemctl add-wants "${PRODUCT_ID}.target" network.target
<file_sep>/hooks/0005-finnix-1000-getty.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
systemctl add-wants "${PRODUCT_ID}.target" getty.target
mkdir -p /lib/systemd/diverted-generators
dpkg-divert --add --rename --divert /lib/systemd/diverted-generators/live-config-getty-generator /lib/systemd/system-generators/live-config-getty-generator
mkdir -p /etc/systemd/system/getty@.service.d
cat <<"EOM" >"/etc/systemd/system/getty@.service.d/${PRODUCT_ID}.conf"
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin root --noclear --skip-login %I $TERM
TTYVTDisallocate=no
EOM
mkdir -p /etc/systemd/system/serial-getty@.service.d
cat <<"EOM" >"/etc/systemd/system/serial-getty@.service.d/${PRODUCT_ID}.conf"
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin root --noclear --skip-login --keep-baud 115200,38400,9600 %I $TERM
EOM
mkdir -p /etc/systemd/system/container-getty@.service.d
cat <<"EOM" >"/etc/systemd/system/container-getty@.service.d/${PRODUCT_ID}.conf"
[Service]
ExecStart=
ExecStart=-/sbin/agetty --autologin root --noclear --skip-login --keep-baud 115200,38400,9600 pts/%I $TERM
EOM
<file_sep>/hooks/9900-finnix-1000-recompress.hook.chroot.in
#!/usr/bin/env python3
# Re-"compress" all .gz files at gzip level 0 so mksquashfs can compress
# it more efficiently
import datetime
import glob
import gzip
import hashlib
import itertools
import logging
import os
import shutil
DIVERSIONS = {}
FILE_COUNT = 0
PRE_SIZE = 0
POST_SIZE = 0
def readiter(fh, size=1024):
return itertools.takewhile(
lambda x: x, map(lambda x: fh.read(size), itertools.count(0))
)
def numfmt(
num,
fmt="{num.real:0.02f} {num.prefix}",
binary=False,
rollover=1.0,
limit=0,
prefixes=None,
):
"""Formats a number with decimal or binary prefixes
num: Input number
fmt: Format string of default repr/str output
binary: If True, use divide by 1024 and use IEC binary prefixes
rollover: Threshold to roll over to the next prefix
limit: Stop after a specified number of rollovers
prefixes: List of (decimal, binary) prefix strings, ascending
"""
class NumberFormat(float):
prefix = ""
fmt = "{num.real:0.02f} {num.prefix}"
def __repr__(self):
return self.fmt.format(num=self)
if prefixes is None:
prefixes = [
("k", "Ki"),
("M", "Mi"),
("G", "Gi"),
("T", "Ti"),
("P", "Pi"),
("E", "Ei"),
("Z", "Zi"),
("Y", "Yi"),
]
divisor = 1024 if binary else 1000
if limit <= 0 or limit > len(prefixes):
limit = len(prefixes)
count = 0
p = ""
for prefix in prefixes:
if num < (divisor * rollover):
break
if count >= limit:
break
count += 1
num = num / float(divisor)
p = prefix[1] if binary else prefix[0]
ret = NumberFormat(num)
ret.fmt = fmt
ret.prefix = p
return ret
def parse_diversions(base_dir="/"):
with open(
os.path.join(base_dir, "/var/lib/dpkg/diversions"), "r", encoding="utf-8"
) as f:
while True:
orig = f.readline()
if orig == "":
break
orig = orig.rstrip()
diverted_to = f.readline().rstrip()
_ = f.readline().rstrip()
DIVERSIONS[orig] = diverted_to
logging.debug("Loaded {} diversions".format(len(DIVERSIONS)))
def recompress(filename):
global FILE_COUNT, PRE_SIZE, POST_SIZE
file_size_pre = os.stat(filename).st_size
with gzip.open(filename, "rb") as fsrc:
with open(filename + "~recomp", "wb") as fdst:
# Explicitly do not set filename and mtime in resulting .gz
with gzip.GzipFile(
filename="", mode="wb", compresslevel=0, mtime=0, fileobj=fdst
) as fdstgz:
shutil.copyfileobj(fsrc, fdstgz)
shutil.copystat(filename, filename + "~recomp")
shutil.move(filename + "~recomp", filename)
file_size_post = os.stat(filename).st_size
with open(filename, "rb") as f:
m = hashlib.md5()
for buf in readiter(f):
m.update(buf)
md5_hex = m.hexdigest()
FILE_COUNT += 1
PRE_SIZE += file_size_pre
POST_SIZE += file_size_post
logging.debug(
"Recompressed {filename} - {pre.real:0.02f} {pre.prefix}B to {post.real:0.02f} {post.prefix}B".format(
filename=filename, pre=numfmt(file_size_pre), post=numfmt(file_size_post)
)
)
return md5_hex
def process_dpkg_file(dpkg_filename, orig_md5, base_dir="/"):
if not dpkg_filename.endswith(".gz"):
return orig_md5
filename = os.path.join("/", dpkg_filename)
if filename in DIVERSIONS:
logging.debug(
"{} was diverted to {} - using that instead".format(
filename, DIVERSIONS[filename]
)
)
filename = DIVERSIONS[filename]
filename = os.path.join(base_dir, filename)
if os.path.islink(filename):
logging.warning("File is a symlink, skipping: {}".format(filename))
return orig_md5
fstat = os.stat(filename)
if fstat.st_nlink > 1:
logging.warning(
"File has {} hard links, skipping: {}".format(fstat.st_nlink, filename)
)
return orig_md5
with open(filename, "rb") as f:
m = hashlib.md5()
for buf in readiter(f):
m.update(buf)
found_md5 = m.hexdigest()
if orig_md5 != found_md5:
logging.error(
"MD5 mismatch (expected {}, got {}), skipping: {}".format(
orig_md5, found_md5, filename
)
)
return orig_md5
return recompress(filename)
if __name__ == "__main__":
logging.basicConfig(level=logging.INFO)
time_start = datetime.datetime.now()
base_dir = "/"
parse_diversions(base_dir=base_dir)
for fn in glob.glob(os.path.join(base_dir, "/var/lib/dpkg/info/*.md5sums")):
file_output = ""
with open(fn, "r", encoding="utf-8") as f:
for line in f.readlines():
orig_md5, _, dpkg_filename = line.rstrip().split(" ", 2)
new_md5 = process_dpkg_file(dpkg_filename, orig_md5, base_dir=base_dir)
file_output += "{} {}\n".format(new_md5, dpkg_filename)
with open(fn, "w", encoding="utf-8") as f:
f.write(file_output)
time_end = datetime.datetime.now()
logging.info(
'{} files re-"compressed" at gzip level 0, in {}.'.format(
FILE_COUNT, (time_end - time_start)
)
)
logging.info(
"{pre.real:0.02f} {pre.prefix}B (previous gzip total) expanded to "
"{post.real:0.02f} {post.prefix}B (gzip level 0).".format(
pre=numfmt(PRE_SIZE), post=numfmt(POST_SIZE)
)
)
ballpark_xz = int(POST_SIZE * 0.15)
logging.info(
"If subsequently compressed with xz, {ballpark.real:0.02f} {ballpark.prefix}B "
"({ballpark_pct:0.02%} of previous gzip) might be achieved (ballpark).".format(
ballpark=numfmt(ballpark_xz), ballpark_pct=(ballpark_xz / PRE_SIZE)
)
)
<file_sep>/README.md
# Finnix live-build tools
`finnix-live-build` is Finnix image build system, and is a wrapper around Debian Live's `live-build` system.
## Building
Requirements:
* Debian testing/sid, or Ubuntu 18.04 bionic or later.
* live-build, built from [live-build git HEAD](https://salsa.debian.org/rfinnie/live-build).
* This is available as a git submodule in this repository.
* While upstream HEAD is usually fine, the link above (and this repository's submodule) points to a Finnix-specific branch which is usually in sync with upstream, but sometimes includes fixes/changes which have not (yet) been accepted upstream.
* Additional required packages: debootstrap debian-archive-keyring apt-utils gzip bzip2 xz-utils cpio file coreutils rsync wget python3-jinja2 librsvg2-bin fonts-liberation2
This can be built on dedicated hardware, in a virtual machine, or in a systemd-nspawn container. Building in a chroot within one of these environments is supported. Docker and LXD containers are not supported, as they do not allow mounting proc/devpts (even the container-specific restricted versions), required by live-build/debootstrap.
The default build directory will be `build/lb/` from the script directory.
## Scheduled builds
* Weekly AMD64 builds are made on the [GitHub finnix-live-build "schedule" workflow](https://github.com/finnix/finnix-live-build/actions?query=workflow%3Aschedule), with ISO build artifacts uploaded. The "ci" workflow is built on each push as an indication, but artifacts are not available.
* Daily AMD64 builds are made on a [container in a colocated environment](https://ci.colobox.com/colobox/finnix-live-build-amd64/), with ISO build artifacts uploaded to [snapshots.finnix.org](https://snapshots.finnix.org/ci/finnix-live-build-amd64/).
* Indicator builds are built on [my home CI system](https://ci.colobox.com/home/) for many architectures (see below). Artifacts are not publicly available. Most architectures are built daily, except for slow pure emulation architectures like s390x and ppc64el.
## Architectures
finnix-live-build supports multiple architectures, but are considered in multiple tiers:
### Tier 1
* amd64
The only supported architecture in the sense that ISOs are officially released. Built images are tested often. Build failures are a blocker and fixed ASAP.
### Tier 2
* arm64
* i386
While ISOs are not officially released, these are still considered important architectures. Built images are tested often. Build failures are a blocker and fixed soon.
### Tier 3
* armhf
* ppc64el
* s390x
Not supported, and produced images are not directly bootable. However, they can be booted by direct kernel/initrd boot in QEMU, and are tested occasionally. Build failures are not a blocker.
## Issues and pull requests
To open a Finnix issue, please use the main [Finnix issue tracker](https://github.com/finnix/finnix/issues), not this repository's.
Pull requests will be considered here, but you probably also want to open an issue to track it.
## Remastering / forking
If you are looking to build a live environment which is outside of the scope of Finnix's goals, feel free to use this build repository as a base.
In essence, this repository is a thin wrapper around live-build, and builds upon the massive work done by the Debian Live project.
I encourage you to study this repository and live-build, and to experiment with your own builds.
If you do produce builds based directly off the finnix-live-build repository, please change the branding to indicate it is not an official Finnix release.
Please see the top of `finnix-live-build` for branding-related variables.
<file_sep>/hooks/5000-finnix-1000-mandb.hook.chroot.in
#!/bin/sh
set -e
# Regenerate man cache after live-build hook
# 0190-remove-temporary-files.hook.chroot
# https://github.com/finnix/finnix/issues/9
mandb -qpc
<file_sep>/hooks/5000-finnix-1000-locale.hook.chroot.in
#!/bin/sh
# Must be run after 0040-create-locales-files.hook.chroot
set -e
echo 'LANG=en_US.UTF-8' >/etc/default/locale
sed -i -e 's/^# en_US.UTF-8 /en_US.UTF-8 /g' /etc/locale.gen
locale-gen
cat <<"EOM" >/usr/local/sbin/0
#!/bin/sh
# Reconfigure keyboard/locale access in a fairly universal way,
# requiring the following keys on a potentially misconfigured keyboard:
# - 0
# - Enter
# - Arrow keys
set -e
dpkg-reconfigure keyboard-configuration
setupcon -k
udevadm trigger --subsystem-match=input --action=change
dpkg-reconfigure locales
EOM
chmod 0755 /usr/local/sbin/0
<file_sep>/hooks/0005-finnix-1000-getting-started.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
mkdir -p /etc/issue.d
cat <<"EOM" >"/etc/issue.d/${PRODUCT_ID}.issue"
Run "{{ PRODUCT_ID }}" to get started.
EOM
mkdir -p "/usr/local/share/doc/${PRODUCT_ID}"
cat <<"EOM" >"/usr/local/share/doc/${PRODUCT_ID}/getting-started.txt"
Welcome to {{ PRODUCT }}!
This is mostly a fully-featured Debian-based text utility distribution,
but there are a few custom utilities to know about:
- # 0
Easy (and mostly keyboard-agnostic) way to change your locale and
keyboard information.
- # wifi-connect "Access Point" "Passphrase"
Set up a standard WPA wireless connection.
DHCP is attemped on any found wired Ethernet interface. For a text-mode
web browser, "elinks" and "w3m" are available.
If you would like to update any dpkg alternatives, such as for the
"editor" command perhaps, "rover" is a friendly curses-based
alternatives selection program.
EOM
mkdir -p /usr/local/bin
cat <<"EOM" >"/usr/local/bin/${PRODUCT_ID}"
#!/bin/sh
exec pager /usr/local/share/doc/{{ PRODUCT_ID }}/getting-started.txt
EOM
chmod 0755 "/usr/local/bin/${PRODUCT_ID}"
<file_sep>/hooks/0005-finnix-1000-defaults.hook.chroot.in
#!/bin/sh
set -e
update-alternatives --set editor /bin/nano
update-alternatives --set pager /usr/bin/less
update-alternatives --set vi /usr/bin/vim.tiny
update-alternatives --set www-browser /usr/bin/elinks
<file_sep>/tools/finnix-strace-reorder
#!/usr/bin/env python3
# finnix-strace-reorder
# Copyright (C) 2011-2020 <NAME>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
import os
import re
import sys
SQUASHFS_ROOT = "/run/live/rootfs/filesystem.squashfs"
R_OPEN = re.compile(r"^[0-9]+ +(open|openat)\(.*?\) = [0-9]+<(.*?)>$")
R_EXEC = re.compile(r"^[0-9]+ +(execve)\(\"(.*?)\".*?\) = [0-9]+$")
def get_filename(line):
m = re.search(R_OPEN, line)
if m:
return m.group(2)
m = re.search(R_EXEC, line)
if m:
return m.group(2)
if __name__ == "__main__":
seen = []
for line in sys.stdin.readlines():
filename = get_filename(line.rstrip())
if not filename:
continue
if not os.path.isfile(os.path.join(SQUASHFS_ROOT, filename[1:])):
continue
if filename in seen:
continue
seen.append(filename)
pos = -1
for filename in seen:
print("{}\t{}".format(filename[1:], pos))
pos -= 1
<file_sep>/hooks/0005-finnix-1000-remove-packages.hook.chroot.in
#!/bin/sh
set -e
apt-get -y --purge remove rsyslog tasksel tasksel-data || true
<file_sep>/hooks/0005-finnix-1000-zramswap.hook.chroot.in
#!/bin/sh
set -e
PRODUCT_ID="{{ PRODUCT_ID }}"
# Light reading:
# https://fedoraproject.org/wiki/Changes/SwapOnZRAM
sed -i -e 's/^\#PERCENT=.*/PERCENT=50/g;' /etc/default/zramswap
systemctl add-wants "${PRODUCT_ID}.target" zramswap.service
<file_sep>/tools/jinja2-render
#!/usr/bin/env python3
import os
import sys
from jinja2 import Template
if __name__ == "__main__":
tmpl = Template(sys.stdin.read())
vars = dict(os.environ)
print(tmpl.render(vars))
|
afe207a269919238e8fd6d61cd026358f0b1a9da
|
[
"Markdown",
"Python",
"Makefile",
"Shell"
] | 25 |
Shell
|
Acidburn0zzz/finnix-live-build
|
5d079cb73cae4bd33006b4762b48919aac4f099a
|
32999689752dd07d0240e3f9db3e79f28e74c508
|
refs/heads/main
|
<file_sep>import Firebase from 'firebase/app';
import 'firebase/firestore';
import 'firebase/auth';
import {seedDatabase} from "../seed"
// 1) when seeding the database you'll have to uncomment this!
const config = {
apiKey: "<KEY>",
authDomain: "netflix2-b4b1b.firebaseapp.com",
projectId: "netflix2-b4b1b",
storageBucket: "netflix2-b4b1b.appspot.com",
messagingSenderId: "695100000587",
appId: "1:695100000587:web:d1a566524199cf2c7f00ce"
};
const firebase = Firebase.initializeApp(config);
// 2) when seeding the database you'll have to uncomment this!
// seedDatabase(firebase);
// 3) once you have populated the database (only run once!), re-comment this so you don't get duplicate data
export { firebase };
|
0870c98a25cdacd64da996c946154d5ab0ac7bf0
|
[
"JavaScript"
] | 1 |
JavaScript
|
TamasFarago/netflix
|
562457926465d2551953a00c65861832d8da0d6d
|
74718584130fff6551248f88272c8caa983f7b96
|
refs/heads/master
|
<file_sep>local telescope_setup, telescope = pcall(require, "telescope")
if not telescope_setup then
return
end
telescope.setup({
defaults = {
layout_config = {
horizontal = {
preview_cutoff = 0,
},
},
{
file_ignore_patterns = {
"node_modules"
},
},
},
})
<file_sep>local lspconfig_status, lspconfig = pcall(require, "lspconfig")
if not lspconfig_status then
return
end
local cmp_nvim_lsp_status, cmp_nvim_lsp = pcall(require, "cmp_nvim_lsp")
if not cmp_nvim_lsp_status then
return
end
local keymap = vim.keymap
-- enable keybinds for avaliable lsp server
local on_attach = function(_, bufnr)
local opts = { noremap = true, silent = true, buffer = bufnr }
-- set keybinds
keymap.set("n", "gf", "<cmd>Lspsaga lsp_finder<CR>", opts) -- show definition, references
keymap.set("n", "gD", "<Cmd>lua vim.lsp.buf.declaration()<CR>", opts) -- got to declaration
keymap.set("n", "gd", "<cmd>Lspsaga peek_definition<CR>", opts) -- see definition and make edits in window
keymap.set("n", "gi", "<cmd>lua vim.lsp.buf.implementation()<CR>", opts) -- go to implementation
keymap.set("n", "<leader>ca", "<cmd>Lspsaga code_action<CR>", opts) -- see available code actions
keymap.set("n", "<leader>rn", "<cmd>Lspsaga rename<CR>", opts) -- smart rename
keymap.set("n", "<leader>s", "<cmd>Lspsaga show_line_diagnostics<CR>", opts) -- show diagnostics for line
keymap.set("n", "<leader>s", "<cmd>Lspsaga show_cursor_diagnostics<CR>", opts) -- show diagnostics for cursor
-- keymap.set("n", "[d", "<cmd>Lspsaga diagnostic_jump_prev<CR>", opts) -- jump to previous diagnostic in buffer
-- keymap.set("n", "]d", "<cmd>Lspsaga diagnostic_jump_next<CR>", opts) -- jump to next diagnostic in buffer
keymap.set("n", "K", "<cmd>Lspsaga hover_doc<CR>", opts) -- show documentation for what is under cursor
keymap.set("n", "<leader>o", "<cmd>LSoutlineToggle<CR>", opts) -- see outline on right hand side
end
-- used to enable autocompletion (assign to every lsp server config)
local capabilities = cmp_nvim_lsp.default_capabilities()
-- configure html server
lspconfig["html"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure css server
lspconfig["cssls"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure javascript server
lspconfig["tsserver"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure javascript lint server
lspconfig["quick_lint_js"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure ruby server
lspconfig["solargraph"].setup({
capabilities = capabilities,
-- Lspsaga not support ruby will
on_attach = function(_, bufnr)
-- Enable completion triggered by <c-x><c-o>
vim.api.nvim_buf_set_option(bufnr, 'omnifunc', 'v:lua.vim.lsp.omnifunc')
-- See `:help vim.lsp.*` for documentation on any of the below functions
local bufopts = { noremap=true, silent=true, buffer=bufnr }
-- ๅ
copy ๅๆฌ cmp ๆๆๅปบ่ญฐ่จญๅฎ๏ผไธๅไธๅๆธฌ่ฉฆๅพๅช็ไธๅฅฝ็จๆๅฏไปฅ็จ็๏ผๅพๅคไธๆฏๆดๆไธ็ฅ้ๆๆ
-- gd ๅ
จๅฐๆกๆพ่ฉฒ defined method ็ๅฐๆน๏ผๅคงๆจ
vim.keymap.set('n', 'gd', vim.lsp.buf.definition, bufopts)
-- rn ๅ
จๅฐๆกไธๆฌกๆดๆฐ่ฉฒ method name๏ผไฝไธ็ฅ้ๆฏๆดๅฐๅช็จฎ็จๅบฆ้ๆฏ่ฆไป็ดฐ check
vim.keymap.set('n', '<space>rn', vim.lsp.buf.rename, bufopts)
-- gr ๅ
จๅฐๆกๆพๅบไฝฟ็จ่ฉฒ class.method ็ๅฐๆน๏ผไฝไธ็ฅ้ๆฏๆดๅฐๅช็จฎ็จๅบฆ้ๆฏ่ฆไป็ดฐ check
vim.keymap.set('n', 'gr', vim.lsp.buf.references, bufopts)
end,
})
-- configure ruby server
-- lspconfig["ruby_ls"].setup({
-- capabilities = capabilities,
-- on_attach = on_attach,
-- })
-- configure sql server
lspconfig["sqlls"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure yaml server
lspconfig["yamlls"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure json server
lspconfig["jsonls"].setup({
capabilities = capabilities,
on_attach = on_attach,
})
-- configure typescript server with plugin
-- typescript.setup({
-- server = {
-- capabilities = capabilities,
-- on_attach = on_attach,
-- },
-- })
-- configure lua server (with special settings)
lspconfig["sumneko_lua"].setup({
capabilities = capabilities,
on_attach = on_attach,
settings = { -- custom settings for lua
Lua = {
-- make the language server recognize "vim" global
diagnostics = {
globals = { "vim" },
},
workspace = {
-- make language server aware of runtime files
library = {
[vim.fn.expand("$VIMRUNTIME/lua")] = true,
[vim.fn.stdpath("config") .. "/lua"] = true,
},
},
},
},
})
<file_sep>local ensure_packer = function()
local fn = vim.fn
local install_path = fn.stdpath('data')..'/site/pack/packer/start/packer.nvim'
if fn.empty(fn.glob(install_path)) > 0 then
fn.system({'git', 'clone', '--depth', '1', 'https://github.com/wbthomason/packer.nvim', install_path})
vim.cmd [[packadd packer.nvim]]
return true
end
return false
end
local packer_bootstrap = ensure_packer() -- true if packer was just install
-- Autocommand that reloads nvim whenever save this file
vim.cmd([[
augroup packer_user_config
autocmd!
autocmd BufWritePost plugins-setup.lua source <afile> | PackerSync
augroup end
]])
local status, packer = pcall(require, "packer")
if not status then
return
end
return packer.startup(function(use)
use("wbthomason/packer.nvim")
-- lua functions that many plugins to use
-- telescope require, ่ผๅ
ฅๅพ telescope ๅฏไปฅ้ ่ฆฝๆชๆก
use("nvim-lua/plenary.nvim")
use("morhetz/gruvbox") --perferred colorscheme
use("christoomey/vim-tmux-navigator") -- ๆญ้
.tmux.conf ๆฏๆด vim switch to other tmux window
use("szw/vim-maximizer") -- vim-maximizer & restores current window
use("tpope/vim-surround") -- c = change, d = delete, y = add, ๅพ้ข + s(surround) ้ๅงไฝฟ็จ
use("numToStr/Comment.nvim") -- gc = comment
use("nvim-tree/nvim-tree.lua") -- file explorer
use("nvim-lualine/lualine.nvim") -- nvim ไนๆ statusline
use("nvim-telescope/telescope.nvim") -- fuzzy finding
use({"akinsho/bufferline.nvim", tag = "v3.*", requires = "nvim-tree/nvim-web-devicons"})
use("lewis6991/gitsigns.nvim") -- git plugin
use("tpope/vim-fugitive") -- git plugin
use("mg979/vim-visual-multi") -- ctrl n ่ท vscode crtl d ไธๆจฃๆๆ
-- use("vim-ruby/vim-ruby") -- ๅบๆฌ็ ruby ๆชๆกไธไบๆไปค, ไฝ้ฝๆฒๆๆๆ, ้็ ็ฉถ
use("tpope/vim-rails") -- ๆ:A, gf ็ญๆไปคๅฏไปฅ็จ
use("kassio/neoterm") -- quick open new terminal, ็ฎๅๅช็จไพๆญ้
vim-rspec
use("thoughtbot/vim-rspec") -- rspec plugin
use("simeji/winresizer") -- window quick resize
-- autocompletion
use("hrsh7th/nvim-cmp") -- Autocompletion plugin
use("hrsh7th/cmp-buffer") -- source for buffer words
use("hrsh7th/cmp-path") -- source for filesystem paths
use("hrsh7th/cmp-cmdline") -- source for command line
-- autocompletion - snippets
use("L3MON4D3/LuaSnip") -- Snippets plugin
use("saadparwaiz1/cmp_luasnip") -- Snippets source for nvim-cmp
use("rafamadriz/friendly-snippets")
-- managing & installing lsp server
use("williamboman/mason.nvim")
use("williamboman/mason-lspconfig.nvim")
-- configuring lsp servers
use("neovim/nvim-lspconfig") -- Collection of configurations for built-in LSP client
use("hrsh7th/cmp-nvim-lsp") -- LSP source for nvim-cmp
use({"glepnir/lspsaga.nvim", branch = "main" })
use("onsails/lspkind.nvim")
-- treesitter configuration
use({
"nvim-treesitter/nvim-treesitter",
run = function()
local ts_update = require("nvim-treesitter.install").update({ with_sync = true })
ts_update()
end,
})
if packer_bootstrap then
require('packer').sync()
end
end)
<file_sep>local setup, comment = pcall(require, "lualine")
if not setup then
return
end
local gruvbox = require'lualine.themes.gruvbox'
comment.setup({
options = {
theme = gruvbox
},
sections = {
lualine_a = {
{
'filename',
path = 1,
},
},
},
})
<file_sep>local mason_status, mason = pcall(require, "mason")
if not mason_status then
return
end
local mason_lspconfig_status, mason_lspconfig = pcall(require, "mason-lspconfig")
if not mason_lspconfig_status then
return
end
mason_lspconfig.setup({
-- A list of servers to automatically install if they're not already installed. Example: { "rust_analyzer@nightly", "sumneko_lua" }
-- This setting has no relation with the `automatic_installation` setting.
ensure_installed = {
"html",
"cssls",
"tsserver",
"quick_lint_js",
"tsserver",
"solargraph",
-- "ruby_ls",
"sqlls",
"yamlls",
"jsonls"
},
-- Whether servers that are set up (via lspconfig) should be automatically installed if they're not already installed.
-- This setting has no relation with the `ensure_installed` setting.
-- Can either be:
-- - false: Servers are not automatically installed.
-- - true: All servers set up via lspconfig are automatically installed.
-- - { exclude: string[] }: All servers set up via lspconfig, except the ones provided in the list, are automatically installed.
-- Example: automatic_installation = { exclude = { "rust_analyzer", "solargraph" } }
automatic_installation = false,
})
mason.setup()
<file_sep>-- vim-rspec
vim.g.rspec_command = "T rspec {spec}"
<file_sep>local plenary_setup, plenary = pcall(require, "plenary")
if not plenary_setup then
return
end
<file_sep>require("kurt.plugins-setup")
require("kurt.core.options")
require("kurt.core.keymaps")
require("kurt.core.colorscheme")
require("kurt.plugins.bufferline")
require("kurt.plugins.comment")
require("kurt.plugins.gitsigns")
require("kurt.plugins.lualine")
require("kurt.plugins.neoterm")
require("kurt.plugins.nvim-cmp")
require("kurt.plugins.nvim-tree")
require("kurt.plugins.plenary")
require("kurt.plugins.telescope")
require("kurt.plugins.treesitter")
require("kurt.plugins.vim-rspec")
require("kurt.plugins.lsp.lspconfig")
require("kurt.plugins.lsp.mason")
<file_sep>-- neoterm
vim.g.neoterm_default_mod = 'botright'
vim.g.neoterm_autoscroll = 1
<file_sep>local setup, nvimtree = pcall(require, "nvim-tree")
if not setup then
return
end
-- recommended settings from nvim-tree documents
vim.g.loaded_netrw = 1
vim.g.loaded_netrwPlugin = 1
vim.cmd([[ highlight NvimTreeIdentMaker guifg=#3FC5FF ]])
nvimtree.setup({
update_focused_file = {
enable = true,
update_root = true,
ignore_list = {},
},
renderer = {
icons = {
glyphs = {
folder = {
arrow_closed = "โธ", -- icon when folder is closed
arrow_open = "โพ", -- icon when folder is open
},
},
},
},
actions = {
open_file = {
quit_on_open = true,
window_picker = {
enable = false,
},
},
},
git = {
ignore = false,
},
})
<file_sep>local opt = vim.opt -- for consieness
-- line number
opt.relativenumber = true
opt.number = true
-- tab & identation
opt.tabstop = 2
opt.shiftwidth = 2
opt.expandtab = true
opt.autoindent = true
-- line wrapping
opt.wrap = false -- ๅญๆธ่ถ
้ termin ๅฏฌๅบฆไธๆ่ก้กฏ็คบ
-- search setting
opt.ignorecase = true -- ไธๅๅคงๅฐๅฏซ
opt.smartcase = true
-- search setting
opt.cursorline = true -- cursor ้ฃไธ่กๆๅ็ฝ
-- appearance
opt.termguicolors = true
opt.background = "dark"
opt.signcolumn = "yes"
-- backspace
-- indent ๅ
่ฎธๅ ้ค่ชๅจ็ผฉ่ฟ็ๅ
ๅฎนใๅฆๆๆฒกๆ่ฟไธ้กน๏ผ่ชๅจ็ผฉ่ฟๆทปๅ ็็ฉบ็ฝๅญ็ฌฆๆ ๆณ็จ Backspace ้ฎๆฅๅ ้ค๏ผๅฏไปฅๅ ้คๆๅจๆทปๅ ็็ผฉ่ฟ็ฉบๆ ผใ
-- eol ๅ
่ฎธๅ ้คๆข่ก็ฌฆใๅฆๆๆฒกๆ่ฟไธ้กน๏ผๅฝๅทฒ็ปๅ ้คๅฐ่ก้ฆๆถ๏ผไธ่ฝ็จ Backspace ้ฎๅ ้คๆข่ก็ฌฆ๏ผไนๅฐฑๆฏไธ่ฝ่ชๅจๅพไธๅ ้คๅฐไธไธ่กใ
-- start ๅ
่ฎธๅ ้ค่ฟๅ
ฅๆๅ
ฅๆจกๅผๅๅทฒๆ็ๅ
ๅฎนใๅฆๆๆฒกๆ่ฟไธ้กน๏ผไธ่ฝๅ ้ค่ฟๅ
ฅๆๅ
ฅๆจกๅผๅๅทฒๆ็ๅ
ๅฎน๏ผๅช่ฝๅ ้คๅฝๅๆๅ
ฅๆจกๅผไธ่พๅ
ฅ็ๅญ็ฌฆใไพๅฆ๏ผ่พๅ
ฅ abc ไธไธชๅญ็ฌฆ๏ผๆ Esc ้ฎ้ๅบๆๅ
ฅๆจกๅผ๏ผๅๆ a๏ผ่ฟๅ
ฅๆๅ
ฅๆจกๅผ๏ผ่พๅ
ฅ efgใๆญคๆถ Backspace ้ฎๅฏไปฅๅ ้ค efg๏ผไธ่ฝๅ ้ค abcใ
opt.backspace = "indent,eol,start"
-- clipboard: ๆๆ่ค่ฃฝๆๆ็พๅจไนๆ็ดๆฅๅฐ็ณป็ตฑ็ clipboard
opt.clipboard:append("unnamedplus")
-- slip window
opt.splitright = true
opt.splitbelow = true
opt.iskeyword:append("-") -- A-lin ๆ็ถไฝไธๅๅญๅ
, dw ๆ็ดๆฅๅช้ค
<file_sep>vim.g.gruvbox_italic = 1
local status, _ = pcall(vim.cmd, "colorscheme gruvbox")
if not status then
print("Colorscheme not found!")
return
end
-- Use 24-bit (true-color) mode in Vim/Neovim when outside tmux.
-- If you're using tmux version 2.2 or later, you can remove the outermost $TMUX check and use tmux's 24-bit color support
-- (see < http://sunaku.github.io/tmux-24bit-color.html#usage > for more information.)
if (vim.fn.empty(vim.env.TMUX)) then
-- ๅฆไฝๆฟ vim ็ฐๅข่ฎๆธ($) ๅฏๅ่ https://vi.stackexchange.com/questions/31737/get-value-of-myvimrc-from-lua
if (vim.fn.has("nvim")) then
-- For Neovim 0.1.3 and 0.1.4 < https://github.com/neovim/neovim/pull/2198 >
vim.env.NVIM_TUI_ENABLE_TRUE_COLOR = 1
end
-- For Neovim > 0.1.5 and Vim > patch 7.4.1799 < https://github.com/vim/vim/commit/61be73bb0f965a895bfb064ea3e55476ac175162 >
-- Based on Vim patch 7.4.1770 (`guicolors` option) < https://github.com/vim/vim/commit/8a633e3427b47286869aa4b96f2bfc1fe65b25cd >
-- < https://github.com/neovim/neovim/wiki/Following-HEAD#20160511 >
if (vim.fn.has("termguicolors")) then
vim.opt.termguicolors = true
end
return
end
<file_sep>vim.g.mapleader = ","
local keymap = vim.keymap -- for conciseness
-- general key maps
keymap.set("i", "<leader>,", "<Esc>", {desc = ",, can quick quit from i mode"})
keymap.set("i", "<C-h>", "<Left>")
keymap.set("i", "<C-j>", "<Down>")
keymap.set("i", "<C-k>", "<Up>")
keymap.set("i", "<C-l>", "<Right>")
keymap.set("c", "<C-h>", "<Left>")
keymap.set("c", "<C-j>", "<Down>")
keymap.set("c", "<C-k>", "<Up>")
keymap.set("c", "<C-l>", "<Right>")
keymap.set("n", "<leader>e", ":e<space>")
keymap.set("n", "<leader>c", ":")
keymap.set("n", "<leader>d", ":bd<CR>")
keymap.set("n", "<leader>ww", ":w<CR>")
keymap.set("n", "<leader>q", ":q<CR>")
keymap.set("n", "<leader>wh", "<C-w>s", {desc = "split window horizontally"})
keymap.set("n", "<leader>wv", "<C-w>v", {desc = "split window vertically"})
keymap.set("n", "<leader>wd", "<cmd>close<CR>", {desc = "close window"})
keymap.set("n", "<leader>wm", "<cmd>MaximizerToggle<CR>", {desc = "toggle max window"})
keymap.set("n", "<leader>we", "<cmd>WinResizerStartResize<CR>", {desc = "quick resize window"})
keymap.set("n", "<leader>n", "<cmd>NvimTreeToggle<CR>", {desc = "toggle nvim-tree"})
-- keymap.set("n", "<leader>tc", ":tabnew<CR>", {desc = "create tab"})
-- keymap.set("n", "<leader>td", ":tabclose<CR>", {desc = "close tab"})
-- keymap.set("n", "<leader>tl", ":tabn<CR>", {desc = "go to next tab"})
-- keymap.set("n", "<leader>th", ":tabp<CR>", {desc = "go to previous tab"})
keymap.set("n", "<Tab>", "<cmd>BufferLineCycleNext<CR>")
keymap.set("n", "<S-Tab>", "<cmd>BufferLineCyclePrev<CR>")
keymap.set("n", "<leader>tf", "<cmd>call RunCurrentSpecFile()<CR>")
keymap.set("n", "<leader>tj", "<cmd>call RunNearestSpec()<CR>")
keymap.set("n", "<leader>ta", "<cmd>call RunAllSpecs()<CR>")
keymap.set("n", "<leader>td", "<cmd>Tkill<CR> :Tclose!<CR>")
local builtin = require('telescope.builtin')
keymap.set("n", "<leader>ff", builtin.find_files)
keymap.set("n", "<leader>fg", builtin.live_grep)
keymap.set("n", "<leader>fb", builtin.buffers)
keymap.set("n", "<leader>fh", builtin.help_tags)
keymap.set("n", "<leader>fw", builtin.grep_string)
keymap.set("n", "<leader>fs", builtin.git_status)
keymap.set("t", "<C-h>", "<C-\\><C-n><C-w>h", {desc = "switch from terminal"})
keymap.set("t", "<C-j>", "<C-\\><C-n><C-w>j", {desc = "switch from terminal"})
keymap.set("t", "<C-k>", "<C-\\><C-n><C-w>k", {desc = "switch from terminal"})
keymap.set("t", "<C-l>", "<C-\\><C-n><C-w>l", {desc = "switch from terminal"})
keymap.set("n", "<leader>ag<space>", ":T rg<space>")
keymap.set("n", "<leader>agw", '"ayiw:T rg<space><c-r>a<space>')
keymap.set("n", "<leader>agd", "\"ayiw:T rg<space>'def<space><c-r>a'<space>")
keymap.set("v", "<leader>fw", 'y"ayiw:T rg<space><c-r>a<space>', {desc = "rg search selected words"})
keymap.set("v", "<leader>fd", "y\"ayiw:T rg<space>'def<space><c-r>a'<space>", {desc = "rg search selected words"})
keymap.set("v", "f", "y\"ayiw/<c-r>a<CR>", {desc = "search selected words"})
keymap.set("n", "<leader>gb", ":Git blame<CR>")
|
9c438cd268a9489ea50df90788d2cc96fcd2d4c8
|
[
"Lua"
] | 13 |
Lua
|
myohmy10420/dotfiles
|
80c63c3649ae35637a0faa91015009bfb6a8fb07
|
95fb820828dd3397563d128525a32cdebb7b9521
|
refs/heads/master
|
<repo_name>Dastanio/Apple-Logic-Bot<file_sep>/keyboards.py
from telebot import types
# Main Keyboard
markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("ะะฐัะฐัั ะธะณัั")
item2 = types.KeyboardButton("ะัะฐะฒะธะปะฐ")
item3 = types.KeyboardButton("ะะพั ััะฐัะธััะธะบะฐ")
item4 = types.KeyboardButton("ะกะพะทะดะฐัะตะปั")
markup.add(item1, item2, item3, item4)
# Apple Keyboard
apple_markup = types.ReplyKeyboardMarkup(resize_keyboard=True)
item1 = types.KeyboardButton("๐")
item2 = types.KeyboardButton("๐๐")
item3 = types.KeyboardButton("๐๐๐")
item4 = types.KeyboardButton("ะกะดะฐัััั")
apple_markup.add(item1, item2, item3, item4)<file_sep>/sqlighter.py
import sqlite3
class SQlighter:
def __init__(self, database):
#ะะพะดะบะปััะฐะตะผัั ะบ ะะ ะธ ัะพั
ัะฐะฝัะตะผ ะบัััะพั ัะพะตะดะธะฝะตะฝะธะต
self.connection = sqlite3.connect(database)
self.cursor = self.connection.cursor()
def add_new_user(self, user_id):
#ะะพะฑะฐะฒะปะตะฝะธะต ะฝะพะฒะพะณะพ ะฟะพะปัะทะพะฒะฐัะตะปั
with self.connection:
if user_id not in self.get_users_id():
return self.cursor.execute("INSERT INTO `users` (`user_id`, `apples`, `wins`, `defeats`, `giveups`) VALUES(?,?,?,?,?)", (user_id,0,0,0,0))
def get_users_id(self):
# ะะพะปััะฐะตะผ ัะฟะธัะพะบ ะฐะนะดะธัะฝะธะบะพะฒ ัะทะตัะพะฒ
with self.connection:
user_id = self.cursor.execute("SELECT user_id FROM users")
user_id_list = [x[0] for x in user_id]
return user_id_list
def update_column(self, user_id ,num, column):
#ะะฑะฝะพะฒะปัะตะผ ะบะพะปะพะฝะบั ั ะบะพะปะธัะตััะฒะพะผ ัะฑะปะพะบ
with self.connection:
return self.cursor.execute(f"UPDATE users SET {column} = {num} WHERE user_id = {user_id}")
def get_column(self, user_id, column):
#ะะพะปััะฐะตะผ ะบะพะปะธัะตััะฒะพ ัะฑะปะพะบ ะฟะพะปัะทะพะฒะฐัะตะปั
with self.connection:
obj = self.cursor.execute(f"SELECT {column} FROM users WHERE user_id = {user_id}")
return list(obj)[0][0]
def close(self):
"""ะะฐะบััะฒะฐะตะผ ัะพะตะดะธะฝะตะฝะธะต ั ะะ"""
self.connection.close()
database = SQlighter('sqlite.db')
<file_sep>/bot.py
from telebot import TeleBot
from config import TOKEN
from telebot import types
import random
from sqlighter import SQlighter
import time
from keyboards import *
bot = TeleBot(TOKEN)
@bot.message_handler(commands = ['start', 'Exit'])
def main(message):
#ะะพะฑะฐะฒะปัะตะผ ะฒ ะะ ะฐะนะดะธ ัะทะตัะฐ ะตัะปะธ ะตะณะพ ะฝะตั ัะฐะฝะตะต
database = SQlighter('sqlite.db')
database.add_new_user(message.chat.id)
bot.send_message(message.chat.id, """
ะัะฐะฒะธะปะฐ ะฝะฐัะตะน ะธะณัั ะพัะตะฝั ะฟัะพัััะต: ะฟะตัะตะด ะะฐะผะธ ะฟะพัะฒะธััั ะฝะตะบะพัะพัะพะต ะบะพะปะธัะตััะฒะพ ัะฑะปะพะบ.
ะั ะธ ั ะฑัะดะตะผ ะฟะพ ะพัะตัะตะดะธ ััะตะดะฐัั 1, 2 ะธะปะธ 3 ัะณะพะดั.
ะขะพั, ะบัะพ ััะตัั ะฟะพัะปะตะดะฝัั (ะธัะฟะพััะตะฝะฝะพะต) ัะฑะปะพะบะพ โ ะฟัะพะธะณัะฐะป!
ะะฐัะฝัะผ?
""", parse_mode='html', reply_markup=markup)
@bot.message_handler(content_types = ['text'])
def text_messages(message):
if message.chat.type == 'private':
if message.text == 'ะะฐัะฐัั ะธะณัั':
msg = bot.send_message(message.chat.id, 'ะก ะบะฐะบะธะผ ะบะพะปะธัะตััะฒะพะผ ัะฑะปะพะบ ะฑัะดะตะผ ะธะณัะฐัั?\nะะฒะตะดะธัะต ัะธัะปะพ ะพั 20 ะดะพ 100:', reply_markup=types.ReplyKeyboardRemove())
bot.register_next_step_handler(msg, process_link_step)
elif message.text == 'ะกะพะทะดะฐัะตะปั':
bot.send_message(message.chat.id, 'ะะตะฝั ัะพะทะดะฐะป @Xeonio\nEัะปะธ ะฑัะดัั ะฟัะพะฑะปะตะผั ะฟะธัะธ ะตะผั ะพะฝ ะฟะพ ัะธะบัะธั ะผะตะฝั)')
elif message.text == '๐':
process_game(message.chat.id, 1)
elif message.text == '๐๐':
process_game(message.chat.id, 2)
elif message.text == '๐๐๐':
process_game(message.chat.id, 3)
elif message.text == 'ะะพั ััะฐัะธััะธะบะฐ':
database = SQlighter('sqlite.db')
chat_id = message.chat.id
wins = database.get_column(chat_id, 'wins')
defeats = database.get_column(chat_id, 'defeats')
giveups = database.get_column(chat_id, 'giveups')
msg = f"ะะพะฑะตะด: {str(wins)}\nะะพัะฐะถะตะฝะธะน: {str(defeats)}\nะั ัะดะฐะปะธัั: {str(giveups)}"
bot.send_message(message.chat.id, msg)
elif message.text == 'ะกะดะฐัััั':
database = SQlighter('sqlite.db')
current_giveups = database.get_column(message.chat.id, 'giveups')
database.update_column(message.chat.id, current_giveups + 1, 'giveups')
bot.send_message(message.chat.id, 'ะั ัะดะฐะปะธัั:(\nะะพ ะฟะพัะตะผั ะฑั ะฝะต ะฟะพะฟัะพะฑะพะฒะฐัั ะตัะต ัะฐะท?', parse_mode='html', reply_markup=markup)
elif message.text == 'ะัะฐะฒะธะปะฐ':
bot.send_message(message.chat.id, """
ะัะฐะฒะธะปะฐ ะธะณัั
โ ะ ัะฐะผะพะผ ะฝะฐัะฐะปะต ะธะณัั ั ะฟัะตะดะปะพะถั ะะฐะผ ะฒัะฑัะฐัั ะบะพะปะธัะตััะฒะพ ัะฑะปะพะบ, ะบะพัะพัะพะต ะฟะพัะฒะธััั ะฟะตัะตะด ะฝะฐะผะธ.
โ ะะฐัะตะผ ะผั ะฟะพ ะพัะตัะตะดะธ ะฑัะดะตะผ ััะตะดะฐัั 1, 2 ะธะปะธ 3 ัะฑะปะพะบ ะฝะฐ ะฒัะฑะพั.
โ ะัะพะธะณััะฒะฐะตั ัะพั, ะบัะพ ััะตัั ะฟะพัะปะตะดะฝัั (ะธัะฟะพััะตะฝะฝะพะต) ัะฑะปะพะบะพ.
ะกัะณัะฐะตะผ?
""")
else:
bot.send_message(message.chat.id, 'ะั ัะฒะฝะพ ะพัะธะฑะปะธัั ะฟัะธ ะฒะฒะพะดะต...')
def process_link_step(message):
try:
chat_id = message.chat.id
number = message.text
database = SQlighter('sqlite.db')
database.update_column(chat_id, int(number), 'apples')
if int(number) < 20 or int(number) > 100:
bot.send_message(chat_id, """
ะั ะพัะธะฑะปะธัั! ะะฐะผ ะฝัะถะฝะพ ะฑัะปะพ ะฒะฒะตััะธ ัะธัะปะพ ะพั 20 ะดะพ 100.
ะะพะฟัะพะฑัะนัะต ะตัั ัะฐะท ะฝะฐะถะฐะฒ ะบะฝะพะฟะบั ะธะณัะฐัั ะธะปะธ ะดะปั ะพัะผะตะฝั ะฝะฐะถะผะธัะต /Exit
""")
else:
quantity = database.get_column(chat_id, 'apples')
apples = '๐' * quantity
message = f'ะัะฐะบ, ะฟะตัะตะด ะะฐะผะธ {number} ัะฑะปะพะบ: \n\n{apples} \n\nะกัะตัััะต 3, 2 ะธะปะธ 1. ะะฐั ั
ะพะด:'
bot.send_message(chat_id, message, parse_mode='html', reply_markup=apple_markup)
except Exception as e:
bot.reply_to(message, """
ะั ะพัะธะฑะปะธัั! ะะฐะผ ะฝัะถะฝะพ ะฑัะปะพ ะฒะฒะตััะธ ัะธัะปะพ ะพั 20 ะดะพ 100.
ะะพะฟัะพะฑัะนัะต ะตัั ัะฐะท ะฝะฐะถะฐะฒ ะบะฝะพะฟะบั ะธะณัะฐัั ะธะปะธ ะดะปั ะพัะผะตะฝั ะฝะฐะถะผะธัะต /Exit
""")
def process_game(chat_id, quantity_apple):
database = SQlighter('sqlite.db')
quantity = database.get_column(chat_id, 'apples')
#ะัะพะฒะตััะตะผ ะฝะฐ ะฟะพะฑะตะดะธัะตะปั
if quantity == 1 or 0:
current_wins = database.get_column(chat_id, 'defeats')
database.update_column(chat_id, current_wins + 1, 'defeats')
bot.send_message(chat_id, 'ะั ะฟัะพะธะณัะฐะปะธ!\n\nะะพะฑะตะดะฐ ะทะฐ ะผะฝะพะน!(\nะฅะพัะธัะต ะพััะณัะฐัััั?', reply_markup=markup, parse_mode='html')
else:
database.update_column(chat_id, quantity - quantity_apple, 'apples')
quantity_after = database.get_column(chat_id, 'apples')
apples = '๐' * quantity_after
msg = f"ะัะปะธัะฝะพ! ะั ััะตะปะธ {str(quantity_apple)} ัะฑะปะพะบะพ.\nะััะฐะฒัะธะตัั:\n\n{apples}\n\nะขะตะฟะตัั ะผะพะน ั
ะพะด!"
bot.send_message(chat_id, msg, reply_markup=types.ReplyKeyboardRemove())
time.sleep(0.5)
if quantity_after == 1:
current_wins = database.get_column(chat_id, 'wins')
database.update_column(chat_id, current_wins + 1, 'wins')
bot.send_message(chat_id, 'ะั ะฒัะนะณัะฐะปะธ!\n\nะะพะฑะตะดะฐ ะทะฐ ะฒะฐะผะธ!)\nะฅะพัะธัะต ะตัะต ัะฐะท?', reply_markup=markup, parse_mode='html')
else:
if quantity_after == 0:
current_wins = database.get_column(chat_id, 'defeats')
database.update_column(chat_id, current_wins + 1, 'defeats')
bot.send_message(chat_id, 'ะั ะฟัะพะธะณัะฐะปะธ!\n\nะะพะฑะตะดะฐ ะทะฐ ะผะฝะพะน!(\nะฅะพัะธัะต ะพััะณัะฐัััั?', reply_markup=markup, parse_mode='html')
else:
random_int = random.randint(1,3)
summ = quantity_after - random_int
if summ > 0:
database.update_column(chat_id, summ, 'apples')
bot_quantity_after = database.get_column(chat_id, 'apples')
bot_apples = '๐' * bot_quantity_after
bot_msg = f'ะฏ ััะตะดะฐั {random_int} ัะฑะปะพะบ(ะพ).\nะััะฐะฒัะธะตัั:\n\n{bot_apples}\n\nะขะตะฟะตัั ะะฐั ั
ะพะด!\nะัััะต ัะฑะปะพะบะพ:'
bot.send_message(chat_id, bot_msg, parse_mode='html', reply_markup=apple_markup)
else:
current_wins = database.get_column(chat_id, 'wins')
database.update_column(chat_id, current_wins + 1, 'wins')
bot.send_message(chat_id, f'ะฏ ะฟัะพะธะณัะฐะป ััะตะฒ {random_int} ัะฑะปะพะบ(ะพ)\n\nะะพะฑะตะดะฐ ะทะฐ ะฒะฐะผะธ!)\nะฅะพัะธัะต ะตัะต ัะฐะท?', reply_markup=markup, parse_mode='html')
if __name__ == '__main__':
bot.polling(none_stop = True)
|
d3bcf0047077fb26cfbd2e8273598c3e0db03f07
|
[
"Python"
] | 3 |
Python
|
Dastanio/Apple-Logic-Bot
|
35ac45818e6fd6c0eba0b795867f5cd526b0835e
|
08359e71c016e1e0b1aa467d0d08b5aa31db2e0a
|
refs/heads/master
|
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Ono\MapBundle\Entity\Indefinition;
use Ono\MapBundle\Form\IndefinitionType;
use Ono\MapBundle\Form\IndefinitionLogType;
class IndefinitionController extends Controller
{
public function addAction(Request $request)
{
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->container->get('security.token_storage')->getToken()->getUser();
$userName = $user->getName();
$userFirstname = $user->getFirstname();
$hasName = false;
if (($userName && trim($userName) != "") || ($userFirstname && trim($userFirstname) != "")) {
$hasName = true;
}
}
$manager = $this->getDoctrine()->getManager();
$indefinition = new Indefinition;
if (isset($user) && $hasName) {
$indefinition->updateUser($user);
$form = $this->get('form.factory')->create(IndefinitionLogType::class, $indefinition);
} else {
$form = $this->get('form.factory')->create(IndefinitionType::class, $indefinition);
}
$tagId = (int) $request->attributes->all()["tag_id"];
$tagRepo = $manager->getRepository("OnoMapBundle:Tag");
$tag = $tagRepo->find($tagId);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
if(isset($user) && $hasName) {
$indefinition->setUser($user);
}
$indefinition->setTag($tag);
$manager->persist($indefinition);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Indรฉfinition bien enregistrรฉe.');
$articleId = (int) $request->attributes->all()["article_id"];
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => $articleId, "id" => $tagId));
}
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$themes = $themRepo->findAll();
return $this->render('OnoMapBundle:Indefinition:add.html.twig', array(
"form" => $form->createView(),
"tag" => $tag,
"themes" => $themes
));
}
public function editAction(Request $request)
{
$manager = $this->getDoctrine()->getManager();
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->container->get('security.token_storage')->getToken()->getUser();
$userName = $user->getName();
$userFirstname = $user->getFirstname();
$hasName = false;
if (($userName && trim($userName) != "") || ($userFirstname && trim($userFirstname) != "")) {
$hasName = true;
}
} else {
return $this->redirectToRoute("ono_map_homepage");
}
$numArt = (int) $request->attributes->all()["article_id"];
$numTag = (int) $request->attributes->all()["tag_id"];
$numId = (int) $request->attributes->all()["id"];
if ($numArt == 0) {
$fromProfile = true;
} else {
$fromProfile = false;
}
$article = $manager->getRepository("OnoMapBundle:Article")->find($numArt);
if (!$article && !$fromProfile) {
return $this->redirectToRoute("ono_map_homepage");
}
$tag = $manager->getRepository("OnoMapBundle:Tag")->find($numTag);
if(!$tag) {
if ($fromProfile) {
return $this->redirectToRoute("fos_user_profile_show");
} else {
return $this->redirectToRoute("ono_map_article_view", array("id" => $numArt));
}
}
$indefinition = $manager->getRepository("OnoMapBundle:Indefinition")->find($numId);
if (!$indefinition) {
if ($fromProfile) {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => 0, "id" => $numTag));
} else {
return $this->redirectToRoute("ono_map_tag_view", array("art_id" => $numArt, "id" => $numTag));
}
}
if ($indefinition->getTag() === $tag) {
if (isset($user) && $hasName) {
if ($indefinition->testUser($user)) {
$form = $this->get('form.factory')->create(IndefinitionLogType::class, $indefinition);
} else {
if ($fromProfile) {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => 0, "id" => $numTag));
} else {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => $numArt, "id" => $numTag));
}
}
} else {
$form = $this->get('form.factory')->create(IndefinitionType::class, $indefinition);
}
} else {
if ($fromProfile) {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => 0, "id" => $numTag));
} else {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => $numArt, "id" => $numTag));
}
}
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($indefinition);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Indรฉfinition bien modifiรฉe.');
if ($fromProfile) {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => 0, "id" => $numTag));
} else {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => $numArt, "id" => $numTag));
}
}
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$themes = $themRepo->findAll();
return $this->render('OnoMapBundle:Indefinition:edit.html.twig', array(
"form" => $form->createView(),
"indefinition" => $indefinition,
"tag" => $tag,
"themes" => $themes
));
}
public function deleteAction(Request $request) {
$numArt = (int) $request->attributes->all()["article_id"];
$numTag = (int) $request->attributes->all()["tag_id"];
$numId = (int) $request->attributes->all()["id"];
if ($numArt == 0) {
$fromProfile = true;
} else {
$fromProfile = false;
}
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->container->get('security.token_storage')->getToken()->getUser();
} else {
return $this->redirectToRoute("ono_map_homepage");
}
$manager = $this->getDoctrine()->getManager();
$article = $manager->getRepository("OnoMapBundle:Article")->find($numArt);
if (!$article && !$fromProfile) {
return $this->redirectToRoute("ono_map_homepage");
}
$tag = $manager->getRepository("OnoMapBundle:Tag")->find($numTag);
if(!$tag) {
if ($fromProfile) {
return $this->redirectToRoute("fos_user_profile_show");
} else {
return $this->redirectToRoute("ono_map_article_view", array("id" => $numArt));
}
}
$indefinition = $manager->getRepository("OnoMapBundle:Indefinition")->find($numId);
if (!$indefinition) {
if ($fromProfile) {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => 0, "id" => $numTag));
} else {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => $numArt, "id" => $numTag));
}
}
if (!$user || $user !== $indefinition->getUser()) {
if ($fromProfile) {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => 0, "id" => $numTag));
} else {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => $numArt, "id" => $numTag));
}
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($indefinition);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "L'indรฉfinition a bien รฉtรฉ supprimรฉe.");
if ($fromProfile) {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => 0, "id" => $numTag));
} else {
return $this->redirectToRoute("ono_map_tag_view", array("article_id" => $numArt, "id" => $numTag));
}
}
$themes = $manager->getRepository('OnoMapBundle:Theme')->findAll();
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Indefinition:delete.html.twig', array(
'indefinition' => $indefinition,
'libTag' => $tag->getLibTag(),
'themes' => $themes,
'artId' => $numArt,
'tagId' => $numTag,
'pathDelete' => "ono_map_indefinition_delete",
'form' => $form->createView()
));
}
}
<file_sep><?php
// src/OC/PlatformBundle/Form/AdvertEditType.php
namespace Ono\MapBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Ono\MapBundle\Form\ResponseType;
class ResponseAdminType extends ResponseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('dtcreation', DateTimeType::class)
->add('published', CheckboxType::class, array("required"=> false))
->add('question', EntityType::class, array(
'class' => 'OnoMapBundle:Question',
'choice_label' => 'libQuestion',
'multiple' => false,
));
parent::buildForm($builder, $options);
}
public function getName()
{
return 'ono_admin_add_question';
}
// public function getParent()
// {
// return new ResponseType();
// }
}
<file_sep><?php
namespace Ono\MapBundle\Twig;
use Ono\MapBundle\Entity\Response;
use Ono\MapBundle\Entity\Article;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Ono\UserBundle\Entity\User;
class AppExtension extends \Twig_Extension
{
// , SecurityContext $context
public function __construct(ContainerInterface $container)
{
$this->container = $container;
}
public function getFilters()
{
return array(
new \Twig_SimpleFilter('isliking', array($this, 'isLiking'))
);
}
public function isLiking($object)
{
$user = $this->container->get('security.token_storage')->getToken()->getUser();
if($user instanceof User){
if($object instanceof Response){
if($user->isLiking($object)){
return true;
}
return false;
} elseif($object instanceof Article){
if($user->isLiking($object)){
return true;
}
}
}
return false;
}
public function getName()
{
return 'app_extension';
}
}
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Vich\UploaderBundle\Mapping\Annotation as Vich;
use Symfony\Component\HttpFoundation\File\File;
/**
* Resource
*
* @ORM\Table(name="resource")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\ResourceRepository")
* @Vich\Uploadable
*/
class Resource
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="legend", type="text")
*/
private $legend;
/**
* @var \DateTime
*
* @ORM\Column(name="created_at", type="datetime")
*/
private $createdAt;
/**
* @var \DateTime
*
* @ORM\Column(name="updated_at", type="datetime")
*/
private $updatedAt;
/**
* @var bool
*
* @ORM\Column(name="is_distant", type="boolean")
*/
private $isDistant;
/**
* @Vich\UploadableField(mapping="resource_file", fileNameProperty="fileName")
*
* @var File
*/
private $file;
/**
* @ORM\Column(type="string", length=255)
*
* @var string
*/
private $fileName;
/**
* Constructor
*/
public function __construct() {
$this->createdAt = new \DateTime();
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
*
* @return Resource
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set legend
*
* @param string $legend
*
* @return Resource
*/
public function setLegend($legend)
{
$this->legend = $legend;
return $this;
}
/**
* Get legend
*
* @return string
*/
public function getLegend()
{
return $this->legend;
}
/**
* Set createdAt
*
* @param \DateTime $createdAt
*
* @return Resource
*/
public function setCreatedAt($createdAt)
{
$this->createdAt = $createdAt;
return $this;
}
/**
* Get createdAt
*
* @return \DateTime
*/
public function getCreatedAt()
{
return $this->createdAt;
}
/**
* Set updatedAt
*
* @param \DateTime $updatedAt
*
* @return Resource
*/
public function setUpdatedAt($updatedAt)
{
$this->updatedAt = $updatedAt;
return $this;
}
/**
* Get updatedAt
*
* @return \DateTime
*/
public function getUpdatedAt()
{
return $this->updatedAt;
}
/**
* Set isDistant
*
* @param boolean $isDistant
*
* @return Resource
*/
public function setIsDistant($isDistant)
{
$this->isDistant = $isDistant;
return $this;
}
/**
* Get isDistant
*
* @return bool
*/
public function getIsDistant()
{
return $this->isDistant;
}
/**
* If manually uploading a file (i.e. not using Symfony Form) ensure an instance
* of 'UploadedFile' is injected into this setter to trigger the update. If this
* bundle's configuration parameter 'inject_on_load' is set to 'true' this setter
* must be able to accept an instance of 'File' as the bundle will inject one here
* during Doctrine hydration.
*
* @param File|\Symfony\Component\HttpFoundation\File\UploadedFile $file
*
* @return Resource
*/
public function setFile(File $file = null)
{
$this->file = $file;
if ($file) {
// It is required that at least one field changes if you are using doctrine
// otherwise the event listeners won't be called and the file is lost
$this->updatedAt = new \DateTimeImmutable();
}
return $this;
}
/**
* @return File|null
*/
public function getFile()
{
return $this->file;
}
/**
* @param string $fileName
*
* @return Resource
*/
public function setFileName($fileName)
{
$this->fileName = $fileName;
return $this;
}
/**
* @return string|null
*/
public function getFileName()
{
return $this->fileName;
}
}
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Article
*
* @ORM\Table(name="article")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\ArticleRepository")
*/
class Article
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="title", type="string", length=255)
*/
private $title;
/**
* @var string
*
* @ORM\Column(name="description", type="string", length=255, nullable=true)
*/
private $description;
/**
* @var string
*
* @ORM\Column(name="content", type="text")
*/
private $content;
/**
* @var bool
*
* @ORM\Column(name="published", type="boolean", nullable=true)
*/
private $published = false;
/**
* @var \DateTime
*
* @ORM\Column(name="dtcreation", type="datetime")
* @Assert\DateTime(message="Le Datetime donnรฉ est incorrect !")
*/
private $dtcreation;
/**
* @var integer
*
* @ORM\Column(name="nbLike", type="integer")
* @Assert\Type(type="integer", message="La valeur donnรฉe n'est pas un integer !")
*/
private $nbLikes = 0;
/**
* @ORM\ManyToMany(targetEntity="Ono\MapBundle\Entity\Theme", cascade={"persist"})
* @Assert\Valid()
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $themes;
/**
* @ORM\ManyToMany(targetEntity="Ono\MapBundle\Entity\Tag", cascade={"persist"}, inversedBy="articles")
* @Assert\Valid()
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $tags;
/**
* @ORM\ManyToOne(targetEntity="Ono\MapBundle\Entity\Country")
* @ORM\JoinColumn(nullable=false)
* @Assert\Valid()
*/
private $country;
/**
* @ORM\ManyToOne(targetEntity="Ono\MapBundle\Entity\Language")
* @ORM\JoinColumn(nullable=true)
* @Assert\Valid()
*/
private $language;
/**
* @ORM\ManyToOne(targetEntity="Ono\UserBundle\Entity\User", inversedBy="responses")
* @ORM\JoinColumn(nullable=true)
* @Assert\Valid()
*/
private $user;
/**
* Many Articles have Many Resources
* @ORM\ManyToMany(targetEntity="Ono\MapBundle\Entity\Resource", cascade={"persist", "remove"}, orphanRemoval=true)
* @ORM\JoinTable(name="articles_resources",
* joinColumns={@ORM\JoinColumn(name="article_id", referencedColumnName="id")},
* inverseJoinColumns={@ORM\JoinColumn(name="resource_id", referencedColumnName="id", unique=true)}
* )
*/
private $resources;
/**
* Constructor
*/
public function __construct()
{
$this->themes = new \Doctrine\Common\Collections\ArrayCollection();
$this->resources = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set title
*
* @param string $title
*
* @return Article
*/
public function setTitle($title)
{
$this->title = $title;
return $this;
}
/**
* Get title
*
* @return string
*/
public function getTitle()
{
return $this->title;
}
/**
* Set description
*
* @param string $description
*
* @return Article
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set content
*
* @param string $content
*
* @return Article
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set published
*
* @param boolean $published
*
* @return Article
*/
public function setPublished($published)
{
$this->published = $published;
return $this;
}
/**
* Get published
*
* @return bool
*/
public function getPublished()
{
return $this->published;
}
/**
* Set dtcreation
*
* @param \DateTime $dtcreation
*
* @return Article
*/
public function setDtcreation($dtcreation)
{
$this->dtcreation = $dtcreation;
return $this;
}
/**
* Get dtcreation
*
* @return \DateTime
*/
public function getDtcreation()
{
return $this->dtcreation;
}
/**
* Set nbLikes
*
* @param integer $nbLikes
*
* @return Article
*/
public function setNbLikes($nbLikes)
{
$this->nbLikes = $nbLikes;
return $this;
}
/**
* Get nbLikes
*
* @return integer
*/
public function getNbLikes()
{
return $this->nbLikes;
}
public function incrementLikes(){
$actual = $this->getNbLikes();
$new = $actual+1;
$this->setNbLikes($new);
return $new;
}
public function decrementLikes(){
$actual = $this->getNbLikes();
$new = $actual-1;
$this->setNbLikes($new);
return $new;
}
/**
* Add theme
*
* @param \Ono\MapBundle\Entity\Theme $theme
*
* @return Article
*/
public function addTheme(\Ono\MapBundle\Entity\Theme $theme)
{
$this->themes[] = $theme;
return $this;
}
/**
* Remove theme
*
* @param \Ono\MapBundle\Entity\Theme $theme
*/
public function removeTheme(\Ono\MapBundle\Entity\Theme $theme)
{
$this->themes->removeElement($theme);
}
/**
* Get themes
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getThemes()
{
return $this->themes;
}
/**
* Set country
*
* @param \Ono\MapBundle\Entity\Country $country
*
* @return Article
*/
public function setCountry(\Ono\MapBundle\Entity\Country $country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* @return \Ono\MapBundle\Entity\Country
*/
public function getCountry()
{
return $this->country;
}
/**
* Set language
*
* @param \Ono\MapBundle\Entity\Language $language
*
* @return Article
*/
public function setLanguage(\Ono\MapBundle\Entity\Language $language = null)
{
$this->language = $language;
return $this;
}
/**
* Get language
*
* @return \Ono\MapBundle\Entity\Language
*/
public function getLanguage()
{
return $this->language;
}
/**
* Set user
*
* @param \Ono\UserBundle\Entity\User $user
*
* @return Article
*/
public function setUser(\Ono\UserBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* @return \Ono\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
/**
* Add tag
*
* @param \Ono\MapBundle\Entity\Tag $tag
*
* @return Article
*/
public function addTag(\Ono\MapBundle\Entity\Tag $tag)
{
$this->tags[] = $tag;
return $this;
}
/**
* Remove tag
*
* @param \Ono\MapBundle\Entity\Tag $tag
*/
public function removeTag(\Ono\MapBundle\Entity\Tag $tag)
{
$this->tags->removeElement($tag);
}
/**
* Remove tag
*
* @param \Ono\MapBundle\Entity\Tag $tag
*/
public function removeTags()
{
$this->tags = null;
}
/**
* Get tags
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getTags()
{
return $this->tags;
}
/**
* Add resource
*
* @param \Ono\MapBundle\Entity\Resource $resource
*
* @return Article
*/
public function addResource(\Ono\MapBundle\Entity\Resource $resource)
{
$this->resources[] = $resource;
return $this;
}
public function temporyDeleteResource(){
$this->resources = [];
}
public function temporyDeleteUser(){
$this->user = null;
}
public function temporyDeleteTagsIndefs() {
$nbTags = count($this->tags);
for ($i = 0 ; $i < $nbTags ; $i++) {
$this->tags[$i] = [
"id" => $this->tags[$i]->getId(),
"libTag" => $this->tags[$i]->getLibTag()
];
}
}
/**
* Remove resource
*
* @param \Ono\MapBundle\Entity\Resource $resource
*/
public function removeResource(\Ono\MapBundle\Entity\Resource $resource)
{
$this->resources->removeElement($resource);
}
/**
* Get resources
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getResources()
{
return $this->resources;
}
}
<file_sep>//S'applique ร un รฉlรฉment du DOM, le Supprime du DOM
Node.prototype.remove = function(){
var parent = this.parentNode;
if(parent){
parent.removeChild(this);
}
}
// document.prototype.newEl = function(tag, classname, attributes=null){
// var result = document.createElement(tag);
// if(result){
// result.className = classname;
// for(current in attributes){
// result.setAttribute(current, attributes[current]);
// }
// } else {
// result = false;
// }
// return result;
// }
//
//
// Renvoi la position d'un รฉlรฉment
function getElementPosition(e, isCenter) {
var left = 0;
var top = 0;
if (isCenter == true) {
console.log("center")
left = e.offsetWidth / 2;
top = e.offsetWidth / 2;
}
/*Tant que l'on a un รฉlรฉment parent*/
while (e.offsetParent != undefined && e.offsetParent != null) {
/*On ajoute la position de l'รฉlรฉment parent*/
left += e.offsetLeft + (e.clientLeft != null ? e.clientLeft : 0);
top += e.offsetTop + (e.clientTop != null ? e.clientTop : 0);
e = e.offsetParent;
}
return {
x: left,
y: top
};
};
// Constructeur de bulle
function BubbleH(el, config){
this.content = el.getAttribute("data-help");
if(!this.content){
return false;
}
this.elementTarget = {
el: el,
position : getElementPosition(el),
width: el.offsetWidth,
height: el.offsetHeight
};
this.setConfig(config);
this.el = {};
if(!this.direction){
this.deductDirection();
}
this.generateHtml();
}
// Dรฉduit l'endroit ou la bulle apparait par rapport ร l'รฉlรฉment ciblรฉ
BubbleH.prototype.deductDirection = function(){
var width = document.body.offsetWidth;
var diff = {
left : this.elementTarget.position.x,
right : width - this.elementTarget.position.x + this.elementTarget.width,
top : this.elementTarget.position.y,
bottom : this.elementTarget.position.y + this.elementTarget.height
}
var xDirection, yDirection, xDiff, yDiff;
if(diff.left < diff.right){
xDirection = "right";
xDiff = diff.right - diff.left;
} else {
xDirection = "left";
xDiff = diff.left - diff.right;
}
if(diff.top < diff.bottom){
yDirection = "bottom";
yDiff = diff.bottom - diff.top;
} else {
yDirection = "top";
yDiff = diff.top - diff.bottom;
}
this.direction = xDirection;
}
// Gรฉnรจre le code HTML
BubbleH.prototype.generateHtml = function(){
var helperBox = document.createElement("div");
helperBox.id = "helperBox";
helperBox.style.width = this.elementTarget.width+"px";
helperBox.style.height = this.elementTarget.height+"px";
helperBox.style.top = this.elementTarget.position.y+"px";
helperBox.style.left = this.elementTarget.position.x+"px";
helperBox.className += this.focusWay;
this.el.box = helperBox;
var BubbleH = document.createElement("dir");
var cross = document.createElement("span");
cross.className = "cross";
BubbleH.appendChild(cross);
BubbleH.id= "BubbleH";
BubbleH.innerHTML = this.content;
BubbleH.className = this.direction;
switch(this.direction) {
case "left" :
BubbleH.style.top = this.elementTarget.position.y+(this.elementTarget.height/2)+"px";
BubbleH.style.left = this.elementTarget.position.x-10+"px";
break;
case "right":
BubbleH.style.top = this.elementTarget.position.y+(this.elementTarget.height/2)+"px";
BubbleH.style.left = this.elementTarget.position.x + this.elementTarget.width+10+"px";
break;
}
this.el.bubble = BubbleH;
}
// Gรจre la configuration de l'objet
BubbleH.prototype.setConfig = function(config={}){
if(this.elementTarget.el.getAttribute("data-bubble-direction")){
var bubbleDirection = this.elementTarget.el.getAttribute("data-bubble-direction");
if(bubbleDirection == "top" || bubbleDirection == "bottom" || bubbleDirection == "left" || bubbleDirection == "right"){
this.direction = bubbleDirection;
}
}
if(config.direction){
if(config.direction == "top" || config.direction == "bottom" || config.direction == "left" || config.direction == "right"){
this.direction = config.direction;
}
}
if(config.focusWay) {
this.focusWay = config.focusWay;
} else {
this.focusWay = "";
}
}
// Affiche l'รฉlรฉment, si un รฉlรฉment semblable existe, le supprime et l'affiche ร la place
BubbleH.prototype.display = function(){
var el1 = document.getElementById("helperBox");
var el2 = document.getElementById("BubbleH");
if(el1 ||ย el2){
el1.remove();
el2.remove();
}
document.body.appendChild(this.el.box);
document.body.appendChild(this.el.bubble);
}
InterfaceH = {
//Initialisation des objet de stockages
button: {},
config: {
bubble : {},
interface: {}
},
// Renvoie les instance de Bubble et les stocke dans un tableau
saveBubbles : function(){
var bubbles = [];
for(i=0; i<InterfaceH.items.length; i++){
bubbles.push(new BubbleH(InterfaceH.items[i], InterfaceH.config.bubble));
}
InterfaceH.bubbles = bubbles;
},
//Rรฉinitialie l'affichage des รฉlรฉments
hideHelpers:function(){
document.getElementById("helperBox").remove();
document.getElementById("BubbleH").remove();
if(InterfaceH.guideTutorialEl) InterfaceH.guideTutorialEl.remove();
InterfaceH.tutorialContainer.removeAttribute("data-helper-notice");
},
//////////////////////////////////
// Quand le tutoriel est lancรฉ //
//////////////////////////////////
//Passe ร l'รฉlement suivant
nextBubble:function(){
InterfaceH.count++;
if(InterfaceH.bubbles[InterfaceH.count]){
InterfaceH.bubbles[InterfaceH.count].display();
(function(){
var rank = InterfaceH.count;
InterfaceH.bubbles[rank].el.bubble.addEventListener("click", InterfaceH.nextBubble, false)
})();
} else {
InterfaceH.stopTutorial();
}
},
//Passe ร l'รฉlรฉment prรฉcรฉdent
previousBubble:function(){
InterfaceH.count--;
if(InterfaceH.bubbles[InterfaceH.count]){
InterfaceH.bubbles[InterfaceH.count].display();
} else {
document.removeEventListener("keydown", InterfaceH.startKeyPressEvent, false);
InterfaceH.hideHelpers();
}
},
displayGuide:function(){
document.body.appendChild(InterfaceH.guideContainer);
},
hideGuide: function(){
InterfaceH.guideContainer.remove();
},
///////////////////////
// Popin du tutoriel //
///////////////////////
//Ferme le popin du tutoriel
hideTutorialContainer:function(){
InterfaceH.tutorialContainer.className = InterfaceH.tutorialContainer.className.replace("big", "small");
},
//Affiche le popin du tutoriel
displayTutorialContainer:function(){
InterfaceH.tutorialContainer.className = InterfaceH.tutorialContainer.className.replace("small", "big");
},
//Test pour l'รฉvenement de dรฉfilement des bubble
startKeyPressEvent:function(event){
if(event.keyCode == 13 || event.keyCode == 32 || event.keyCode == 39 ){
InterfaceH.nextBubble();
} else if(event.keyCode == 37 || event.keyCode == 8){
InterfaceH.previousBubble();
}
},
/////////////////////////////
// Comportement Tutoriel //
/////////////////////////////
//Lance le tutoriel
launchTutorial: function(){
InterfaceH.saveBubbles();
InterfaceH.count = 0;
InterfaceH.hideTutorialContainer();
InterfaceH.bubbles[InterfaceH.count].display();
(function(){
var rank = InterfaceH.count;
InterfaceH.bubbles[rank].el.bubble.addEventListener("click", InterfaceH.nextBubble, false)
})();
InterfaceH.tutorialContainer.setAttribute("data-helper-notice", "stoptutorial")
InterfaceH.tutorialContainer.removeEventListener("click", InterfaceH.displayTutorialContainer, false);
InterfaceH.tutorialContainer.addEventListener("click", InterfaceH.stopTutorial, false);
if(InterfaceH.guideTutorialEl){
console.log(InterfaceH.guideTutorialEl);
document.body.appendChild(InterfaceH.guideTutorialEl);
}
document.addEventListener("keydown", InterfaceH.startKeyPressEvent, false)
},
//Arrete le tutoriel
stopTutorial: function(){
document.removeEventListener("keydown", InterfaceH.startKeyPressEvent, false);
InterfaceH.tutorialContainer.removeEventListener("click", InterfaceH.stopTutorial, false);
InterfaceH.tutorialContainer.addEventListener("click", InterfaceH.displayTutorialContainer, false);
InterfaceH.hideHelpers();
},
/////////////////////////////
// Initialisation //
/////////////////////////////
genTutoContainer:function(){
var tutorialContainer = document.createElement("div");
tutorialContainer.id = "tutorialContainer";
tutorialContainer.className = "small";
var tutorialActions = document.createElement("div");
tutorialActions.id = "tutorialActions";
var title = document.createElement("h2");
title.innerHTML = "Besoin d'aide ?<span>On vous explique tout !</span>";
var close = document.createElement("i");
close.id = "closeTutorialActions";
var startTutorial = document.createElement("a");
startTutorial.href = "#";
startTutorial.id= "help-launch-tutorial";
startTutorial.className = "helper-button";
startTutorial.innerHTML = "Commencer le tutoriel";
if(InterfaceH.config.interface.helpConsult){
var startHelp = document.createElement("a");
startHelp.href = "#";
startHelp.className = "helper-button";
startHelp.innerHTML = "Consulter l'aide";
}
tutorialActions.appendChild(title);
tutorialActions.appendChild(close);
tutorialActions.appendChild(startTutorial);
if(InterfaceH.config.interface.helpConsult){
tutorialActions.appendChild(startHelp);
}
tutorialContainer.appendChild(tutorialActions);
document.body.appendChild(tutorialContainer);
},
genGuide: function(){
var guideContainer = document.createElement("div");
var actionContainer = document.createElement("div");
var guideDisplay = document.createElement("div");
var next = document.createElement("span");
var previous = document.createElement("span");
var stop = document.createElement("span");
guideContainer.className = "guideContainer visible";
guideContainer.id = "tutorialManage";
next.className = "guideNext fa fa-arrow-circle-o-right";
previous.className = "guidePrevious fa fa-arrow-circle-o-left";
stop.className = "guideStop fa fa-stop-circle";
guideDisplay.className = "guideDisplay fa fa-chevron-up";
actionContainer.className = "actionContainer";
actionContainer.appendChild(previous);
actionContainer.appendChild(next);
actionContainer.appendChild(stop);
guideContainer.appendChild(guideDisplay);
guideContainer.appendChild(actionContainer);
next.addEventListener("click", function(){
InterfaceH.nextBubble();
}, false)
previous.addEventListener("click", function(){
InterfaceH.previousBubble();
}, false)
stop.addEventListener("click", function(){
InterfaceH.stopTutorial();
}, false);
guideDisplay.addEventListener("click", function(){
if(guideContainer.className.match("visible")){
guideContainer.className = guideContainer.className.replace("visible", "hidden");
} else if(guideContainer.className.match("hidden")){
guideContainer.className = guideContainer.className.replace("hidden", "visible");
}
}, false);
InterfaceH.guideTutorialEl = guideContainer;
},
initEvents:function(){
//Bouton de gestion
InterfaceH.tutorialContainer.addEventListener("click", InterfaceH.displayTutorialContainer, false);
//Bouton de lancement du tutoriel
InterfaceH.button.launch.addEventListener("click", function(e){
InterfaceH.launchTutorial();
e.stopPropagation();
}, false)
//Bouton de fermeture du popin de tutoriel
InterfaceH.closeTutorialActions.addEventListener("click", function(e){
InterfaceH.hideTutorialContainer();
e.stopPropagation();
}, false);
},
init: function(config={}){
//Trie les configurations passรฉ entre l'objet BubbleH et InterfaceH
if(config.focusWay == "border"){
InterfaceH.config.bubble.focusWay = "border";
}
if(config.focusWay == "background"){
InterfaceH.config.bubble.focusWay = "background";
}
if(config.tutorialGuide){
InterfaceH.config.interface.tutorialGuide = true;
}
if(config.helpConsult){
InterfaceH.config.interface.helpConsult = config.helpConsult;
}
//Rรฉcupรจre les รฉlements concernรฉ
InterfaceH.items = document.querySelectorAll("*[data-help]");
InterfaceH.genTutoContainer();
//Rรฉcupรฉration des รฉlรฉments nรฉcรฉssaire au fonctionnement normal
InterfaceH.button.launch = document.getElementById("help-launch-tutorial");
InterfaceH.tutorialContainer = document.getElementById("tutorialContainer");
InterfaceH.closeTutorialActions = document.getElementById("closeTutorialActions");
if(config.tutorialGuide){
InterfaceH.genGuide();
}
//Lance les รฉvenements
InterfaceH.initEvents()
}
}
//Systรจme d'alert
//EventListener pour activer aide sur un bouton
//Interface
<file_sep><?php
namespace Ono\UserBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Security\Core\User\UserInterface;
use FOS\UserBundle\Model\User as BaseUser;
use Symfony\Component\Validator\Constraints as Assert;
use Ono\MapBundle\Entity\Response;
use Ono\MapBundle\Entity\Article;
/**
* User
*
* @ORM\Table(name="user")
* @ORM\Entity(repositoryClass="Ono\UserBundle\Repository\UserRepository")
*/
class User extends BaseUser
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
protected $id;
/**
* @var \Text
*
* @ORM\Column(name="name", type="text", nullable=true)
*/
private $name;
/**
* @var \Text
*
* @ORM\Column(name="firstname", type="text", nullable=true)
*/
private $firstname;
/**
* @var \Date
*
* @ORM\Column(name="dtnaissance", type="date", nullable=true)
* @Assert\Date(message="La date donnรฉe est incorrecte !")
*/
private $dtnaissance;
/**
* @var \Text
*
* @ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
/**
* @ORM\ManyToOne(targetEntity="Ono\MapBundle\Entity\Country")
* @ORM\JoinColumn(nullable=true)
*/
private $country;
/**
* @ORM\ManyToOne(targetEntity="Ono\MapBundle\Entity\Language")
* @ORM\JoinColumn(nullable=true)
*/
private $language;
/**
* @ORM\OneToMany(targetEntity="Ono\MapBundle\Entity\Response", mappedBy="user")
* @ORM\JoinColumn(nullable=true)
*/
private $responses;
/**
* @ORM\ManyToMany(targetEntity="Ono\MapBundle\Entity\Response")
* @ORM\JoinColumn(nullable=true)
* @ORM\JoinTable(name="user_like_response")
*/
private $responsesLiked;
/**
* @ORM\ManyToMany(targetEntity="Ono\MapBundle\Entity\Article")
* @ORM\JoinColumn(nullable=true)
* @ORM\JoinTable(name="user_like_article")
*/
private $articlesLiked;
/**
* @ORM\OneToMany(targetEntity="Ono\MapBundle\Entity\Indefinition", mappedBy="user")
* @ORM\JoinColumn(nullable=true)
*/
private $indefinitions;
/**
* Set country
*
* @param \Ono\MapBundle\Entity\Country $country
*
* @return User
*/
public function setCountry(\Ono\MapBundle\Entity\Country $country = null)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* @return \Ono\MapBundle\Entity\Country
*/
public function getCountry()
{
return $this->country;
}
/**
* Set dtnaissance
*
* @param \DateTime $dtnaissance
*
* @return User
*/
public function setDtnaissance($dtnaissance)
{
$this->dtnaissance = $dtnaissance;
return $this;
}
/**
* Get dtnaissance
*
* @return \DateTime
*/
public function getDtnaissance()
{
return $this->dtnaissance;
}
/**
* Set description
*
* @param string $description
*
* @return User
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set language
*
* @param \Ono\MapBundle\Entity\Language $language
*
* @return User
*/
public function setLanguage(\Ono\MapBundle\Entity\Language $language)
{
$this->language = $language;
return $this;
}
/**
* Get language
*
* @return \Ono\MapBundle\Entity\Language
*/
public function getLanguage()
{
return $this->language;
}
/**
* Set name
*
* @param string $name
*
* @return User
*/
public function setName($name)
{
$this->name = $name;
return $this;
}
/**
* Get name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Set firstname
*
* @param string $firstname
*
* @return User
*/
public function setFirstname($firstname)
{
$this->firstname = $firstname;
return $this;
}
/**
* Get firstname
*
* @return string
*/
public function getFirstname()
{
return $this->firstname;
}
/**
* Add response
*
* @param \Ono\MapBundle\Entity\Response $response
*
* @return User
*/
public function addResponse(\Ono\MapBundle\Entity\Response $response)
{
$this->responses[] = $response;
return $this;
}
/**
* Remove response
*
* @param \Ono\MapBundle\Entity\Response $response
*/
public function removeResponse(\Ono\MapBundle\Entity\Response $response)
{
$this->responses->removeElement($response);
}
/**
* Get responses
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getResponses()
{
return $this->responses;
}
/**
* Add responsesLiked
*
* @param \Ono\MapBundle\Entity\Response $responsesLiked
*
* @return User
*/
public function addResponsesLiked(\Ono\MapBundle\Entity\Response $responsesLiked)
{
$this->responsesLiked[] = $responsesLiked;
return $this;
}
/**
* Remove responsesLiked
*
* @param \Ono\MapBundle\Entity\Response $responsesLiked
*/
public function removeResponsesLiked(\Ono\MapBundle\Entity\Response $responsesLiked)
{
$this->responsesLiked->removeElement($responsesLiked);
}
/**
* Get responsesLiked
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getResponsesLiked()
{
return $this->responsesLiked;
}
public function isLiking($object){
if($object instanceof Article){
$likes = $this->getArticlesLiked();
} else if($object instanceof Response){
$likes = $this->getResponsesLiked();
}
for($i=0; $i<count($likes); $i++){
if($likes[$i]->getId()===$object->getId()){
return true;
}
}
return false;
}
/**
* Add articlesLiked
*
* @param \Ono\MapBundle\Entity\Article $articlesLiked
*
* @return User
*/
public function addArticlesLiked(\Ono\MapBundle\Entity\Article $articlesLiked)
{
$this->articlesLiked[] = $articlesLiked;
return $this;
}
/**
* Remove articlesLiked
*
* @param \Ono\MapBundle\Entity\Article $articlesLiked
*/
public function removeArticlesLiked(\Ono\MapBundle\Entity\Article $articlesLiked)
{
$this->articlesLiked->removeElement($articlesLiked);
}
/**
* Get articlesLiked
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getArticlesLiked()
{
return $this->articlesLiked;
}
/**
* Add indefinition
*
* @param \Ono\MapBundle\Entity\Indefinition $indefinition
*
* @return User
*/
public function addIndefinition(\Ono\MapBundle\Entity\Indefinition $indefinition)
{
$this->indefinitions[] = $indefinition;
return $this;
}
/**
* Remove indefinition
*
* @param \Ono\MapBundle\Entity\Indefinition $indefinition
*/
public function removeIndefinition(\Ono\MapBundle\Entity\Indefinition $indefinition)
{
$this->indefinitions->removeElement($indefinition);
}
/**
* Get indefinitions
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getIndefinitions()
{
return $this->indefinitions;
}
}
<file_sep><?php
namespace Ono\MapBundle\Repository;
/**
* QuestionRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class QuestionRepository extends \Doctrine\ORM\EntityRepository
{
public function getQuestionsWithThemes(array $themesId)
{
$qb = $this->createQueryBuilder('q');
// On fait une jointure avec l'entitรฉ Category avec pour alias ยซ c ยป
$qb
->innerJoin('q.themes', 't')
;
// Puis on filtre sur le nom des catรฉgories ร l'aide d'un IN
$qb->where($qb->expr()->in('t.id', $themesId));
// La syntaxe du IN et d'autres expressions se trouve dans la documentation Doctrine
$qb->groupBy('q.id, q.libQuestion');
$qb->having('COUNT(q.id) = :themes_count');
$qb->setParameter('themes_count', count($themesId));
// Enfin, on retourne le rรฉsultat
return $qb
->getQuery()
->getResult()
;
}
public function getQuestionsWithIds(array $ids)
{
$qb = $this->createQueryBuilder('q');
// Puis on filtre sur le nom des catรฉgories ร l'aide d'un IN
$qb->where($qb->expr()->in('q.id', $ids));
// La syntaxe du IN et d'autres expressions se trouve dans la documentation Doctrine
// Enfin, on retourne le rรฉsultat
return $qb
->getQuery()
->getResult()
;
}
}
<file_sep><?php
namespace Ono\UserBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Finder\Exception\AccessDeniedException;
//Response already use;
use Ono\MapBundle\Entity\Response as ResponseQ;
use Ono\MapBundle\Entity\Question;
use Ono\MapBundle\Entity\Theme;
use Ono\MapBundle\Entity\Country;
use Ono\MapBundle\Entity\Language;
use Ono\UserBundle\Entity\User;
use Ono\UserBundle\Form\RegistrationAdminType;
//JSON
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class UserController extends Controller
{
public function promoteAction($id)
{
if($this->container->get('security.authorization_checker')->isGranted('ROLE_ADMIN')){
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array("id"=>$id));
if(!$user->hasRole('ROLE_ADMIN')){
$user->addRole('ROLE_ADMIN');
$userManager->updateUser($user);
}
return $this->render('OnoMapBundle:Admin:list-user.html.twig', array(
// ...
));
} else {
return new AccessDeniedException();
}
}
////////////////////////////////////
// Users
///////////////////////////////////
public function addAction(Request $request){
$user = new User();
$form = $this->get('form.factory')->create(RegistrationAdminType::class, $user);
// $form = $this->createForm(new RegistrationType(), $user);
// $form->submit($request);
if($request->isMethod('POST') && $form->isValid()) {
$userManager = $this->get('fos_user.user_manager');
$exists = $userManager->findUserBy(array('email' => $user->getEmail()));
if ($exists instanceof User) {
throw new HttpException(409, 'Email already taken');
}
$request->getSession()->getFlashBag()->add('notice', 'Utilisateur bien enregistrรฉe.');
$userManager->updateUser($user);
return redirectToRoute("ono_admin_list_user");
}
return $this->render('OnoMapBundle:Admin:add-user.html.twig', array(
"form"=> $form->createView()
));
}
public function listAction(Request $request){
$userManager = $this->get('fos_user.user_manager');
$users = $userManager->findUsers();
return $this->render('OnoMapBundle:Admin:list-user.html.twig', array(
"users"=>$users
));
}
public function deleteAction($id){
}
public function editAction(Request $request, $id){
// Pour rรฉcupรฉrer le service UserManager du bundle
$userManager = $this->get('fos_user.user_manager');
$user = $userManager->findUserBy(array("id"=>$id));
if($user){
$form = $this->get('form.factory')->create(RegistrationAdminType::class, $user);
// $form = $this->createForm(new RegistrationType(), $user);
// $form->submit($request);
dump($form);
exit;
if($request->isMethod('POST') && $form->isValid()) {
// $exists = $userManager->findUserBy(array('email' => $user->getEmail()));
// if ($exists instanceof User) {
// throw new HttpException(409, 'Email already taken');
// }
$request->getSession()->getFlashBag()->add('notice', 'Utilisateur bien enregistrรฉe.');
$userManager->updateUser($user);
return redirectToRoute("ono_admin_list_user");
}
return $this->render('OnoMapBundle:Admin:add-user.html.twig', array(
"form"=> $form->createView()
));
}
return $this->redirectToRoute("ono_admin_list_user");
}
}
<file_sep><?php
// src/AppBundle/Form/RegistrationType.php
namespace Ono\UserBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\HiddenType;
use Symfony\Component\Validator\Constraints\DateTime;
class ProfileFormType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->add('name', TextType::class, array(
"label"=>"Nom",
"required" => false
))
->add('firstname', TextType::class, array(
'label'=>"Prรฉnom"
))
->add('country', EntityType::class, array(
'class' => 'OnoMapBundle:Country',
'choice_label' => 'libCountry',
'multiple' => false,
))
->remove("current_password")
->add('current_password', HiddenType::class, array(
'translation_domain' => 'AcmeUserBundle',
'mapped' => false,
'required' => false,
))
->add('language', EntityType::class, array(
'class' => 'OnoMapBundle:Language',
'choice_label' => 'libLanguageFr',
'multiple' => false,
))
->add('description', TextareaType::class, array("required"=>false))
->add('dtnaissance', DateType::class, array(
"required" => false,
"label" => "Date de naissance",
"years" => range(1900, date("Y")),
"format" => "dd / MM / yyyy"
));
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\ProfileFormType';
// Or for Symfony < 2.8
// return 'fos_user_registration';
}
// For Symfony 2.x
public function getName()
{
return "fos_user_profile";
}
}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\sfWebRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Ono\MapBundle\Entity\Article;
use Ono\MapBundle\Entity\Tag;
use Ono\MapBundle\Entity\Resource;
use Ono\UserBundle\Entity\User;
use Ono\MapBundle\Form\ArticleType;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class ArticleController extends Controller
{
public function indexAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$themesRepo = $manager->getRepository("OnoMapBundle:Theme");
$themes = $themesRepo->findAll();
$articles = $repoArticle->findAll();
$routeName = $request->get('_route');
if($routeName === "ono_admin_list_articles") {
return $this->render('OnoMapBundle:Admin:list-articles.html.twig', array(
"articles" => $articles
));
}
return $this->render("OnoMapBundle:Article:index.html.twig", array(
"articles" => $articles,
"themes" => $themes
));
}
public function showAction(Request $request){
$parameters = $request->attributes->all();
$numId = (int) $parameters["id"];
if(isset($parameters["tag"])){
$numTag = (int) $parameters["tag"];
}
$manager = $this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$tagRepo = $manager->getRepository("OnoMapBundle:Tag");
$article = $repoArticle->find($numId);
if(isset($numTag)){
$helper = $this->container->get('vich_uploader.templating.helper.uploader_helper');
$tag = $tagRepo->find($numTag);
$articles = $tag->getArticles();
$articles = $articles->toArray();
foreach ($articles as $key => $value) {
if($value == $article) {
array_splice($articles, $key, 1);
}
}
if (count($articles)>0){
$article = $articles[floor(rand(0, count($articles)-1))];
}
}
if($article === null){
throw new NotFoundHttpException("La rรฉponse ร afficher n'existe pas.");
}
$themes = $themRepo->findAll();
return $this->render("OnoMapBundle:Article:show.html.twig", array(
"article" => $article,
"themes" =>$themes
));
}
public function addAction(Request $request){
$manager =$this->getDoctrine()->getManager();
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$tagRepo = $manager->getRepository("OnoMapBundle:Tag");
$articleRepo = $manager->getRepository("OnoMapBundle:Article");
$themes = $themRepo->findAll();
$article = new Article;
$article->setDtcreation(new \DateTime());
if($this->container->get('security.authorization_checker')->isGranted('ROLE_EDITOR')){
$user = $this->get('security.token_storage')->getToken()->getUser();
$article->setUser($user);
$form = $this->get('form.factory')->create(ArticleType::class, $article);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$article = $this->manageTagsType($article);
$manager->persist($article);
//On enregistre
$manager->flush();
return $this->redirectToRoute("ono_map_article_view", array(
"id" => $article->getId(),
"themes" => $themes
));
}
$routeName = $request->get('_route');
if($routeName === "ono_admin_add_article") {
return $this->render('OnoMapBundle:Admin:add-article.html.twig', array(
"article" => $article,
"form" => $form->createView()
));
}
return $this->render('OnoMapBundle:Article:add.html.twig', array(
'form' => $form->createView(),
"themes" => $themes
));
}
return $this->redirectToRoute("ono_map_article_index");
}
public function editAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager =$this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$tagRepo = $manager->getRepository("OnoMapBundle:Tag");
$themes = $themRepo->findAll();
$article = $repoArticle->find($numId);
$user = $this->get('security.token_storage')->getToken()->getUser();
if($article && $user instanceof User && $user->getId() === $article->getUser()->getId()){
if($this->container->get('security.authorization_checker')->isGranted('ROLE_EDITOR')){
$form = $this->get('form.factory')->create(ArticleType::class, $article);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$article = $this->manageTagsType($article);
$manager->persist($article);
//On enregistre
$manager->flush();
return $this->redirectToRoute("ono_map_article_view", array(
"id" => $article->getId(),
"themes" => $themes
));
}
$routeName = $request->get('_route');
if($routeName === "ono_admin_edit_article") {
return $this->render('OnoMapBundle:Admin:edit-article.html.twig', array(
"article" => $article,
"form" => $form->createView()
));
}
return $this->render('OnoMapBundle:Article:edit.html.twig', array(
'form' => $form->createView(),
"themes" => $themes,
"article" => $article
));
}
}
return $this->redirectToRoute("ono_map_article_view", array(
"id" => $numId
));
}
public function likeAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$article = $repoArticle->find($numId);
if($article){
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->get('security.token_storage')->getToken()->getUser();
if($user){
$isLiking = $user->isLiking($article);
if(!$isLiking){
$user->addArticlesLiked($article);
$article->incrementLikes();
$manager->persist($user);
$manager->persist($article);
$manager->flush();
}
if($request->isXmlHttpRequest()){
return new Response($this->getXhrLikesResponse(true, $article->getNbLikes(), $article->getId()));
}
}
}
return $this->redirectToRoute('ono_map_article_view', array('id' => $article->getId()));
}
//L'utilisateur n'est pas authentifiรฉ
return $this->redirectToRoute('ono_map_homepage');
}
public function unlikeAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$article = $repoArticle->find($numId);
if($article){
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->get('security.token_storage')->getToken()->getUser();
if($user){
$isLiking = $user->isLiking($article);
if($isLiking){
$user->removeArticlesLiked($article);
$article->decrementLikes();
$manager->persist($user);
$manager->persist($article);
$manager->flush();
}
if($request->isXmlHttpRequest()){
return new Response($this->getXhrLikesResponse(false, $article->getNbLikes(), $article->getId()));
}
return $this->redirectToRoute('ono_map_article_view', array('id' => $article->getId()));
}
}
return $this->redirectToRoute('ono_map_article_view', array('id' => $article->getId()));
}
//L'utilisateur n'est pas authentifiรฉ
return $this->redirectToRoute('ono_map_homepage');
}
public function deleteAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$article = $manager->getRepository('OnoMapBundle:Article')->find($numId);
// $resources = $manager->getRepository('OnoMapBundle:Resource');
if (null === $article) {
throw new NotFoundHttpException("L'article d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$articleResources = $article->getResources();
$count = count($articleResources);
for ($i = $count-1; $i >= 0; $i--) {
$article->removeResource($articleResources[$i]);
}
$manager->remove($article);
$manager->flush();
return $this->redirect($this->generateUrl('ono_admin_list_articles'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $article,
'title' => $article->getTitle(),
'pathDelete' => "ono_admin_delete_article",
'form' => $form->createView()
));
}
public function popupAction(Request $request){
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->get('security.token_storage')->getToken()->getUser();
}
// On rรฉcupรจre les paramรจtres de route
$numArt = (int) $request->attributes->all()["id"];
$numTag = (int) $request->attributes->all()["tag"];
// On prรฉpare le lien pour ajouter une indรฉfinition
$indefPersoLink = $this->generateUrl('ono_map_indefinition_add', array(
"article_id" => $numArt,
"tag_id" => $numTag
));
$seeMoreLink = $this->generateUrl('ono_map_tag_view', array(
"article_id" => $numArt,
"id" => $numTag
));
// On rรฉcupรจre les repositories nรฉcessaires
$manager = $this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$repoTag = $manager->getRepository("OnoMapBundle:Tag");
// On rรฉcupรจre les entitรฉs correspondantes
$article = $repoArticle->find($numArt);
$tag = $repoTag->find($numTag);
if($tag){
// On rรฉcupรจre tous les articles du tag en question sauf celui en cours
$tagArticles = $tag->getArticles()->toArray();
$key = 0;
foreach ($tagArticles as $tagArticle) {
if ($tagArticle == $article) {
array_splice($tagArticles, $key, 1);
}
$key++;
}
// Randomisation & si moins de 3, on prend tous les articles, sinon les 3 premiers
$articles = [];
if(count($tagArticles) > 0) {
shuffle($tagArticles);
if(count($tagArticles) < 3) {
$articles = $tagArticles;
} else {
$articles = [$tagArticles[0], $tagArticles[1], $tagArticles[2]];
}
}
$indefinitions = [];
$tagIndefs = $tag->getIndefinitions()->toArray();
if(count($tagIndefs) > 0) {
shuffle($tagIndefs);
foreach ($tagIndefs as $tagIndef) {
if (isset($user) && $user === $tagIndef->getUser()) {
$indefEditLink = $this->generateUrl('ono_map_indefinition_edit', array(
"article_id" => $numArt,
"tag_id" => $numTag,
"id" => $tagIndef->getId()
));
} else {
$indefEditLink = null;
}
$indefinitions[] = [
"content" => $tagIndef->getContent(),
"author" => $tagIndef->getAuthor(),
"indefEditLink" => $indefEditLink
];
}
}
if($request->isXmlHttpRequest()){
// REPONSE XHR
return new Response($this->getPopupResponse($tag->getLibTag(), $indefinitions, $indefPersoLink, $seeMoreLink, $articles));
}
}
return $this->redirectToRoute('ono_map_article_view', array('id' => $article->getId()));
}
private function getPopupResponse($libTag, $indefinitions, $indefPersoLink, $seeMoreLink, $articles) {
$helper = $this->container->get('vich_uploader.templating.helper.uploader_helper');
// Pour chaque article, on rรฉcupรจre le titre, l'image et le lien
$arts = [];
for($i = 0 ; $i < count($articles) ; $i++) {
$arts[$i]["link"] = $this->generateUrl('ono_map_article_view', array("id" => $articles[$i]->getId()));
$arts[$i]["title"] = $articles[$i]->getTitle();
$resources = $articles[$i]->getResources();
if(count($resources) != 0) {
$arts[$i]["image"] = $helper->asset($resources[0], 'file', 'Ono\\MapBundle\\Entity\\Resource');
} else {
$arts[$i]["image"] = null;
}
}
// On hydrate le tableau qui sera encodรฉ en JSON pour la rรฉponse XHR
$render = [];
$render["libTag"] = $libTag;
$render["indefinitions"] = $indefinitions;
$render["indefPersoLink"] = $indefPersoLink;
$render["seeMoreLink"] = $seeMoreLink;
$render["articles"] = $arts;
return json_encode($render);
}
private function getXhrLikesResponse($isLiking, $nbLikes, $id){
$render = [];
$render["nbLike"] = $nbLikes;
if($isLiking){
$render["liking"] = true;
$render["nextRoute"] = $this->generateUrl(
'ono_map_article_unlike',
array('id' => $id)
);
return json_encode($render);
}
$render["liking"] = false;
$render["nextRoute"] = $this->generateUrl(
'ono_map_article_like',
array('id' => $id)
);
return json_encode($render);
}
private function manageTagsType($article){
$manager = $this->getDoctrine()->getManager();
$tagRepo = $manager->getRepository("OnoMapBundle:Tag");
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
//Stocke les tags
$tags=$article->getTags();
//Supprime les tags actuel de l'article
$article->removeTags();
for($i=0; $i<count($tags); $i++){
//Dรฉtache du persistage les tags รฉditรฉs du formulaire
$manager->detach($tags[$i]);
//Initialise un tag
$tagSearch = null;
//Test si le libellรฉ existe dans la bdd
$tagSearch = $tagRepo->findOneBy(array(
"libTag" => $tags[$i]->getlibTag()
));
//Si il n'y a pas de tag dans la bdd on le crรฉe
if(!$tagSearch){
$tagSearch = new Tag;
$tagSearch->setLibTag($tags[$i]->getlibTag());
$tagSearch->setUsedCount(1);
}
//Si le tag est dรฉja dans la bdd, on met ร jour le comptage
if($tagSearch->getId()){
$amount = $repoArticle->getNbUsedCount($tagSearch->getId())[0]["amount"];
$tagSearch->setUsedCount($amount+1);
}
//On rajoute le nouveau tag ร l'article
$article->addTag($tagSearch);
}
return $article;
}
}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Finder\Exception\AccessDeniedException;
//Response already use;
use Ono\MapBundle\Entity\Response as ResponseQ;
use Ono\MapBundle\Entity\Question;
use Ono\MapBundle\Entity\Theme;
use Ono\MapBundle\Entity\Indefinition;
use Ono\MapBundle\Form\ResponseType;
use Ono\MapBundle\Form\ResponseAdminType;
use Ono\MapBundle\Form\IndefinitionType;
use Ono\MapBundle\Form\IndefinitionAdminType;
use Ono\MapBundle\Form\QuestionType;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class AdminController extends Controller
{
public function indexAction()
{
$manager = $this->getDoctrine()->getManager();
$questionRepo = $manager->getRepository("OnoMapBundle:Question");
$responseRepo = $manager->getRepository("OnoMapBundle:Response");
$themesRepo = $manager->getRepository("OnoMapBundle:Theme");
$serializer = $this->get('serializer');
$questions = $questionRepo->findAll();
$themes = $themesRepo->findAll();
return $this->render('OnoMapBundle:Admin:index.html.twig', array(
"questions" => $questions,
"themes" => $themes
));
}
////////////////////////////////////
// Questions
///////////////////////////////////
public function addQuestionAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$question = new Question;
$form = $this->get('form.factory')->create(QuestionType::class, $question);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($question);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Question bien enregistrรฉe.');
return $this->redirectToRoute("ono_admin_list_question");
}
return $this->render('OnoMapBundle:Admin:add-question.html.twig', array(
"form" => $form->createView()
));
}
public function listQuestionAction(){
$manager = $this->getDoctrine()->getManager();
$questions = $manager->getRepository("OnoMapBundle:Question")->findAll();
return $this->render('OnoMapBundle:Admin:list-question.html.twig', array(
"questions" => $questions
));
}
public function editQuestionAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$question = $manager->getRepository("OnoMapBundle:Question")->find($numId);
$form = $this->get('form.factory')->create(QuestionType::class, $question);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($question);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Question bien modifiรฉ.');
return $this->redirectToRoute("ono_admin_list_question");
}
return $this->render('OnoMapBundle:Admin:edit-question.html.twig', array(
"form" => $form->createView(),
"question" => $question
));
}
public function deleteQuestionAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$question = $manager->getRepository('OnoMapBundle:Question')->find($numId);
if (null === $question) {
throw new NotFoundHttpException("La question d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($question);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "La question a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_question'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $question,
'title' => $question->getLibQuestion(),
'pathDelete' => "ono_admin_delete_question",
'form' => $form->createView()
));
}
////////////////////////////////////
// Response
///////////////////////////////////
public function addResponseAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$response = new ResponseQ;
$form = $this->get('form.factory')->create(ResponseAdminType::class, $response);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($response);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Rรฉponse bien enregistrรฉe.');
return $this->redirectToRoute("ono_admin_list_response");
}
return $this->render('OnoMapBundle:Admin:add-response.html.twig', array(
"form" => $form->createView()
));
return $this->render('OnoMapBundle:Admin:add-response.html.twig', array());
}
public function listResponseAction(){
$manager = $this->getDoctrine()->getManager();
$responses = $manager->getRepository("OnoMapBundle:Response")->findAll();
return $this->render('OnoMapBundle:Admin:list-response.html.twig', array(
"responses" => $responses
));
}
public function editResponseAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$response = $manager->getRepository("OnoMapBundle:Response")->find($numId);
$form = $this->get('form.factory')->create(ResponseType::class, $response);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($response);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Rรฉponse bien modifiรฉ.');
return $this->redirectToRoute("ono_admin_list_response");
}
return $this->render('OnoMapBundle:Admin:edit-response.html.twig', array(
"form" => $form->createView(),
"response" => $response
));
}
public function deleteResponseAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$response = $manager->getRepository('OnoMapBundle:Response')->find($numId);
if (null === $response) {
throw new NotFoundHttpException("La rรฉponse d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($response);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "La rรฉponse a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_response'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $response,
'title' => $response->getQuestion()->getLibQuestion(),
'pathDelete' => "ono_admin_delete_response",
'form' => $form->createView()
));
}
////////////////////////////////////
// Indefinition
///////////////////////////////////
public function addIndefinitionAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$indefinition = new Indefinition;
$form = $this->get('form.factory')->create(IndefinitionAdminType::class, $indefinition);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$user = $this->container->get('security.token_storage')->getToken()->getUser();
$indefinition->setUser($user);
$manager->persist($indefinition);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Indรฉfinition bien enregistrรฉe.');
return $this->redirectToRoute("ono_admin_list_indefinitions");
}
return $this->render('OnoMapBundle:Admin:add-indefinition.html.twig', array(
"form" => $form->createView()
));
}
public function listIndefinitionAction(){
$manager = $this->getDoctrine()->getManager();
$indefinitions = $manager->getRepository("OnoMapBundle:Indefinition")->findAll();
return $this->render('OnoMapBundle:Admin:list-indefinition.html.twig', array(
"indefinitions" => $indefinitions
));
}
public function editIndefinitionAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$indefinition = $manager->getRepository("OnoMapBundle:Indefinition")->find($numId);
$form = $this->get('form.factory')->create(IndefinitionType::class, $indefinition);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($indefinition);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Indรฉfinition bien modifiรฉe.');
return $this->redirectToRoute("ono_admin_list_indefinitions");
}
return $this->render('OnoMapBundle:Admin:edit-indefinition.html.twig', array(
"form" => $form->createView(),
"indefinition" => $indefinition
));
}
public function deleteIndefinitionAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$indefinition = $manager->getRepository('OnoMapBundle:Indefinition')->find($numId);
if (null === $indefinition) {
throw new NotFoundHttpException("L'indรฉfinition d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($indefinition);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "L'indรฉfinition a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_indefinitions'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $indefinition,
'title' => $indefinition->getTag()->getLibTag(),
'indefContent' => $indefinition->getContent(),
'pathDelete' => "ono_admin_delete_indefinition",
'form' => $form->createView()
));
}
}
<file_sep><?php
namespace Ono\MapBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ono\MapBundle\Entity\Theme;
class LoadTheme extends AbstractFixture implements OrderedFixtureInterface
{
// Dans l'argument de la mรฉthode load, l'objet $manager est l'EntityManager
public function load(ObjectManager $manager)
{
$json = file_get_contents("web/json/theme.json");
$tab = (array) json_decode($json);
for($i=0; $i<count($tab); $i++){
$tab[$i] = (array) $tab[$i];
}
for ($i=0; $i<count($tab); $i++) {
// On crรฉe la catรฉgorie
$theme = new Theme();
$theme->setLibTheme($tab[$i]["libTheme"]);
$theme->setDescription($tab[$i]["description"]);
$theme->setCdTheme($tab[$i]["cdTheme"]);
// On la persiste
$manager->persist($theme);
}
// On dรฉclenche l'enregistrement de tous les thรจmes
$manager->flush();
}
public function getOrder() {
return 4;
}
}
<file_sep><?php
namespace Ono\MapBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\CollectionType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Ivory\CKEditorBundle\Form\Type\CKEditorType;
use Ono\MapBundle\Form\TagType;
use Ono\MapBundle\Form\ResourceType;
class ArticleType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
// ->add('content', TextareaType::class)
->add('title', TextType::class)
->add('description', TextareaType::class)
->add('content', CKEditorType::class, array(
'config' => array(
'uiColor' => '#ffffff',
)
))
->add('published', CheckboxType::class, array(
"required" => false
))
->add('country', EntityType::class, array(
'class' => 'OnoMapBundle:Country',
'choice_label' => 'libCountry',
'multiple' => false,
))
->add('tags', CollectionType::class, array(
'entry_type' => TagType::class,
'allow_add' => true,
'allow_delete' => true
))
->add('language', EntityType::class, array(
'class' => 'OnoMapBundle:Language',
'choice_label' => 'libLanguageFr',
'multiple' => false,
))
->add('themes', EntityType::class, array(
'class' => 'OnoMapBundle:Theme',
'choice_label' => 'libTheme',
'multiple' => true,
"expanded" => true
))
->add('resources', CollectionType::class, array(
'entry_type' => ResourceType::class,
'allow_add' => true,
'allow_delete' => true
))
->add('save', SubmitType::class)
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ono\MapBundle\Entity\Article'
));
}
}
<file_sep>
materializeForm = {
elements: {
input: [],
label: []
},
// Rรฉcupรฉre les รฉlรฉments
getElements: function() {
for (i = 0; i < materializeForm.elements.container.length; i++) {
materializeForm.elements.input.push(materializeForm.elements.container[i].getElementsByTagName("input")[0]);
materializeForm.elements.label.push(materializeForm.elements.container[i].getElementsByTagName("label")[0]);
}
},
//
setReset:function(){
for (i = 0; i < materializeForm.elements.label.length; i++) {
if (!materializeForm.elements.input[i].value) {
materializeForm.elements.label[i].className = "";
}
}
},
setFocus:function(rank){
for (i = 0; i < materializeForm.elements.label.length; i++) {
if (i === rank) {
materializeForm.elements.label[i].className = "focus";
} else if (!materializeForm.elements.input[i].value) {
materializeForm.elements.label[i].className = "";
}
}
},
setLabelPosition: function(rank, reset) {
if (reset) {
materializeForm.setReset();
} else {
materializeForm.setFocus(rank);
}
},
// Initialise un รฉvenement de clique
initEventClick: function(el, rank) {
if(el){
el.addEventListener("focus", function() {
materializeForm.setLabelPosition(rank);
}, false)
el.addEventListener("blur", function() {
materializeForm.setLabelPosition(rank, true);
}, false)
}
},
// Parcours les input et initialise les รฉlรฉments de click
initEventsFocus: function() {
for (i = 0; i < materializeForm.elements.input.length; i++) {
materializeForm.initEventClick(materializeForm.elements.input[i], i)
}
},
init: function() {
materializeForm.elements.container = document.getElementsByClassName("textfieldContainer");
if(!materializeForm.elements.container.length){
materializeForm.elements.container = document.getElementsByClassName("form-group");
}
if(materializeForm.elements.container.length){
materializeForm.getElements();
materializeForm.initEventsFocus();
// materializeForm.initEventKey();
}
}
}
function DynamicFormPrototype(args){
if(args.form) {
this.form = args.form;
this.prototype = this.form.getAttribute("data-prototype");
} else {
return false;
}
if(args.label){
this.label = args.label;
}
this.childrens = [];
this.index = this.form.children.length ? this.form.children.length : 0;
this.init();
}
DynamicFormPrototype.prototype.generatePrototype = function(){
var prototype = this.prototype.replace(/__name__label__/g, this.label).replace(/__name__/g, this.index)
var test = document.createElement("template");
test.innerHTML = prototype;
prototype = test.content.firstChild;
prototype.className += " dynamic-form-group";
this.form.appendChild(prototype);
this.index++
this.childrens.push(this.form.children[this.form.children.length-1]);
this.generateUpdateButton(this.form.children[this.form.children.length-1]);
}
DynamicFormPrototype.prototype.generateAddButton = function(){
var button = document.createElement("span");
button.className = "btn";
button.innerHTML = "Ajouter";
this.button = button
this.form.parentNode.appendChild(this.button);
}
DynamicFormPrototype.prototype.generateUpdateButton = function(el, notRemovable){
var buttonDelete = document.createElement("span");
var vichType = el.getElementsByClassName("vich-type");
var distantType = el.getElementsByClassName("distant-type")[0];
var fileType = vichType[0].firstChild;
var deleteCheckBox = vichType[0].lastChild;
var urlName = el.getElementsByClassName("url-type")[0];
distantType.parentNode.parentNode.parentNode.className += " form-right";
buttonDelete.className = "btn btn-danger";
if(notRemovable) {
vichType[0].className += " form-hide";
distantType.parentNode.parentNode.parentNode.className += " form-hide";
urlName.className = urlName.className.replace("form-hide", "form-display");
urlName.setAttribute("type", "output");
} else {
distantType.onclick = function(){
if(this.checked){
urlName.className = urlName.className.replace("form-hide", "form-display");
vichType[0].className = vichType[0].className.replace("form-display", "form-hide");
} else {
urlName.className = urlName.className.replace("form-display", "form-hide");
vichType[0].className = vichType[0].className.replace("form-hide", "form-display");
}
}
}
buttonDelete.innerHTML = "";
el.appendChild(buttonDelete);
buttonDelete.onclick = function(){
this.parentNode.remove();
}
}
DynamicFormPrototype.prototype.init = function(){
this.generateAddButton();
this.initEvents();
for(i=0; i<this.form.children.length; i++){
this.form.children[i].className += " dynamic-form-group";
this.generateUpdateButton(this.form.children[i], true);
this.childrens.push(this.form.children[i]);
}
}
DynamicFormPrototype.prototype.initEvents = function(){
var self = this;
this.button.addEventListener("click", function(e){
e.preventDefault();
self.generatePrototype();
return false;
}, false)
}
var dynamic = new DynamicFormPrototype({
form: document.getElementById("article_resources"),
label: "Fichier"
});
dynamicTag = {
els: [],
initEvent:function(){
dynamicTag.addbutton.addEventListener("click", function(){
dynamicTag.create();
console.log("Bonjour");
}, false)
},
create:function(inputValue = null){
var id = dynamicTag.lgt;
var formGroup = document.createElement("div");
var label = document.createElement("label");
var input = document.createElement("input");
if (inputValue){
input.value = inputValue;
}
var buttonSupp = document.createElement("button");
buttonSupp.className= "btn supp-tag";
buttonSupp.innerHTML = "Supprimer";
buttonSupp.setAttribute("data-id", id);
input.setAttribute("required", "required");
input.className = "tag-control";
input.name="article[tags]["+id+"][libTag]";
formGroup.className = "tag-group";
label.className="control-label required";
label.innerHTML = "Tag : "+id;
formGroup.appendChild(label);
formGroup.appendChild(input);
formGroup.appendChild(buttonSupp);
dynamicTag.initSuppButtonEvent(buttonSupp);
dynamicTag.container.appendChild(formGroup);
dynamicTag.els.push({
"group" : formGroup,
"input" : input,
"label": label,
"suppEl" : buttonSupp,
"id" : id
});
dynamicTag.lgt ++;
},
indent:function(){
for(i=0; i<dynamicTag.els.length; i++){
dynamicTag.els[i].input.name = dynamicTag.els[i].input.name.replace("article[tags]["+dynamicTag.els[i].id+"][libTag]", "article[tags]["+i+"][libTag]")
dynamicTag.els[i].label.innerHTML = "Tag : "+i;
dynamicTag.els[i].suppEl.setAttribute("data-id", i);
}
},
initSuppButtonEvent:function(el){
el.addEventListener("click", function(){
var id = this.getAttribute("data-id");
dynamicTag.els[id].group.remove();
dynamicTag.els.splice(id, 1);
dynamicTag.indent();
dynamicTag.lgt --;
}, false);
},
initChildren:function(){
dynamicTag.lgt = 0;
if(dynamicTag.container.getElementsByTagName("input")){
var inputs = dynamicTag.container.getElementsByTagName("input");
var value = [];
for(i=0; i<inputs.length; i++){
value.push(inputs[i].value)
}
dynamicTag.container.innerHTML = "";
for(i=0; i<value.length; i++){
dynamicTag.create(value[i]);
}
}
},
init:function(queryContainer){
dynamicTag.container = document.querySelector(queryContainer);
dynamicTag.queryId = queryContainer;
if(dynamicTag.container){
dynamicTag.initChildren()
dynamicTag.prototype = dynamicTag.container.getAttribute("data-prototype");
dynamicTag.addbutton=document.getElementById("add_item_dynamic");
if(dynamicTag.addbutton){
dynamicTag.initEvent();
}
}
}
}
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
/////////////////////////////////////////////////////////////
materializeForm.init();
<file_sep><?php
namespace Ono\UserBundle\DataFixtures\ORM;
use Ono\UserBundle\Entity\User;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\Persistence\ObjectManager;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Symfony\Component\DependencyInjection\ContainerAwareInterface;
use Symfony\Component\DependencyInjection\ContainerInterface;
class LoadUserData
extends AbstractFixture
implements OrderedFixtureInterface, ContainerAwareInterface
{
/**
* @var ContainerInterface
*/
private $container;
/**
* Load data fixtures with the passed EntityManager
* @param ObjectManager $manager
*/
public function load(ObjectManager $manager)
{
// Rรฉcupรฉration des repos pour langue & pays
$l_repo = $manager->getRepository("OnoMapBundle:Language");
$c_repo = $manager->getRepository("OnoMapBundle:Country");
// Rรฉcupรฉration du UserManager
$userManager = $this->container->get('fos_user.user_manager');
// Crรฉation d'un Admin
$admin = $userManager->createUser();
$admin->setUsername('admin');
$admin->setEmail('<EMAIL>');
$admin->setPlainPassword('<PASSWORD>');
$admin->setEnabled(true);
$admin->setName("Admin");
$admin->setFirstname("Mr");
$admin->addRole('ROLE_ADMIN');
$admin->setDtnaissance(date_create_from_format("Y-m-d", "1997-08-06"));
$admin->setDescription("Admin Ono");
$language = $l_repo->findOneByCdLanguage("fr");
$admin->setLanguage($language);
$country = $c_repo->findOneByCdCountry("fra");
$admin->setCountry($country);
$this->addReference('user-admin', $admin);
$userManager->updateUser($admin);
// Crรฉation d'un Admin
$editor = $userManager->createUser();
$editor->setUsername('editor');
$editor->setEmail('<EMAIL>');
$editor->setPlainPassword('<PASSWORD>');
$editor->setEnabled(true);
$editor->setName("Editor");
$editor->setFirstname("Mr");
$editor->addRole('ROLE_EDITOR');
$editor->setDtnaissance(date_create_from_format("Y-m-d", "1997-08-06"));
$editor->setDescription("Admin Ono");
$language = $l_repo->findOneByCdLanguage("fr");
$editor->setLanguage($language);
$country = $c_repo->findOneByCdCountry("fra");
$editor->setCountry($country);
$this->addReference('user-editor', $editor);
$userManager->updateUser($editor);
// Crรฉation d'un User
$user = $userManager->createUser();
$user->setUsername('user');
$user->setEmail('<EMAIL>');
$user->setPlainPassword('<PASSWORD>');
$user->setEnabled(true);
$user->addRole('ROLE_USER');
$user->setName("User");
$user->setFirstname("Mr");
$user->setDtnaissance(date_create_from_format("Y-m-d", "1999-06-03"));
$user->setDescription("User Ono");
$language = $l_repo->findOneByCdLanguage("zh");
$user->setLanguage($language);
$country = $c_repo->findOneByCdCountry("chn");
$user->setCountry($country);
$this->addReference('user-basic', $user);
$userManager->updateUser($user);
}
/**
* Sets the container.
* @param ContainerInterface|null $container A ContainerInterface instance or null
*/
public function setContainer(ContainerInterface $container = null)
{
$this->container = $container;
}
/**
* Get the order of this fixture
* @return integer
*/
public function getOrder()
{
return 3;
}
}
<file_sep>
//Ce fichier permet de stocker des informations importante pour le dรฉroullement
//du script, il se remplit donc au chargement de la page.
config = {}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Ono\MapBundle\Entity\Theme;
use Ono\MapBundle\Form\ThemeType;
class ThemeController extends Controller
{
public function updateSessionAction(Request $request) {
if ($request->request->get('xhr')) {
//Traitement du filtre des thรจmes
$filters = (array) json_decode($request->request->get("json"));
$request->getSession()->set("themes", $filters["themes"]);
$route = $this->getRefererRoute($request);
switch($route) {
case "ono_map_homepage":
return $this->redirectToRoute("ono_map_update_homepage");
break;
default:
return new Response("Cette route ne match pas !", 500);
}
return new Response("Pas de route !", 500);
}
return new Response("Error : Request not XHR argument");
}
public function addAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$theme = new Theme;
$form = $this->get('form.factory')->create(ThemeType::class, $theme);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($theme);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Thรจme bien enregistrรฉe.');
return $this->redirectToRoute("ono_admin_list_theme");
}
return $this->render('OnoMapBundle:Admin:add-theme.html.twig', array(
"form" => $form->createView()
));
}
public function listAction(){
$manager = $this->getDoctrine()->getManager();
$themes = $manager->getRepository("OnoMapBundle:Theme")->findAll();
return $this->render('OnoMapBundle:Admin:list-theme.html.twig', array(
"themes" => $themes
));
}
public function editAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$theme = $manager->getRepository("OnoMapBundle:Theme")->find($numId);
$form = $this->get('form.factory')->create(ThemeType::class, $theme);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($theme);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Thรจme bien modifiรฉ.');
return $this->redirectToRoute("ono_admin_list_theme");
}
return $this->render('OnoMapBundle:Admin:edit-theme.html.twig', array(
"form" => $form->createView(),
"theme" => $theme
));
}
public function deleteAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$theme = $manager->getRepository('OnoMapBundle:Theme')->find($numId);
if (null === $theme) {
throw new NotFoundHttpException("Le thรจme d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($theme);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "Le thรจme a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_theme'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $theme,
'title' => $theme->getLibTheme(),
'pathDelete' => "ono_admin_delete_theme",
'form' => $form->createView()
));
}
private function getRefererRoute(Request $request)
{
//look for the referer route
$referer = $request->headers->get('referer');
$lastPath = substr($referer, strpos($referer, $request->getBaseUrl()));
$lastPath = str_replace($request->getBaseUrl(), '', $lastPath);
$matcher = $this->get('router')->getMatcher();
$parameters = $matcher->match($lastPath);
$route = $parameters['_route'];
return $route;
}
}
<file_sep><?php
namespace Ono\MapBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ono\MapBundle\Entity\Country;
class LoadCountry extends AbstractFixture implements OrderedFixtureInterface
{
// Dans l'argument de la mรฉthode load, l'objet $manager est l'EntityManager
public function load(ObjectManager $manager)
{
$json = file_get_contents("web/json/country.json");
$tab = (array) json_decode($json);
for($i=0; $i<count($tab); $i++){
$tab[$i] = (array) $tab[$i];
}
for ($i=0; $i<count($tab); $i++) {
// On crรฉe la catรฉgorie
$country = new Country();
$country->setCdCountry($tab[$i]["cdCountry"]);
$country->setLibCountry($tab[$i]["country"]);
$country->setLibCapital($tab[$i]["capital"]);
$country->setLat((int) $tab[$i]["lat"]);
$country->setLn((int) $tab[$i]["lon"]);
// On la persiste
$manager->persist($country);
}
// On dรฉclenche l'enregistrement de tous les pays
$manager->flush();
}
public function getOrder() {
return 2;
}
}
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Language
*
* @ORM\Table(name="language")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\LanguageRepository")
*/
class Language
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="cdLanguage", type="string", length=255, unique=true)
* @Assert\Length(max=4, maxMessage="Le code langue ne doit pas dรฉpasser 4 caractรจres !")
*/
private $cdLanguage;
/**
* @var string
*
* @ORM\Column(name="libLanguageFr", type="string", length=255, unique=true)
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $libLanguageFr;
/**
* @var string
*
* @ORM\Column(name="libLanguageEn", type="string", length=255, unique=true)
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $libLanguageEn;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set cdLanguage
*
* @param string $cdLanguage
*
* @return Language
*/
public function setCdLanguage($cdLanguage)
{
$this->cdLanguage = $cdLanguage;
return $this;
}
/**
* Get cdLanguage
*
* @return string
*/
public function getCdLanguage()
{
return $this->cdLanguage;
}
/**
* Set libLanguageFr
*
* @param string $libLanguageFr
*
* @return Language
*/
public function setLibLanguageFr($libLanguageFr)
{
$this->libLanguageFr = $libLanguageFr;
return $this;
}
/**
* Get libLanguageFr
*
* @return string
*/
public function getLibLanguageFr()
{
return $this->libLanguageFr;
}
/**
* Set libLanguageEn
*
* @param string $libLanguageEn
*
* @return Language
*/
public function setLibLanguageEn($libLanguageEn)
{
$this->libLanguageEn = $libLanguageEn;
return $this;
}
/**
* Get libLanguageEn
*
* @return string
*/
public function getLibLanguageEn()
{
return $this->libLanguageEn;
}
}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\sfWebRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Finder\Exception\AccessDeniedException;
//Response already use;
use Ono\MapBundle\Entity\Response as ResponseQ;
use Ono\MapBundle\Entity\Question;
use Ono\MapBundle\Form\QuestionType;
class QuestionController extends Controller
{
//Action affichant la page d'accueil avec la carte
public function indexAction(Request $request, $numIds = null, $activeThemes)
{
//Initialisation
$manager = $this->getDoctrine()->getManager();
$questionRepo = $manager->getRepository("OnoMapBundle:Question");
$responseRepo = $manager->getRepository("OnoMapBundle:Response");
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
//On rรฉcupรจre les objets
$questions = $questionRepo->findAll();
$themes = $themRepo->findAll();
$themesActive = $request->getSession()->get("themes");
if(count($themesActive)>0 && $activeThemes==="active"){
$responses = $responseRepo->getResponses($themesActive, true);
} else {
$responses = $responseRepo->getResponses(false, true);
}
$routeName = $request->get('_route');
if($routeName === "ono_admin_list_question") {
return $this->render('OnoMapBundle:Admin:list-question.html.twig', array(
"questions" => $questions
));
}
//On retourne le tout
return $this->render('OnoMapBundle:Question:index.html.twig', array(
"questions" => $questions,
"responses" => $responses,
"themes" => $themes
));
}
public function viewAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$repoQ = $manager->getRepository("OnoMapBundle:Question");
$repoR = $manager->getRepository("OnoMapBundle:Response");
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$question = $repoQ->find($numId);
if($question === null){
throw new NotFoundHttpException("La question ร afficher n'existe pas.");
}
$responses = $repoR->findBy(array("question"=>$question));
$themes = $themRepo->findAll();
return $this->render("OnoMapBundle:Question:view.html.twig", array(
"question" => $question,
"responses" => $responses,
"themes" => $themes
));
}
public function editAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$question = $manager->getRepository("OnoMapBundle:Question")->find($numId);
$form = $this->get('form.factory')->create(QuestionType::class, $question);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($question);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Question bien modifiรฉ.');
return $this->redirectToRoute("ono_admin_list_question");
}
return $this->render('OnoMapBundle:Admin:edit-question.html.twig', array(
"form" => $form->createView(),
"question" => $question
));
}
public function addAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$question = new Question;
$form = $this->get('form.factory')->create(QuestionType::class, $question);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($question);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Question bien enregistrรฉe.');
return $this->redirectToRoute("ono_admin_list_question");
}
return $this->render('OnoMapBundle:Admin:add-question.html.twig', array(
"form" => $form->createView()
));
}
public function deleteAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$question = $manager->getRepository('OnoMapBundle:Question')->find($numId);
if (null === $question) {
throw new NotFoundHttpException("La question d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($question);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "La question a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_question'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $question,
'title' => $question->getLibQuestion(),
'pathDelete' => "ono_admin_delete_question",
'form' => $form->createView()
));
}
}
<file_sep><?php
namespace Ono\MapBundle\Repository;
/**
* ResponseRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ResponseRepository extends \Doctrine\ORM\EntityRepository
{
public function getResponses($themesId, $orderByLike){
$qb = $this->createQueryBuilder('r');
// On fait une jointure avec l'entitรฉ Category avec pour alias ยซ c ยป
$qb
->innerJoin('r.question', 'q')
->addSelect('q')
->innerJoin('q.themes', 't')
->addSelect('t')
;
// Puis on filtre sur le nom des catรฉgories ร l'aide d'un IN
if($themesId){
$qb->where($qb->expr()->in('r.id', $themesId));
}
if($orderByLike){
$qb->orderBy('r.nbLikes', 'ASC');
}
// La syntaxe du IN et d'autres expressions se trouve dans la documentation Doctrine
// Enfin, on retourne le rรฉsultat
return $qb
->getQuery()
->getResult()
;
}
}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\sfWebRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Finder\Exception\AccessDeniedException;
//Response already use;
use Ono\MapBundle\Entity\Response as ResponseQ;
use Ono\MapBundle\Entity\Question;
use Ono\MapBundle\Entity\LikeResponse;
use Ono\MapBundle\Form\ResponseType;
use Ono\MapBundle\Form\ResponseLogType;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class ResponseController extends Controller
{
// View Response
public function viewAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$repoReponse = $manager->getRepository("OnoMapBundle:Response");
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$response = $repoReponse->find($numId);
if($response === null){
throw new NotFoundHttpException("La rรฉponse ร afficher n'existe pas.");
}
$themes = $themRepo->findAll();
return $this->render("OnoMapBundle:Response:view.html.twig", array(
"response" => $response,
"themes" =>$themes
));
}
public function addAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager =$this->getDoctrine()->getManager();
$repoQuestion = $manager->getRepository("OnoMapBundle:Question");
$question = $repoQuestion->find($numId);
//On crรฉe le formulaire d'ajout de rรฉponse, qu'on modifiera dynamiquement aprรจs
if($question){
$response = new ResponseQ;
$response->setDtcreation(new \DateTime());
$response->setQuestion($question);
//Si un utilisateur est co on adapte le formulaire
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->get('security.token_storage')->getToken()->getUser();
$response->updateUser($user);
$form = $this->get('form.factory')->create(ResponseLogType::class, $response);
} else {
$form = $this->get('form.factory')->create(ResponseType::class, $response);
}
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager = $this->getDoctrine()->getManager();
$manager->persist($response);
$question->addResponse($response);
$manager->flush();
return $this->redirectToRoute('ono_map_response_view', array('id' => $response->getId()));
}
}
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$themes = $themRepo->findAll();
return $this->render('OnoMapBundle:Response:add.html.twig', array(
'form' => $form->createView(),
'question' =>$question,
"themes" => $themes
));
}
// public function addAction(Request $request)
// {
// $numId = (int) $request->attributes->all()["id"];
// $manager =$this->getDoctrine()->getManager();
// $repoQuestion = $manager->getRepository("OnoMapBundle:Question");
// $question = $repoQuestion->find($numId);
//
// //On crรฉe le formulaire d'ajout de rรฉponse, qu'on modifiera dynamiquement aprรจs
// if($question){
// $response = new ResponseQ;
// $response->setDtcreation(new \DateTime());
// $response->setQuestion($question);
//
// if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
// $user = $this->get('security.token_storage')->getToken()->getUser();
// $response->updateUser($user);
// $form = $this->get('form.factory')->create(ResponseLogType::class, $response);
// } else {
// $form = $this->get('form.factory')->create(ResponseType::class, $response);
// }
//
//
//
// if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
// $manager->persist($response);
// $question->addResponse($response);
// $manager->flush();
// dump("Bonjour");
// dump($response);
// exit;
// return new JsonResponse(array(
// "type"=>"notice",
// "title" => "Message bien enregistrรฉ"
// ));
// }
// }
//
//
// $question = $manager->getRepository("OnoMapBundle:Question")->find($numId);
// //Si il n'y a pas de rรฉponse
// if($question === null){
// throw new NotFoundHttpException("La question ร rรฉpondre n'existe pas.");
// }
//
// //On instancie la rรฉponse
// $response = new ResponseQ;
//
// //On dรฉfinis la date courante et la question affiliรฉ
// $response->setDtcreation(new \DateTime());
// $response->setQuestion($question);
// $response->setDtnaissance(new \DateTime());
//
// //On crรฉe le formulaire
// $form = $this->get('form.factory')->create(ResponseType::class, $response);
//
// if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
//
// dump(true);
// exit;
// dump($response);
// dump($question);
// exit;
//
// $manager = $this->getDoctrine()->getManager();
// $manager->persist($response);
// $question->addResponse($response);
// $manager->flush();
// return $this->redirectToRoute('ono_map_response_view', array('id' => $response->getId()));
// }
//
// $themRepo = $manager->getRepository("OnoMapBundle:Theme");
// $themes = $themRepo->findAll();
//
// return $this->render('OnoMapBundle:Response:add.html.twig', array(
// 'form' => $form->createView(),
// 'question' =>$question,
// "themes" => $themes
// ));
//
//
//
// $manager->persist($response);
// $manager->flush();
//
// return $this->redirectToRoute('ono_map_response_view', array(
// "id" => $response->getId()
// ));
// }
public function likeAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$repoResponse = $manager->getRepository("OnoMapBundle:Response");
$response = $repoResponse->find($numId);
if($response){
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->get('security.token_storage')->getToken()->getUser();
if($user){
$isLiking = $user->isLiking($response);
if(!$isLiking){
$user->addResponsesLiked($response);
$response->incrementLikes();
$manager->persist($user);
$manager->persist($response);
$manager->flush();
}
if($request->isXmlHttpRequest()){
return new Response($this->getXhrLikesResponse(true, $response->getNbLikes(), $response->getId()));
}
$request->getSession()->getFlashBag()->add('notice', 'La rรฉponse est dรฉja aimรฉ.');
return $this->redirectToRoute('ono_map_response_view', array('id' => $response->getId()));
}
}
return $this->redirectToRoute('ono_map_response_view', array('id' => $response->getId()));
} else {
$request->getSession()->getFlashBag()->add('notice', 'La rรฉponse n\'existe pas.');
}
//L'utilisateur n'est pas authentifiรฉ
return $this->redirectToRoute('ono_map_homepage');
}
public function unlikeAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$repoResponse = $manager->getRepository("OnoMapBundle:Response");
$response = $repoResponse->find($numId);
if($response){
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->get('security.token_storage')->getToken()->getUser();
if($user){
$isLiking = $user->isLiking($response);
if($isLiking){
$user->removeResponsesLiked($response);
$response->decrementLikes();
$manager->persist($user);
$manager->persist($response);
$manager->flush();
}
if($request->isXmlHttpRequest()){
return new Response($this->getXhrLikesResponse(false, $response->getNbLikes(), $response->getId()));
}
$request->getSession()->getFlashBag()->add('notice', 'La rรฉponse n\'est pas aimรฉ.');
return $this->redirectToRoute('ono_map_response_view', array('id' => $response->getId()));
}
//La response n'existe pas
}
return $this->redirectToRoute('ono_map_response_view', array('id' => $response->getId()));
}
//L'utilisateur n'est pas authentifiรฉ
return $this->redirectToRoute('ono_map_homepage');
}
private function getXhrLikesResponse($isLiking, $nbLikes, $id){
$render = [];
$render["nbLike"] = $nbLikes;
if($isLiking){
$render["liking"] = true;
$render["nextRoute"] = $this->generateUrl(
'ono_map_response_unlike',
array('id' => $id)
);
return json_encode($render);
}
$render["liking"] = false;
$render["nextRoute"] = $this->generateUrl(
'ono_map_response_like',
array('id' => $id)
);
return json_encode($render);
}
}
<file_sep><?php
namespace Ono\MapBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\FileType;
use Vich\UploaderBundle\Form\Type\VichFileType;
class ResourceType extends AbstractType
{
/**
* {@inheritdoc}
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('title', TextType::class, array(
"label" => false,
"attr"=> array(
"placeholder" => "Titre"
)
))
->add('legend', TextType::class, array(
"label" => false,
"attr"=> array(
"placeholder" => "Lรฉgende"
)
))
->add('file', VichFileType::class, array(
"required" => false,
"label"=> false,
"attr"=> array(
"class" => "vich-type form-display"
)
))
->add('filename', TextType::class, array(
"label"=> false,
"required" => false,
"attr"=> array(
"placeholder" => "URL",
"class" => "url-type form-hide"
)
))
->add('isDistant', CheckboxType::class, array(
"label" => "Distant",
"required" => false,
"attr"=> array(
"class"=>"distant-type"
)
))
;
}
/**
* {@inheritdoc}
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ono\MapBundle\Entity\Resource'
));
}
/**
* {@inheritdoc}
*/
public function getBlockPrefix()
{
return 'ono_mapbundle_resource';
}
}
<file_sep><?php
namespace Ono\UXInteractiveBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class OnoUXInteractiveBundle extends Bundle
{
}
<file_sep># <img src="https://raw.githubusercontent.com/SolalDR/Ono/master/web/asset/img/logo-name.png" alt="Ono" width="400" />
[](https://codeclimate.com/github/SolalDR/Ono)
A Symfony project created on September 15, 2016, 10:30 am.
## Initialisation :
#### Prรฉ-requis
Assurez-vous d'avoir votre serveur web en cours de fonctionnement (MySQL inclus)
#### Alias-Symfony
- Installer Alias-Symfony (crรฉรฉ par SolalDR) ร l'aide de son README pour simplifier les commandes
https://github.com/SolalDR/alias-symfony
#### Configuration de PHP (Timezone)
- Trouver le rรฉpertoire de votre php.ini (configuration PHP) avec la commande :
```
php -i | grep php.ini
```
- Placez-vous dans le dossier trouvรฉ (par exemple /etc)
- Si vous n'avez qu'un fichier php.ini.default, copiez-le en php.ini avec la commande cp
- Ouvrez php.ini avec un รฉditeur de texte (ex: nano), recherchez la ligne avec date.timezone et modifiez lร ainsi :
```
date.timezone = Europe/Paris
```
#### Rรฉcupรฉration du repo & Composer
- Dans le rรฉpertoire de votre serveur web, clonez le repository
```
git clone https://github.com/SolalDR/Ono.git
```
- Allez dans le dossier Ono et tรฉlรฉchargez Composer
- Pour Linux :
```
wget https://getcomposer.org/composer.phar
```
- Pour Mac :
```
curl https://getcomposer.org/composer.phar -o composer.phar
```
#### Configuration locale du projet
- Installer les dรฉpendances d'Ono avec Composer
```
php composer.phar install
```
Pour les paramรจtres :
- Laissez par dรฉfaut :
- database_host (127.0.0.1)
- database_port (8888)
- database_name (db-ono)
- database_user (root)
- database_password (<PASSWORD>)
- mailer_transport (smtp)
- mailer_host (127.0.0.1)
- mailer_user (null)
- mailer_password (null)
- secret (51c22993d139d305998644299354a849fbdd16dd)
- unix_socket laissez par dรฉfaut (null)
Sur Mac, si vous obtenez une erreur comme "No such file or directory" :
- Supprimez le fichier app/config/parameters.yml
- Recommencez l'installation des dรฉpendances
- Pour "unix_socket", mettez cette valeur : /Applications/MAMP/tmp/mysql.sock
- Une erreur peut apparaรฎtre car la base de donnรฉes "db-ono" n'existe pas. Dans tous les cas, crรฉez-lร :
```
Symfony db create
```
- Finissez l'installation des dรฉpendances d'Ono pour vรฉrifier que vous n'avez plus d'erreur
```
php composer.phar install
```
- Installer la structure de la base de donnรฉes
```
Symfony update -f
```
- Installer les fixtures pour la base de donnรฉes
```
Symfony load fixtures
```
===
## Rappel pour les dรฉveloppeurs :
### Installer Sass
SASS a รฉtรฉ implรฉmenter pour gรฉrer les assets. Si vous ne disposer pas de sass, vous pouvez l'installer en lanรงant :
```
gem install sass
```
Sass utilise ruby, passez ici si vous n'avez pas gem
https://rubygems.org/pages/download
####Afin de lancer le watching des assets et mettre ร jour vos css :
Depuis la racine Ono
```
cd src/Ono/MapBundle/Resources/public/
```
Lancer la commande :
```
sass --watch sass/application.sass:css/style.css
```
### Pour rรฉcupรฉrer code avant de push ses modifications :
```
git stash // Met ses modifications locales de cรดtรฉ
git pull // Rรฉcupรจre les รฉventuelles mises ร jour sur le repo
git stash apply // Rรฉcupรจre ses modifications locales
git add . // Ajoute les modifications
git commit -m "Votre commentaire de commit"
git push
```
### Pour gรฉrer les utilisateurs :
- Promouvoire :
```
php bin/console fos:user:promote monutilisateur ROLE_ADMIN
```
- Rรฉtrograder :
```
php bin/console fos:user:demote monutilisateur ROLE_ADMIN
```
- Crรฉer :
```
php bin/console fos:user:create monutilisateur <EMAIL> motdepasse
```
### Pour installation CKEditor :
- Lancer cette commande aprรจs mise en place
```
php bin/console assets:install web --symlink
```
===
## Liens externes :
Affichage article ร la Pinterest :
http://codepen.io/dudleystorey/pen/yqrhw
Pour plus d'informations sur CKEditor :
http://symfony.com/doc/current/bundles/IvoryCKEditorBundle/index.html
Lien utile pour upload de vidรฉo
https://openclassrooms.com/forum/sujet/upload-de-video-symfony2-85865
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Bridge\Doctrine\Validator\Constraints\UniqueEntity;
/**
* Theme
*
* @ORM\Table(name="theme")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\ThemeRepository")
* @UniqueEntity(fields="cdTheme", message="Le code thรจme est dรฉjร utilisรฉ !")
*/
class Theme
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="libTheme", type="string", length=255, unique=true)
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
* @Assert\Length(min=2, minMessage="Le nom du thรจme doit รชtre au minimum de 2 caractรจres !")
*/
private $libTheme;
/**
* @var string
*
* @ORM\Column(name="description", type="text", nullable=true)
*/
private $description;
//Utile notamment pour les picto associรฉ
/**
* @var string
*
* @ORM\Column(name="cdTheme", type="string", length=255, unique=true)
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
* @Assert\Length(min=3, minMessage="La longueur du code thรจme doit รชtre au minimum de 3 caractรจres !")
* @Assert\Regex(pattern="/^[a-z]+$/", message="Le code thรจme ne doit contenir que des letres minuscules sans accent !")
*/
private $cdTheme;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set libTheme
*
* @param string $libTheme
*
* @return Theme
*/
public function setLibTheme($libTheme)
{
$this->libTheme = $libTheme;
return $this;
}
/**
* Get libTheme
*
* @return string
*/
public function getLibTheme()
{
return $this->libTheme;
}
/**
* Set description
*
* @param string $description
*
* @return Theme
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
/**
* Get description
*
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* Set cdTheme
*
* @param string $cdTheme
*
* @return Theme
*/
public function setCdTheme($cdTheme)
{
$this->cdTheme = $cdTheme;
return $this;
}
/**
* Get cdTheme
*
* @return string
*/
public function getCdTheme()
{
return $this->cdTheme;
}
}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Ono\MapBundle\Entity\Language;
use Ono\MapBundle\Form\LanguageType;
class LanguageController extends Controller
{
public function addAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$language = new Language;
$form = $this->get('form.factory')->create(LanguageType::class, $language);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($language);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Langue bien enregistrรฉe.');
return $this->redirectToRoute("ono_admin_list_language");
}
return $this->render('OnoMapBundle:Admin:add-language.html.twig', array(
"form" => $form->createView()
));
}
public function indexAction(){
$manager = $this->getDoctrine()->getManager();
$languages = $manager->getRepository("OnoMapBundle:Language")->findAll();
return $this->render('OnoMapBundle:Admin:list-language.html.twig', array(
"languages" => $languages
));
}
public function editAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$language = $manager->getRepository("OnoMapBundle:Language")->find($numId);
$form = $this->get('form.factory')->create(LanguageType::class, $language);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($language);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Langue bien modifiรฉe.');
return $this->redirectToRoute("ono_admin_list_language");
}
return $this->render('OnoMapBundle:Admin:edit-language.html.twig', array(
"form" => $form->createView(),
"language" => $language
));
}
public function deleteAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$language = $manager->getRepository('OnoMapBundle:Language')->find($numId);
if (null === $language) {
throw new NotFoundHttpException("La langue d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($language);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "La langue a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_language'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $language,
'title' => $language->getLibLanguageFr(),
'pathDelete' => "ono_admin_delete_language",
'form' => $form->createView()
));
}
}
<file_sep><?php
namespace Ono\MapBundle;
use Symfony\Component\HttpKernel\Bundle\Bundle;
class OnoMapBundle extends Bundle
{
}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Finder\Exception\AccessDeniedException;
//Response already use;
use Ono\MapBundle\Entity\Country;
use Ono\MapBundle\Form\CountryType;
class CountryController extends Controller
{
////////////////////////////////////
// Country
///////////////////////////////////
public function addAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$country = new Country;
$form = $this->get('form.factory')->create(CountryType::class, $country);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($country);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Pays bien enregistrรฉe.');
return $this->redirectToRoute("ono_admin_list_country");
}
return $this->render('OnoMapBundle:Admin:add-country.html.twig', array(
"form" => $form->createView()
));
}
public function indexAction(){
$manager = $this->getDoctrine()->getManager();
$countries = $manager->getRepository("OnoMapBundle:Country")->findAll();
return $this->render('OnoMapBundle:Admin:list-country.html.twig', array(
"countries" => $countries
));
}
public function editAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$country = $manager->getRepository("OnoMapBundle:Country")->find($numId);
$form = $this->get('form.factory')->create(CountryType::class, $country);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($country);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Pays bien modifiรฉ.');
return $this->redirectToRoute("ono_admin_list_country");
}
return $this->render('OnoMapBundle:Admin:edit-country.html.twig', array(
"form" => $form->createView(),
"country" => $country
));
}
public function deleteAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$country = $manager->getRepository('OnoMapBundle:Country')->find($numId);
if (null === $country) {
throw new NotFoundHttpException("Le pays d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($country);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "Le pays a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_country'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $country,
'title' => $country->getLibCountry(),
'pathDelete' => "ono_admin_delete_country",
'form' => $form->createView()
));
}
}
<file_sep><?php
namespace Ono\MapBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ono\MapBundle\Entity\Question;
use Ono\MapBundle\Entity\Response;
class LoadQR extends AbstractFixture implements OrderedFixtureInterface
{
// Dans l'argument de la mรฉthode load, l'objet $manager est l'EntityManager
public function load(ObjectManager $manager)
{
// Rรฉcupรฉration des repositories
$t_repo = $manager->getRepository("OnoMapBundle:Theme");
$c_repo = $manager->getRepository("OnoMapBundle:Country");
$l_repo = $manager->getRepository("OnoMapBundle:Language");
// Rรฉcupรฉration des questions
$ques_json = file_get_contents("web/json/question.json");
$ques_tab = (array) json_decode($ques_json);
for($i=0; $i<count($ques_tab); $i++){
$ques_tab[$i] = (array) $ques_tab[$i];
}
// Rรฉcupรฉration des rรฉponses
$resp_json = file_get_contents("web/json/response.json");
$resp_tab = (array) json_decode($resp_json);
for($i=0; $i<count($resp_tab); $i++){
$resp_tab[$i] = (array) $resp_tab[$i];
}
for ($i=0; $i<count($ques_tab); $i++) {
// On crรฉe la catรฉgorie
$question = new Question();
$question->setLibQuestion($ques_tab[$i]["libQuestion"]);
$themes = $t_repo->findBy(array("cdTheme" => $ques_tab[$i]["cdThemes"]));
// Ajout des thรจmes
for ($j=0; $j < count($themes); $j++) {
$question->addTheme($themes[$j]);
}
// On la persiste
$manager->persist($question);
for ($j=0; $j < 2; $j++) {
$k = 2*$i + $j;
// Crรฉation d'une rรฉponse associรฉe ร la question (avec paramรจtres)
$response = new Response();
$response->setContent($resp_tab[$k]["content"]);
$response->setDtcreation(date_create_from_format("Y-m-d G:i:s", $resp_tab[$k]["dtcreation"]));
$response->setAuthor($resp_tab[$k]["author"]);
$response->setDtnaissance(date_create_from_format("Y-m-d", $resp_tab[$k]["dtnaissance"]));
$response->setPublished($resp_tab[$k]["published"]);
$country = $c_repo->findOneByCdCountry($resp_tab[$k]["cdCountry"]);
$response->setCountry($country);
$language = $l_repo->findOneBy(array("cdLanguage" => $resp_tab[$k]["cdLanguage"]));
$response->setLanguage($language);
// Relation Q-R cรดtรฉ rรฉponse
$response->setQuestion($question);
$manager->persist($response);
// Relation Q-R cรดtรฉ question
$question->addResponse($response);
$manager->persist($question);
}
}
// On dรฉclenche l'enregistrement de toutes les catรฉgories
$manager->flush();
}
public function getOrder() {
return 5;
}
}
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Response
*
* @ORM\Table(name="response")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\ResponseRepository")
*/
class Response
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="content", type="text")
* @Assert\NotBlank()
* @Assert\Length(min=30, minMessage="La longueur de la rรฉponse doit รชtre au minimum de 30 caractรจres !")
*/
private $content;
/**
* @var \DateTime
*
* @ORM\Column(name="dtcreation", type="datetime")
* @Assert\DateTime(message="Le Datetime donnรฉ est incorrect !")
*/
private $dtcreation;
/**
* @var \Date
*
* @ORM\Column(name="dtnaissance", type="date")
* @Assert\Date(message="La date donnรฉe est incorrecte !")
*/
private $dtnaissance;
/**
* @var string
*
* @ORM\Column(name="author", type="string", length=255)
* @Assert\Length(min=2, minMessage="Le nom doit รชtre au minimum de 2 caractรจres !")
*/
private $author;
/**
* @var bool
*
* @ORM\Column(name="published", type="boolean")
* @Assert\Type(type="bool", message="La valeur donnรฉe n'est pas un boolรฉen !")
*/
private $published = false;
/**
* @var integer
*
* @ORM\Column(name="nbLike", type="integer")
* @Assert\Type(type="integer", message="La valeur donnรฉe n'est pas un integer !")
*/
private $nbLikes = 0;
/**
* @ORM\ManyToOne(targetEntity="Ono\MapBundle\Entity\Question", inversedBy="responses")
* @ORM\JoinColumn(nullable=false)
* @Assert\Valid()
*/
private $question;
/**
* @ORM\ManyToOne(targetEntity="Ono\MapBundle\Entity\Country")
* @ORM\JoinColumn(nullable=false)
* @Assert\Valid()
*/
private $country;
/**
* @ORM\ManyToOne(targetEntity="Ono\MapBundle\Entity\Language")
* @ORM\JoinColumn(nullable=true)
* @Assert\Valid()
*/
private $language;
/**
* @ORM\ManyToOne(targetEntity="Ono\UserBundle\Entity\User", inversedBy="responses")
* @ORM\JoinColumn(nullable=true)
* @Assert\Valid()
*/
private $user;
/**
* @ORM\OneToOne(targetEntity="Ono\MapBundle\Entity\Resource", cascade={"persist", "remove"}, orphanRemoval=true)
* @ORM\JoinColumn(nullable=true)
*/
private $resource;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set content
*
* @param string $content
*
* @return Response
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set dtcreation
*
* @param \DateTime $dtcreation
*
* @return Response
*/
public function setDtcreation($dtcreation)
{
$this->dtcreation = $dtcreation;
return $this;
}
/**
* Get dtcreation
*
* @return \DateTime
*/
public function getDtcreation()
{
return $this->dtcreation;
}
/**
* Set author
*
* @param string $author
*
* @return Response
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* @return string
*/
public function getAuthor()
{
return $this->author;
}
/**
* Set published
*
* @param boolean $published
*
* @return Response
*/
public function setPublished($published)
{
$this->published = $published;
return $this;
}
/**
* Get published
*
* @return bool
*/
public function getPublished()
{
return $this->published;
}
/**
* Set question
*
* @param \Ono\MapBundle\Entity\Question $question
*
* @return Response
*/
public function setQuestion(\Ono\MapBundle\Entity\Question $question)
{
$this->question = $question;
return $this;
}
/**
* Get question
*
* @return \Ono\MapBundle\Entity\Question
*/
public function getQuestion()
{
return $this->question;
}
/**
* Set country
*
* @param \Ono\MapBundle\Entity\Country $country
*
* @return Response
*/
public function setCountry(\Ono\MapBundle\Entity\Country $country)
{
$this->country = $country;
return $this;
}
/**
* Get country
*
* @return \Ono\MapBundle\Entity\Country
*/
public function getCountry()
{
return $this->country;
}
/**
* Set dtnaissance
*
* @param \DateTime $dtnaissance
*
* @return Response
*/
public function setDtnaissance($dtnaissance)
{
$this->dtnaissance = $dtnaissance;
return $this;
}
/**
* Get dtnaissance
*
* @return \DateTime
*/
public function getDtnaissance()
{
return $this->dtnaissance;
}
/**
* Set user
*
* @param \Ono\UserBundle\Entity\User $user
*
* @return Response
*/
public function setUser(\Ono\UserBundle\Entity\User $user = null)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* @return \Ono\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
public function updateUser(\Ono\UserBundle\Entity\User $user = null){
if($user){
$this->user = $user;
} elseif($this->user) {
$user = $this->user;
} else {
return false;
}
$this->country = $user->getCountry();
$this->language = $user->getLanguage();
$this->dtnaissance = $user->getDtnaissance();
$this->author = $user->getFirstname().' '.$user->getName();
return true;
}
/**
* Set language
*
* @param \Ono\MapBundle\Entity\Language $language
*
* @return Response
*/
public function setLanguage(\Ono\MapBundle\Entity\Language $language = null)
{
$this->language = $language;
return $this;
}
/**
* Get language
*
* @return \Ono\MapBundle\Entity\Language
*/
public function getLanguage()
{
return $this->language;
}
/**
* Set nbLikes
*
* @param integer $nbLikes
*
* @return Response
*/
public function setNbLikes($nbLikes)
{
$this->nbLikes = $nbLikes;
return $this;
}
/**
* Get nbLikes
*
* @return integer
*/
public function getNbLikes()
{
return $this->nbLikes;
}
public function incrementLikes(){
$actual = $this->getNbLikes();
$new = $actual+1;
$this->setNbLikes($new);
return $new;
}
public function decrementLikes(){
$actual = $this->getNbLikes();
$new = $actual-1;
$this->setNbLikes($new);
return $new;
}
/**
* Set resource
*
* @param \Ono\MapBundle\Entity\Resource $resource
*
* @return Response
*/
public function setResource(\Ono\MapBundle\Entity\Resource $resource = null)
{
$this->resource = $resource;
return $this;
}
/**
* Get resource
*
* @return \Ono\MapBundle\Entity\Resource
*/
public function getResource()
{
return $this->resource;
}
public function temporyDeleteResource(){
$this->resource = null;
}
public function temporyDeleteUser(){
$this->user = null;
}
}
<file_sep>
/////////////////////////////////////////////
//
// FONCTION GรNรRIQUE
//
/////////////////////////////////////////////
function Request(args){
if(args.url){
this.target = args.target;
this.url = args.url;
}
if(args.method){
this.method = args.method;
} else {
this.method = "GET";
}
if(args.json){
this.json = args.json;
} else {
this.json = true;
}
if(args.callback){
this.callback = args.callback;
}
if(args.target){
this.target = args.target;
}
if(args.data){
this.data = args.data;
} else if(args.formData){
this.formData = args.formData;
}
this.additionnalData = args.additionnalData;
this.xhr = getXhrObject();
}
Request.prototype.open = function(){
var self = this;
this.xhr.open(this.method, this.url, true);
this.opened = true;
this.xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
this.xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
this.xhr.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200) {
var response = this.responseText;
self.success = true;
if(typeof self.callback === "function") {
self.callback(response);
} else {
console.log("Response successfull but no callback");
}
}
}
return this;
}
Request.prototype.send = function(){
if(!this.opened){
console.warn("Objet XHR ouvert automatiquement");
this.open();
}
//Si donnรฉes en string ou en json
// if(this.data){
var data = "";
if(this.data && this.json){
console.log(this.data);
data = "json="+JSON.stringify(this.data);
} else {
console.log(typeof this.data);
if(this.data && typeof this.data === "string"){
data = this.data;
}
}
this.xhr.send(data);
return this;
}
//S'applique ร un รฉlรฉment du DOM, le Supprime du DOM
Node.prototype.remove = function(){
var parent = this.parentNode;
if(parent){
parent.removeChild(this);
}
}
Node.prototype.setStyle = function(obj){
var s="";
for(sProp in obj){
s+=sProp+":"+obj[sProp]+";";
}
var a = this.getAttribute("style");
s+=a;
this.setAttribute("style", s);
return s;
}
function toggleFullScreen() {
if (!document.fullscreenElement && // alternative standard method
!document.mozFullScreenElement && !document.webkitFullscreenElement) { // current working methods
if (document.documentElement.requestFullscreen) {
document.documentElement.requestFullscreen();
} else if (document.documentElement.mozRequestFullScreen) {
document.documentElement.mozRequestFullScreen();
} else if (document.documentElement.webkitRequestFullscreen) {
document.documentElement.webkitRequestFullscreen(Element.ALLOW_KEYBOARD_INPUT);
}
} else {
if (document.cancelFullScreen) {
document.cancelFullScreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitCancelFullScreen) {
document.webkitCancelFullScreen();
}
}
}
//Met un รฉlรฉment ร la taille de la fenรชtre
function setToWindowHeight(el){
el.style.height = window.innerHeight+'px';
}
//Test si un objet est un รฉlรฉment HTML
function isElement(obj) {
try {
//Using W3 DOM2 (works for FF, Opera and Chrom)
return obj instanceof HTMLElement;
}
catch(e){
//Browsers not supporting W3 DOM2 don't have HTMLElement and
//an exception is thrown and we end up here. Testing some
//properties that all elements have. (works on IE7)
return (typeof obj==="object") &&
(obj.nodeType===1) && (typeof obj.style === "object") &&
(typeof obj.ownerDocument ==="object");
}
}
function toggleClassSidebarOpen(el, classOpen, classClose){
if(el.className.match(classOpen)){
el.className = el.className.replace(classOpen, classClose)
} else if(el.className.match(classClose)){
el.className = el.className.replace(classClose, classOpen)
}
}
function getXhrObject(){
// ### Construction de lโobjet XMLHttpRequest selon le type de navigateur
if(window.XMLHttpRequest){
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
} else {
// XMLHttpRequest non supportรฉ par le navigateur
console.log("Votre navigateur ne supporte pas les objets XMLHTTPRequest...");
return;
}
}
// Envoie la XHR
function callScript (scriptName, args, form, isJsonEncode){
var xhr_object = getXhrObject();
console.log(scriptName);
xhr_object.open("POST", scriptName, true);
// Dรฉfinition du comportement ร adopter sur le changement dโรฉtat de lโobjet XMLHttpRequest
xhr_object.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200) {
if(form) {
if(form.getAttribute("data-action")) {
XHRResponse.init(xhr_object.responseText, form, args);
}
} else {
XHRResponse.response = xhr_object.responseText;
}
sendMAJ(xhr_object.responseText);
}
return xhr_object.readyState;
}
xhr_object.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
if(isJsonEncode){
console.log("Is Json");
xhr_object.send("json="+JSON.stringify(args));
} else {
var str = "";
for(arg in args){
str+=arg+"="+args[arg]+"&"
}
str = str.replace(/&$/, "&isXHR=1");
// console.log(str);
xhr_object.send(str);
}
}
// Renvoi le temps รฉcoulรฉ depuis une date
function getAgeResponse(date){
date*=1000;
var actualDate = Date.now();
var diff = actualDate-date;
//Miliseconde
diff = Math.floor(diff/1000/60/60/24/365);
return diff;
}
//Crรฉe un รฉlรฉment HTML de maniรจre aisรฉ
function createElement(type, classname, attributes){
var el = document.createElement(type);
if(classname){
el.className+=classname;
}
for(attribute in attributes){
el.setAttribute(attribute, attributes[attribute]);
}
return el;
}
///////////////////////////////////////////////////////
//
// XHR POST AUTO
//
///////////////////////////////////////////////////////
function getArgs(els, arg){
for(i=0; i<els.length; i++){
if(els[i]){
arg[els[i].name]= els[i].value;
}
}
return arg;
}
function getInputs(inputs, arg){
for(i=0; i<inputs.length; i++){
if(inputs[i]){
if(inputs[i].value && inputs[i].name){
arg[inputs[i].name] = inputs[i].value;
}
}
}
return arg
}
XHRformAuto = {
forms : document.querySelectorAll("form[data-xhrpost='true']"),
main : function(form){
form.onsubmit = function(e){
e.preventDefault();
return false;
}
var submitButton = form.querySelectorAll("input[type='submit'], button[type='submit']")[0];
submitButton.addEventListener("click", function(e){
var arg = {};
var inputs = form.getElementsByTagName("input");
var textarea = form.getElementsByTagName("textarea");
var select = form.getElementsByTagName("select");
var test;
arg = getArgs(select, arg);
arg = getArgs(textarea, arg);
arg = getInputs(inputs, arg);
if(form.getAttribute("data-json")){
test = callScript(form.action, arg, form, true);
} else {
test = callScript(form.action, arg, form);
}
}, false)
},
realiseAction(txt, form, content){
function removeForm(form){
var formParent = form.parentNode;
var parent = form.parentNode;
parent.removeChild(formParent);
// console.log(parent);
console.log("Supprimer formulaire");
}
var action = form.getAttribute("data-action");
if(action){
switch(action) {
case "remove" :
removeForm(form);
break;
default :
break;
}
}
},
init : function(){
forms = XHRformAuto.forms;
for(i=0; i<forms.length; i++){
XHRformAuto.main(forms[i]);
}
}
}
///////////////////////////////////////////////////////
//
// XHR LIKE OBJECT
//
// gรจre les test et requรชte xhr pour like & dislike
//
///////////////////////////////////////////////////////
likeManage = {
updateContent: function(response){
response = JSON.parse(response);
var button = likeManage.currentAction.el;
var id = button.getAttribute("data-id");
var content = document.querySelector("[data-like-content][data-id='"+id+"']");
content.innerHTML = response.nbLike;
button.href = response.nextRoute;
if(response.liking){
console.log("Like");
button.parentNode.className += " liked";
} else {
console.log("Unlike");
button.parentNode.className = button.parentNode.className.replace("liked", "");
}
},
initEvent : function(el){
var self = this;
el.addEventListener("click", function(e){
self.currentAction = {};
self.currentAction.request = new Request({
url : this.href,
method: "GET",
callback : self.updateContent
}).send();
console.log(self.currentAction);
self.currentAction.el = this;
e.preventDefault();
e.stopPropagation();
return false;
}, false)
},
initEvents:function(){
for(i=0; i<this.buttons.length; i++){
this.initEvent(this.buttons[i])
}
},
init:function(){
this.buttons = document.querySelectorAll("[data-like-action]");
if(this.buttons.length){
this.initEvents();
}
}
}
///////////////////////////////////////////////////////
//
// XHR POPUP OBJECT
//
// gรจre les test et requรชte xhr pour les popus de tags
//
///////////////////////////////////////////////////////
popupManage = {
updateContent: function(response){
// Rรฉcupรฉration de la rรฉponse XHR
response = JSON.parse(response);
// Debug
console.log(response);
// On vide le contenu du modal
var modalContent = document.getElementById("modal-content");
modalContent.innerHTML = "";
// On rรฉcupรจre le prototype du modal
var popupPrototype = modalContent.getAttribute("data-prototype");
// On rรฉcupรจre nos attributs dans la rรฉponse XHR
var libTag = response.libTag;
var indefinitions = response.indefinitions;
var indefPersoLink = response.indefPersoLink;
var seeMoreLink = response.seeMoreLink;
var articles = response.articles;
// On insรจre le libTag dans le prototype
popupPrototype = popupPrototype.replace(/__libtag__/, libTag);
var hasCarousel;
// On crรฉe notre carousel d'indรฉfinitions s'il y en a
if (indefinitions.length == 0) {
hasCarousel = false;
popupPrototype = popupPrototype.replace(/__indefinitions__/, "<p class='no-indef'>Ce tag reste ร indรฉfinir...</p>");
} else {
hasCarousel = true;
var carouselEl = document.createElement("div");
carouselEl.classList = "carousel";
carouselEl.setAttribute("id", "indef-carousel");
var carouselItemPrototype = "<div class='item-carousel __active__' data-animation='scrollRight'><div class='indef-container'><p class='indef-content'>__content__</p></div>__btns__<p class='indef-author'>__author__</p>";
for (i = 0 ; i < indefinitions.length ; i++) {
var carouselItem = carouselItemPrototype;
carouselItem = carouselItem.replace(/__content__/, indefinitions[i].content);
carouselItem = carouselItem.replace(/__author__/, ("- " + indefinitions[i].author));
if (indefinitions[i].indefEditLink) {
editIndefLink = indefinitions[i].indefEditLink
deleteIndefLink = editIndefLink.replace(/edit/, "delete");
// console.log("Edit link : "+editIndefLink);
// console.log("Delete link : "+deleteIndefLink);
var indefBtns = "<p class='indef-btns'><a href='"+editIndefLink+"'>Editer</a> - <a href='"+deleteIndefLink+"'>Supprimer</a></p>";
carouselItem = carouselItem.replace(/__btns__/, indefBtns);
} else {
carouselItem = carouselItem.replace(/__btns__/, "");
}
if (i == 0) {
carouselItem = carouselItem.replace(/__active__/, "active");
} else {
carouselItem = carouselItem.replace(/__active__/, "");
}
carouselEl.innerHTML += carouselItem;
}
popupPrototype = popupPrototype.replace(/__indefinitions__/, carouselEl.outerHTML);
}
// On ajoute le href du lien "Proposer votre indรฉfinition"
popupPrototype = popupPrototype.replace(/__indefPersoLink__/, indefPersoLink);
// On ajoute le href du lien "Voir plus"
popupPrototype = popupPrototype.replace(/__seeMoreLink__/, seeMoreLink);
// On crรฉe notre conteneur d'articles
var articlesContainer = document.createElement("div");
articlesContainer.classList = "articles-container";
if (articles.length == 0) {
articlesContainer.innerHTML = "<p class='no-article'>Pas d'autre article comportant ce tag</p>";
} else {
var articleItemPrototype = "<a href='__link__' class='article-item'><div><img src=\"__image__\" alt='__title__'><p class='article-title'>__title__</p></div></a>";
for (i = 0 ; i < articles.length ; i++) {
var articleItem = articleItemPrototype;
articleItem = articleItem.replace(/__link__/g, articles[i].link);
var imageSrc = articles[i].image || "http://placehold.it/250x150?text=Pas+d'image";
articleItem = articleItem.replace(/__image__/, imageSrc);
var articleTitle = articles[i].title.length > 30 ? articles[i].title.substring(0, 30) + "..." : articles[i].title
articleItem = articleItem.replace(/__title__/g, articleTitle);
articlesContainer.innerHTML += articleItem;
}
}
popupPrototype = popupPrototype.replace(/__articles__/, articlesContainer.outerHTML);
modalContent.innerHTML += popupPrototype;
if(hasCarousel) {
var carousel = new Carousel(document.querySelector("#indef-carousel"), {
displayArrowSelectors: true,
displayButtonSelectors: false,
stopOnMouseOver: true,
});
carousel.launch();
}
popupModal.display();
},
initEvent : function(el){
var self = this;
el.addEventListener("click", function(e){
self.currentAction = {};
self.currentAction.request = new Request({
url : this.href,
method: "GET",
callback : self.updateContent
}).send();
console.log(self.currentAction);
self.currentAction.el = this;
e.preventDefault();
e.stopPropagation();
return false;
}, false)
},
initEvents:function(){
for(i=0; i<this.buttons.length; i++){
this.initEvent(this.buttons[i])
}
},
init:function(){
this.buttons = document.querySelectorAll("[data-popup-action]");
if(this.buttons.length){
this.initEvents();
}
}
}
///////////////////////////////////////////////////////
//
// Popup Modal
//
///////////////////////////////////////////////////////
popupModal = {
display:function(){
this.modal.className = this.modal.className.replace("hidden", "visible");
},
hide:function(){
this.modal.className = this.modal.className.replace("visible", "hidden");
},
initEvents:function(){
var self = this;
this.close.addEventListener("click", function(e){
e.preventDefault();
self.hide();
return false;
}, false);
window.onclick = function(event) {
if (event.target == self.modal) {
self.hide();
}
}
},
init:function(){
this.modal = document.getElementById('tag-modal');
this.close = document.getElementsByClassName("close-modal")[0];
if(this.modal && this.close){
if(!this.modal.className.match(/(?:visible|hidden)/)){
this.modal.className+= " hidden";
}
this.initEvents();
}
}
}
popupModal.init();
///////////////////////////////////////////////////////
//
// headerComplement
//
///////////////////////////////////////////////////////
headerComplement = {
display:function(){
this.menu.className = this.menu.className.replace("hidden", "visible");
},
hide:function(){
this.menu.className = this.menu.className.replace("visible", "hidden");
},
isHide:function(){
return this.menu.className.match("visible") ? false : true;
},
initEvents:function(){
var self = this;
this.button.addEventListener("click", function(e){
e.preventDefault();
if(self.isHide()){
self.display();
} else {
self.hide();
}
return false;
}, false)
},
init:function(){
this.button = document.getElementById("headerComplementButton");
this.menu = document.getElementById("headerComplementMenu");
if(this.button && this.menu){
if(!this.menu.className.match(/(?:visible|hidden)/)){
this.menu.className+= " hidden";
}
this.initEvents();
}
}
}
headerComplement.init();
///////////////////////////////////////////////////////
//
//
//
// Gรจre la crรฉation des liens sur les tags dans des articles
//
///////////////////////////////////////////////////////
tagManage = {
tags : [],
hydrateObject:function(){
for(i=0; i<tagManage.tagsEl.length; i++){
tagManage.tags.push({
"id": tagManage.tagsEl[i].getAttribute("data-id"),
"lib" : tagManage.tagsEl[i].innerHTML
});
}
},
run:function(){
var regStr, link, str;
var regPunctu = "\(\[\\<\\>\\.\\s\\;\\,\\&\]\)" //On rรฉcupรจre les " . ; , & < > "
for(i=0; i<tagManage.tags.length; i++){
regStr = new RegExp(regPunctu+tagManage.tags[i].lib+regPunctu, "g");
link = tagManage.prototype.replace(/(.+?)\d+$/, "$1"+tagManage.tags[i].id)
str = tagManage.content.innerHTML || tagManage.content.textContent;
console.log(str);
str = str.replace(regStr, '$1<a class="link-tag" href="'+link+'" data-popup-action>'+tagManage.tags[i].lib+'</a>$2')
tagManage.content.innerHTML = str;
console.log(str);
console.log(regStr, '<a class="link-tag" href="'+link+'" data-popup-action>'+tagManage.tags[i].lib+'</a>');
}
},
init:function(){
//On influe sur ce tag car tout les tags ne seront pas traitรฉ par le script
tagManage.tagsEl = document.getElementsByClassName("tag-content");
tagManage.content = document.getElementById("tagManageContent");
if(tagManage.content && tagManage.tagsEl){
console.log("ready to run");
console.log(tagManage.content);
tagManage.prototype = tagManage.content.getAttribute("data-prototypetag");
tagManage.hydrateObject();
tagManage.run();
}
}
}
///////////////////////////////////////////////////////
//
// Capte filter
//
///////////////////////////////////////////////////////
filter = {
limit:5,
filterThemeActive : [],
filterTab : {
themes : [],
age : null
},
testCount: function(){
var count = 0;
for(i=0; i<this.filterThemeActive.length ; i++){
if(this.filterThemeActive[i]){
count++;
}
}
console.log(count, this.limit);
if(count < this.limit){
return true;
} else {
return false;
}
},
updateQuestionCallscript: function(scriptName, args){
var xhr_object = getXhrObject();
xhr_object.open("POST", scriptName, true);
// Dรฉfinition du comportement ร adopter sur le changement dโรฉtat de lโobjet XMLHttpRequest
xhr_object.onreadystatechange = function() {
if(this.readyState === 4 && this.status === 200) {
if(typeof mapGestion !== "undefined"){
mapGestion.updateQuestionFromJson(xhr_object.responseText);
} else {
config.xhrLastResponse = xhr_object.responseText;
}
}
return xhr_object.readyState;
}
xhr_object.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr_object.send("json="+JSON.stringify(args)+"&xhr=true");
},
sendModification:function(){
filter.updateQuestionCallscript(config.rootPath+"update", filter.filterTab)
},
addClickEvent:function(el, rank){
var self = this;
el.addEventListener("click", function(){
console.log(self.testCount());
if(el.className.match("active")){
console.log("Hide");
el.className = el.className.replace("active", "");
filter.filterThemeActive[parseInt(el.getAttribute("data-id"))] = false
} else if(self.testCount()){
console.log("Display");
el.className+= " active";
filter.filterThemeActive[parseInt(el.getAttribute("data-id"))] = true;
} else {
console.log("No modif");
return;
}
filter.updateFilterTheme();
}, false)
},
clearFilterTab: function(){
filter.filterTab.themes = [];
},
updateFilterTheme:function(){
filter.clearFilterTab();
for(i=0; i<filter.filterThemeActive.length; i++){
if(filter.filterThemeActive[i]){
filter.filterTab.themes.push(i);
}
}
filter.sendModification();
},
initEvent: function(){
for(i=0; i<filter.themes.length; i++){
filter.addClickEvent(filter.themes[i], i);
}
if(filter.age){
filter.age.addEventListener("change", function(){
if(filter.ageControl.checked){
filter.filterTab.age = this.value;
}
filter.sendModification();
}, false)
}
if(filter.ageControl){
filter.ageControl.addEventListener("change", function(){
if(this.checked){
filter.filterTab.age = filter.age.value;
} else {
filter.filterTab.age = null;
}
filter.sendModification();
}, false)
}
},
//Se lance au chargement de la page
initFilterThemeActive : function(){
if(filter.themes) {
for(i=0; i<filter.themes.length; i++){
if(filter.themes[i].className.match("active")){
filter.filterThemeActive[parseInt(filter.themes[i].getAttribute('data-id'))] = true;
}
}
}
},
init: function(){
filter.themes = document.getElementsByClassName("filter-theme");
filter.age = document.getElementById("rangeAge");
filter.ageControl = document.getElementById("rangeAgeActive");
filter.initFilterThemeActive();
filter.initEvent();
}
}
///////////////////////////////////////////////////////
//
// DISPLAY THEME PANNEL
//
///////////////////////////////////////////////////////
themeGestion = {
initEvent:function(){
themeGestion.closebutton.addEventListener("click", function(){
themeGestion.container.className = themeGestion.container.className.replace("sidebar-open", "sidebar-close")
}, false)
themeGestion.openbutton.addEventListener("click", function(e){
e.preventDefault();
toggleClassSidebarOpen(themeGestion.container, "sidebar-open", "sidebar-close");
}, false)
},
init:function(){
themeGestion.container = document.getElementById("theme-list-container");
themeGestion.closebutton = document.getElementById("theme-list-container-close");
themeGestion.openbutton = document.getElementById("theme-list-container-open");
themeGestion.initEvent();
}
}
///////////////////////////////////////////////////////
//
// UTILISATION DES ALERT
//
///////////////////////////////////////////////////////
//Envoie une mise ร jour
function sendMAJ(response){
response = JSON.parse(response);
response.parent = document.getElementById("alerts-container");
var message = new Message(response);
message.run();
}
function Message(args, timelife = null){
console.log(args);
this.config = {
"closeOnclick" : true
}
if(args.type && args.title){
this.type = args.type;
this.title = args.title;
if(args.message){
this.message = args.message;
}
if(args.parent && isElement(args.parent)){
this.parent = args.parent;
} else {
this.parent = null;
}
if(timelife === null){
this.timelife = 5000;
}
this.generateHtml();
} else {
return false;
}
}
Message.prototype.generateHtml = function(){
var containerString = "alert-container alert-status-"+this.type
var container = createElement("div", containerString);
var title = createElement("p", "alert-title");
title.innerHTML = this.title;
container.appendChild(title);
if(this.message){
var message = createElement("p", "alert-content");
message.innerHTML = this.message;
container.appendChild(message);
}
if(this.config.closeOnclick){
var self = this;
container.addEventListener("click", function(){
html = self.html;
self.html.parentNode.removeChild(html);
self.isRunning = false;
}, false);
}
this.html = container;
console.log("Html crรฉe : ", this.html);
}
Message.prototype.append = function(){
if(this.html){
this.parent.appendChild(this.html);
}
}
Message.prototype.remove = function(){
this.parent.removeChild(this.html);
}
Message.prototype.run = function () {
this.append();
this.isRunning = true;
var html = this.html;
var self = this;
setTimeout(function(){
if(self.isRunning) {
html.parentNode.removeChild(html);
}
}, this.timelife)
};
likeManage.init();
filter.init();
XHRformAuto.init();
themeGestion.init();
tagManage.init();
popupManage.init();
InterfaceH.init({
focusWay: "background",
tutorialGuide : true,
helpConsult : false
});
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Tag
*
* @ORM\Table(name="tag")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\TagRepository")
*/
class Tag
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="libTag", type="string", length=255, unique=true)
*/
private $libTag;
/**
* @var int
*
* @ORM\Column(name="usedCount", type="integer")
*/
private $usedCount = 0;
/**
*
* @ORM\ManyToMany(targetEntity="Article", mappedBy="tags")
*/
private $articles;
/**
* @ORM\OneToMany(targetEntity="Ono\MapBundle\Entity\Indefinition", mappedBy="tag")
*/
private $indefinitions;
/**
* Constructor
*/
public function __construct()
{
$this->articles = new \Doctrine\Common\Collections\ArrayCollection();
$this->indefinitions = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set libTag
*
* @param string $libTag
*
* @return Tag
*/
public function setLibTag($libTag)
{
$this->libTag = $libTag;
return $this;
}
/**
* Get libTag
*
* @return string
*/
public function getLibTag()
{
return $this->libTag;
}
/**
* Set usedCount
*
* @param integer $usedCount
*
* @return Tag
*/
public function setUsedCount($usedCount)
{
$this->usedCount = $usedCount;
return $this;
}
/**
* Get usedCount
*
* @return integer
*/
public function getUsedCount()
{
return $this->usedCount;
}
public function incrementUsedCount()
{
$count = $this->getUsedCount();
return $this->setUsedCount($count+1);
}
public function decrementUsedCount()
{
$count = $this->getUsedCount();
return $this->setUsedCount($count-1);
}
/**
* Add article
*
* @param \Ono\MapBundle\Entity\Article $article
*
* @return Tag
*/
public function addArticle(\Ono\MapBundle\Entity\Article $article)
{
$this->articles[] = $article;
return $this;
}
/**
* Remove article
*
* @param \Ono\MapBundle\Entity\Article $article
*/
public function removeArticle(\Ono\MapBundle\Entity\Article $article)
{
$this->articles->removeElement($article);
}
/**
* Get articles
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getArticles()
{
return $this->articles;
}
/**
* Add indefinition
*
* @param \Ono\MapBundle\Entity\Indefinition $indefinition
*
* @return Tag
*/
public function addIndefinition(\Ono\MapBundle\Entity\Indefinition $indefinition)
{
$this->indefinitions[] = $indefinition;
return $this;
}
/**
* Remove indefinition
*
* @param \Ono\MapBundle\Entity\Indefinition $indefinition
*/
public function removeIndefinition(\Ono\MapBundle\Entity\Indefinition $indefinition)
{
$this->indefinitions->removeElement($indefinition);
}
/**
* Get indefinitions
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getIndefinitions()
{
return $this->indefinitions;
}
}
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Indefinition
*
* @ORM\Table(name="indefinition")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\IndefinitionRepository")
*/
class Indefinition
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="content", type="text")
* @Assert\NotBlank()
* @Assert\Length(min=20, minMessage="La longueur de l'indรฉfinition doit รชtre d'au moins 20 caractรจres.")
*/
private $content;
/**
* @var string
*
* @ORM\Column(name="author", type="string", length=255)
* @ORM\JoinColumn(nullable=false)
* @Assert\NotBlank()
* @Assert\Length(max=50, maxMessage="La longueur du nom de l'auteur ne doit pรขs dรฉpasser 50 caractรจres.")
*/
private $author;
/**
* @ORM\ManyToOne(targetEntity="Ono\MapBundle\Entity\Tag", inversedBy="indefinitions")
* @ORM\JoinColumn(nullable=false)
*/
private $tag;
/**
* @ORM\ManyToOne(targetEntity="Ono\UserBundle\Entity\User", inversedBy="indefinitions")
* @ORM\JoinColumn(nullable=true)
*/
private $user;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set content
*
* @param string $content
*
* @return Indefinition
*/
public function setContent($content)
{
$this->content = $content;
return $this;
}
/**
* Get content
*
* @return string
*/
public function getContent()
{
return $this->content;
}
/**
* Set tag
*
* @param \Ono\MapBundle\Entity\Tag $tag
*
* @return Indefinition
*/
public function setTag(\Ono\MapBundle\Entity\Tag $tag)
{
$this->tag = $tag;
$tag->addIndefinition($this);
return $this;
}
/**
* Get tag
*
* @return \Ono\MapBundle\Entity\Tag
*/
public function getTag()
{
return $this->tag;
}
/**
* Set user
*
* @param \Ono\UserBundle\Entity\User $user
*
* @return Indefinition
*/
public function setUser(\Ono\UserBundle\Entity\User $user)
{
$this->user = $user;
return $this;
}
/**
* Get user
*
* @return \Ono\UserBundle\Entity\User
*/
public function getUser()
{
return $this->user;
}
public function updateUser(\Ono\UserBundle\Entity\User $user = null){
if($user){
$this->user = $user;
} elseif($this->user) {
$user = $this->user;
} else {
return false;
}
$this->author = ($user->getFirstname().' '.$user->getName());
return true;
}
public function testUser(\Ono\UserBundle\Entity\User $user = null) {
if($user && $this->user) {
if ($user === $this->user) {
return true;
}
}
return false;
}
/**
* Set author
*
* @param string $author
*
* @return Indefinition
*/
public function setAuthor($author)
{
$this->author = $author;
return $this;
}
/**
* Get author
*
* @return string
*/
public function getAuthor()
{
return $this->author;
}
}
<file_sep>var prefix = ["webkit", "o", "moz"];
function listenAnimationIteration(prefix){
loaderManage.el.antenne.addEventListener(prefix+"Animationiteration", function(){
loaderManage.animationStart = Date.now();
}, false);
}
loaderManage = {
loaderContainer : document.getElementById("loader"),
loaderContainerManage : document.getElementById("loaderContent"),
config: {
duration : { //ms
classic : 4200,
speed : 4200,
skew : 3000
}
},
el: {
antenne : document.getElementById("antenne"),
interieur : document.getElementById("interieur"),
exterieur : document.getElementById("exterieur"),
oeil : document.getElementById("oeil")
},
button : {
speed : document.getElementById("speedAction"),
slow : document.getElementById("slowAction"),
// out : document.getElementById("outAction"),
skew : document.getElementById("skewAction"),
simulateLoading: document.getElementById('simulateLoading')
},
setToOutAnimation:function(){
for(el in loaderManage.el){
loaderManage.el[el].className = loaderManage.el[el].className.replace(/speed|classic|skew/, "out");
}
},
stopAnimation:function(){
loaderManage.loaderContainerManage.style.opacity = 0;
setTimeout(function(){
document.body.removeChild(loaderManage.loaderContainerManage);
}, 1600);
},
initEvent: function(){
//Stocke ร chaque itรฉration d'animation, le dรฉbut de cette derniรจre pour chaque prefix
for(i=0; i<prefix.length; i++){
listenAnimationIteration(prefix[i]);
}
loaderManage.el.antenne.addEventListener("animationiteration", function(){
loaderManage.animationStart = Date.now();
console.log(loaderManage.animationStart);
}, false);
},
init : function(){
loaderManage.initEvent();
loaderManage.animationStart = Date.now();
}
}
loaderManage.init();
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Ono\MapBundle\Entity\Tag;
use Ono\MapBundle\Form\TagType;
class TagController extends Controller
{
public function viewAction(Request $request) {
$numId = $request->attributes->all()["id"];
$numArt = $request->attributes->all()['article_id'];
$manager = $this->getDoctrine()->getManager();
$tag = $manager->getRepository("OnoMapBundle:Tag")->find($numId);
if ($tag) {
$themes = $manager->getRepository("OnoMapBundle:Theme")->findAll();
return $this->render('OnoMapBundle:Tag:view.html.twig', array(
"tag" => $tag,
"themes" => $themes,
"numArt" => $numArt
));
}
return $this->redirectToRoute("ono_map_homepage");
}
public function addAction(Request $request)
{
$manager = $this->getDoctrine()->getManager();
$tag = new Tag;
$form = $this->get('form.factory')->create(TagType::class, $tag);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($tag);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Tag bien enregistrรฉe.');
return $this->redirectToRoute("ono_admin_list_tags");
}
return $this->render('OnoMapBundle:Admin:add-tag.html.twig', array(
"form" => $form->createView()
));
}
public function editAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
$tag = $manager->getRepository("OnoMapBundle:Tag")->find($numId);
$form = $this->get('form.factory')->create(TagType::class, $tag);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$manager->persist($tag);
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Tag bien modifiรฉ.');
return $this->redirectToRoute("ono_admin_list_tags");
}
return $this->render('OnoMapBundle:Admin:edit-tag.html.twig', array(
"form" => $form->createView(),
"tag" => $tag
));
}
public function deleteAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$tag = $manager->getRepository('OnoMapBundle:Tag')->find($numId);
if (null === $tag) {
throw new NotFoundHttpException("Le pays d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($tag);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "Le tag a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_tags'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $tag,
'title' => $tag->getLibTag(),
'pathDelete' => "ono_admin_delete_tag",
'form' => $form->createView()
));
}
public function indexAction()
{
$manager = $this->getDoctrine()->getManager();
$tags = $manager->getRepository("OnoMapBundle:Tag")->findAll();
return $this->render('OnoMapBundle:Admin:list-tags.html.twig', array(
"tags" => $tags
));
}
}
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Question
*
* @ORM\Table(name="question")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\QuestionRepository")
*/
class Question
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="libQuestion", type="string", length=255, unique=true)
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
* @Assert\Length(min=20, minMessage="La longueur de la question doit รชtre au minimum de 20 caractรจres !")
*/
private $libQuestion;
/**
* @ORM\OneToMany(targetEntity="Ono\MapBundle\Entity\Response", mappedBy="question")
* @Assert\Valid()
*/
private $responses;
/**
* @ORM\ManyToMany(targetEntity="Ono\MapBundle\Entity\Theme", cascade={"persist"})
* @Assert\Valid()
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $themes;
/**
* Constructor
*/
public function __construct()
{
$this->responses = new \Doctrine\Common\Collections\ArrayCollection();
}
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set libQuestion
*
* @param string $libQuestion
*
* @return Question
*/
public function setLibQuestion($libQuestion)
{
$this->libQuestion = $libQuestion;
return $this;
}
/**
* Get libQuestion
*
* @return string
*/
public function getLibQuestion()
{
return $this->libQuestion;
}
/**
* Add response
*
* @param \Ono\MapBundle\Entity\Response $response
*
* @return Question
*/
public function addResponse(\Ono\MapBundle\Entity\Response $response)
{
$this->responses[] = $response;
return $this;
}
/**
* Remove response
*
* @param \Ono\MapBundle\Entity\Response $response
*/
public function removeResponse(\Ono\MapBundle\Entity\Response $response)
{
$this->responses->removeElement($response);
}
/**
* Get responses
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getResponses()
{
return $this->responses;
}
/**
* Add theme
*
* @param \Ono\MapBundle\Entity\Theme $theme
*
* @return Question
*/
public function addTheme(\Ono\MapBundle\Entity\Theme $theme)
{
$this->themes[] = $theme;
return $this;
}
/**
* Remove theme
*
* @param \Ono\MapBundle\Entity\Theme $theme
*/
public function removeTheme(\Ono\MapBundle\Entity\Theme $theme)
{
$this->themes->removeElement($theme);
}
/**
* Get themes
*
* @return \Doctrine\Common\Collections\Collection
*/
public function getThemes()
{
return $this->themes;
}
}
<file_sep><?php
namespace Ono\MapBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints as Assert;
/**
* Country
*
* @ORM\Table(name="country")
* @ORM\Entity(repositoryClass="Ono\MapBundle\Repository\CountryRepository")
*/
class Country
{
/**
* @var int
*
* @ORM\Column(name="id", type="integer")
* @ORM\Id
* @ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORM\Column(name="cdCountry", type="string", length=255, unique=true)
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
* @Assert\Length(max=4, maxMessage="Le code pays doit รชtre au maximum de 4 caractรจres !")
*/
private $cdCountry;
/**
* @var string
*
* @ORM\Column(name="libCountry", type="string", length=255)
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $libCountry;
/**
* @var string
*
* @ORM\Column(name="libCapital", type="string", length=255)
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $libCapital;
/**
* @var int
*
* @ORM\Column(name="lat", type="integer")
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $lat;
/**
* @var int
*
* @ORM\Column(name="ln", type="integer")
* @Assert\NotBlank(message="Le champ ne doit pas รชtre vide !")
*/
private $ln;
/**
* Get id
*
* @return int
*/
public function getId()
{
return $this->id;
}
/**
* Set libCountry
*
* @param string $libCountry
*
* @return Country
*/
public function setLibCountry($libCountry)
{
$this->libCountry = $libCountry;
return $this;
}
/**
* Get libCountry
*
* @return string
*/
public function getLibCountry()
{
return $this->libCountry;
}
/**
* Set libCapital
*
* @param string $libCapital
*
* @return Country
*/
public function setLibCapital($libCapital)
{
$this->libCapital = $libCapital;
return $this;
}
/**
* Get libCapital
*
* @return string
*/
public function getLibCapital()
{
return $this->libCapital;
}
/**
* Set lat
*
* @param integer $lat
*
* @return Country
*/
public function setLat($lat)
{
$this->lat = $lat;
return $this;
}
/**
* Get lat
*
* @return int
*/
public function getLat()
{
return $this->lat;
}
/**
* Set ln
*
* @param integer $ln
*
* @return Country
*/
public function setLn($ln)
{
$this->ln = $ln;
return $this;
}
/**
* Get ln
*
* @return int
*/
public function getLn()
{
return $this->ln;
}
/**
* Set cdCountry
*
* @param string $cdCountry
*
* @return Country
*/
public function setCdCountry($cdCountry)
{
$this->cdCountry = $cdCountry;
return $this;
}
/**
* Get cdCountry
*
* @return string
*/
public function getCdCountry()
{
return $this->cdCountry;
}
}
<file_sep>CREATE TABLE mytable(
country VARCHAR(20) NOT NULL PRIMARY KEY
,capital VARCHAR(18) NOT NULL
,lat INT NOT NULL
,lon INT NOT NULL
);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('AFGHANISTAN','KABOUL',35,69);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('AFRIQUE DU SUD','PRETORIA',-26,28);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ALBANIE','TIRANA',41,20);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ALGERIE','ALGER',37,3);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ALLEMAGNE','BONN',51,7);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ANDORRE','ANDORRE-LA-VIEILLE',43,2);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ANGOLA','LOANDA',-9,13);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ANTIGUA','SAINT-JOHN''S',17,-62);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ARABIE SAOUDITE','AR RIYAD',25,47);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ARGENTINE','BUENOS AIRES',-35,-50);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('AUSTRALIE','CANBERRA',-35,149);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('AUTRICHE','VIENNE',48,16);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('AZERBAIDJAN','BAKOU',41,50);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BAHAMAS','NASSAU',25,-77);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BAHREIN','MANAMA',26,51);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BANGLADESH','DACCA',24,90);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BARBADE','BRIDGETOWN',13,-60);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BELARUS','MINSK',53,28);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BELGIQUE','BRUXELLES',51,4);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BELIZE','BELIZE CITY',18,-88);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BENIN','PORTO NOVO',6,2);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BERMUDES','MANILTON',32,-65);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BHOUTAN','THIMPHU-PUNAKHA',27,90);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BIRMANIE','RANGOON',17,96);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BOLIVIE','LA PAZ-SUCRE',-17,-65);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BOSNIE','SARAJEVO',44,18);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BOTSWANA','GABORONE',-22,24);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BRESIL','BRASILIA',-16,-48);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BRUNEI','BANDAR SERI[1]',5,115);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BULGARIE','SOFIA',43,23);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BURKINA FASO','OUADAGOUDOU',12,-2);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('BURUNDI','BUJUMBURA',-3,29);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CAMBODGE','PNOM PENH',11,104);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CAMEROUN','YAOUNDE',4,12);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CANADA','OTTAWA',45,-75);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CAP-VERT','PRAIA',18,-25);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CENTRAFRIQUE','BANGUI',4,19);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CHILI','SANTIAGO',-33,-71);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CHINE','PEKIN',40,116);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CHYPRE','NICOSIE',35,33);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('COLOMBIE','BOGOTA',5,-72);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('COMORES','MORONI',-12,43);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CONGO','BRAZZAVILLE',-4,15);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CONGO (EX-ZAIRE)','KINSHASA',-4,15);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('COREE DU NORD','PYONGYANG',40,127);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('<NAME>','SEOUL',37,127);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('COSTA RICA','<NAME>',10,-84);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('<NAME>','YAMOUSSOUKRO',6,-6);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CROATIE','ZAGREB',46,16);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('CUBA','LA HAVANE',21,-80);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('DANEMARK','COPENHAGUE',56,10);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('DJIBOUTI','DJIBOUTI',12,43);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('DOMINICAINE','SAINT-DOMINGUE',18,-70);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('DOMINIQUE','ROSEAU',15,-61);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('EGYPTE','LE CAIRE',30,32);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('EMIRATS ARABES UNIS','<NAME>',24,54);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('EQUATEUR','QUITO',0,-78);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('รRYTHRรE','ASMARA',15,39);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ESPAGNE','MADRID',40,-4);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ESTONIE','TALLINN',59,25);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ETATS-UNIS','WASHINGTON',39,-77);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ETHIOPIE','ADDIS ABEBA',9,39);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('FIDJI','SUVA',-18,178);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('FINLANDE','HELSINKI',60,25);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('FORMOSE','TAIPEH',25,122);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('FRANCE','PARIS',49,2);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GABON','LIBREVILLE',0,9);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GAMBIE','BANJUL',13,-15);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GรORGIE','TBILISSI',42,45);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GHANA','ACCRA',6,0);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GRECE','ATHENES',38,24);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GRENADE','SAINT-GEORGE''S',12,-62);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GUATEMALA','GUATEMAMLA CITY',15,-91);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GUINEE','CONAKRY',10,-14);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GUINEE EQUATORIALE','MALABO',2,10);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GUINEE-BISSAU','BISSAU',12,-16);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('GUYANA','GEORGETOWN',7,-58);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('HAITI','PORT-AU-PRINCE',19,-73);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('HONDURAS','TEGUCIGALPA',14,-87);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('HONGRIE','BUDAPEST',48,19);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('INDE','DELHI',29,77);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('INDONESIE','DJAKARTA',-6,107);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('IRAK','BAGDAD',31,48);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('IRAN','TEHERAN',33,52);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('IRLANDE','DUBLIN',53,-6);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ISLANDE','REYKJAVIK',64,-23);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ISRAEL','JERUSALEM',32,35);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ITALIE','ROME',42,12);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('JAMAIQUE','KINGSTON',18,-77);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('JAPON','TOKYO',36,150);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('JORDANIE','AMMAN',32,36);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('KAZAKHSTAN','ALMA-ATA',42,78);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('KENYA','NAIROBI',-1,37);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('KIRGHIZISTAN','BICHKEK',42,75);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('KIRIBATI','TARAWA',2,-157);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('KOWEIT','KOWEIT',29,48);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LAOS','VIENTIANE',18,103);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LESOTHO','MASERU',-29,27);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LETTONIE','RIGA',57,24);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LIBAN','BEYROUTH',34,35);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LIBERIA','MONROVIA',7,-10);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LIBYE','TRIPOLI',32,13);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LIECHTENSTEIN','VADUZ',47,10);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LITUANIE','VILNIUS',54,26);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('LUXEMBOURG','LUXEMBOURG',50,6);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MACรDOINE','SKOPJE',42,21);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MADAGASCAR','ANTANANARIVO',-19,48);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MALAISIE','KUALA LUMPUR',3,102);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MALAWI','ZOMBA',-13,34);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MALDIVES','MALE',2,73);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MALI','BAMAKO',13,8);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MALTE','LA VALETTE',36,14);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MAROC','RABAT',33,-7);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MARSHALL','MAJURO',7,171);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MARTINIQUE','FORT-DE-FRANCE',15,-61);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MAURICE','PORT-LOUIS',19,57);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MAURITANIE','NOUAKCHOTT',20,10);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MEXIQUE','MEXICO',19,-99);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MICRONรSIE','KOLONIA',7,158);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MONACO','MONACO',44,7);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MONGOLIE','OULAN BATOR',47,105);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('MOZAMBIQUE','MAPUTO',-26,33);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('NAMIBIE','WINDHOEK',-22,17);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('NAURU','MAKWA',-1,167);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('NEPAL','KHATMANDOU',22,85);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('NICARAGUA','MANAGUA',13,-85);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('NIGER','NIAMEY',13,2);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('NIGERIA','ABUJA',9,7);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('NORVEGE','OSLO',60,11);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('NOUVELLE-ZELANDE','WELLINGTON',-41,175);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('OMAN','MASCATE',13,45);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('OUGANDA','KAMPALA',0,32);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('OUZBรKISTAN','TACHKENT',41,69);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PAKISTAN','ISLAMABAD',34,73);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PANAMA','PANAMA',8,-80);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PAPOUASIE','PORT MORESBY',-5,145);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PARAGUAY','ASUNCION',-25,-58);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PAYS-BAS','LA HAYE',57,4);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PEROU','LIMA',-12,-77);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PHILIPPINES','MANILLE',15,121);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('POLOGNE','VARSOVIE',52,21);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PORTO RICO','SAN JUAN',18,-66);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('PORTUGAL','LISBONNE',39,-9);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('QATAR','DOHA',25,51);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ROUMANIE','BUCAREST',44,26);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ROYAUME-UNI','LONDRES',52,0);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('RUSSIE','MOSCOU',56,38);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('RWANDA','KIGALI',-2,30);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SAINTE-LUCIE','CASTRIES',14,-61);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SAINT-MARIN','SAINT-MARIN',44,12);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SAINT-VINCENT','KINGSTOWN',12,-61);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SALOMON','HONIARA',-10,155);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SALVADOR','SAN SALVADOR',14,-89);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SAMOA OCCIDENTALES','APIA',-12,-172);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SAO TOME-ET-PRINCIPE','SAO TOME',0,7);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SENEGAL','DAKAR',15,-18);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SERBIE','BELGRADE',45,20);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SEYCHELLES','PORT VICTORIA',-5,55);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SIERRA LEONE','FREETOWN',8,-13);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SINGAPOUR','SINGAPOUR',1,104);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SLOVAQUIE','BRATISLAVA',48,17);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SLOVรNIE','LJUBLJANA',46,15);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SOMALIE','MOGADISCIO',2,45);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SOUDAN','KHARTOUM',16,33);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SRI LANKA','COLOMBO',7,80);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ST-KITTS-ET-NEVIS','BASSETERRE',17,-63);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SUEDE','STOCKHOLM',59,18);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SUISSE','BERNE',47,9);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SURINAME','PARAMARIBO',6,-55);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SWAZILAND','MBABANE',-26,32);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('SYRIE','DAMAS',33,36);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TADJIKISTAN','DOUCHAMBE',39,69);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TANZANIE','DAR-ES-SALAM',-7,39);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TCHAD','N''DJAMENA',12,15);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TCHรQUIE','PRAGUE',50,14);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('THAILANDE','BANGKOK',14,101);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TIMOR ORIENTAL','DILI',-8,125);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TOGO','LOME',6,1);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TONGA','NUKU ALOFA',-20,-175);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TRINITE-ET-TOBAGO','PORT OF SPAIN',11,-61);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TUNISIE','TUNIS',37,10);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TURKMรNIE','ACHKHABAD',38,59);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TURQUIE','ANKARA',40,33);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('TUVALU','FUNAFUTI',-8,180);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('URUGUAY','MONTEVIDEO',-35,-56);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('VANUATU','VILA',-17,167);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('VATICAN','CITE DU VATICAN',42,12);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('VENEZUELA','CARACAS',11,-67);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('VIETNAM','HANOI',26,106);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('YEMEN','SANAA',15,-44);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ZAMBIE','LUSAKA',-15,29);
INSERT INTO mytable(country,capital,lat,lon) VALUES ('ZIMBABWE','HARARE',-18,31);
<file_sep>var galleryCells = document.querySelectorAll('.gallery-cell');
if (galleryCells) {
for (var i = 0 ; i < galleryCells.length ; i++) {
if (galleryCells[i].hasAttribute("data-linkproto")) {
galleryCells[i].addEventListener("click", function(e) {
document.location.href = e.currentTarget.getAttribute("data-linkproto");
});
}
}
}
<file_sep><?php
namespace Ono\MapBundle\Repository;
/**
* TagRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class TagRepository extends \Doctrine\ORM\EntityRepository
{
public function getNbUsedCount($tagId){
$qb = $this->createQueryBuilder('t');
// On fait une jointure avec l'entitรฉ Category avec pour alias ยซ c ยป
$qb
->innerJoin('t.article', 'a')
->addSelect('COUNT(t.id) AS amount');
// Puis on filtre sur le nom des catรฉgories ร l'aide d'un IN
$qb->where('t.id = :tagId')
->setParameter("tagId", $tagId);
// La syntaxe du IN et d'autres expressions se trouve dans la documentation Doctrine
// Enfin, on retourne le rรฉsultat
return $qb
->getQuery()
->getResult()
;
}
}
<file_sep><?php
// src/OC/PlatformBundle/Form/IndefinitionAdminType.php
namespace Ono\MapBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Ono\MapBundle\Form\ResponseType;
class IndefinitionLogType extends IndefinitionType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder->remove('author');
}
public function getName()
{
return 'ono_admin_add_tag';
}
// public function getParent()
// {
// return new ResponseType();
// }
}
<file_sep><?php
namespace Ono\UserBundle\Form;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\AbstractType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Validator\Constraints\DateTime;
use FOS\UserBundle\Form\Type\ProfileFormType;
class RegistrationType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
}
public function getParent()
{
return 'FOS\UserBundle\Form\Type\RegistrationFormType';
}
public function getBlockPrefix()
{
return 'app_user_registration';
}
public function getName()
{
return $this->getBlockPrefix();
}
}
<file_sep><?php
namespace Ono\MapBundle\DataFixtures\ORM;
use Doctrine\Common\DataFixtures\AbstractFixture;
use Doctrine\Common\DataFixtures\OrderedFixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use Ono\MapBundle\Entity\Language;
class LoadLanguage extends AbstractFixture implements OrderedFixtureInterface
{
// Dans l'argument de la mรฉthode load, l'objet $manager est l'EntityManager
public function load(ObjectManager $manager)
{
$json = file_get_contents("web/json/language.json");
$tab = (array) json_decode($json);
for($i=0; $i<count($tab); $i++){
$tab[$i] = (array) $tab[$i];
}
for ($i=0; $i<count($tab); $i++) {
// On crรฉe la catรฉgorie
$language = new Language();
$language->setCdLanguage($tab[$i]["cdLang"]);
$language->setLibLanguageFr($tab[$i]["libLang"]);
$language->setLibLanguageEn($tab[$i]["libLangEn"]);
// On la persiste
$manager->persist($language);
}
// On dรฉclenche l'enregistrement de toutes les catรฉgories
$manager->flush();
}
public function getOrder() {
return 1;
}
}
<file_sep><?php
// src/OC/PlatformBundle/Form/AdvertEditType.php
namespace Ono\MapBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Ono\MapBundle\Form\ResponseType;
class ResponseLogType extends ResponseType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
parent::buildForm($builder, $options);
$builder
->remove("author")
->remove("dtnaissance")
->remove("language")
->remove("country");
}
public function getName()
{
return 'ono_admin_add_question';
}
// public function getParent()
// {
// return new ResponseType();
// }
}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\sfWebRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Ono\MapBundle\Entity\Article;
use Ono\MapBundle\Entity\Tag;
use Ono\UserBundle\Entity\User;
use Ono\MapBundle\Form\ArticleType;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class Resource extends Controller
{
public function indexAction(Request $request){
$manager = $this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$themesRepo = $manager->getRepository("OnoMapBundle:Theme");
$themes = $themesRepo->findAll();
$articles = $repoArticle->findAll();
$routeName = $request->get('_route');
if($routeName === "ono_admin_list_articles") {
return $this->render('OnoMapBundle:Admin:list-articles.html.twig', array(
"articles" => $articles
));
}
return $this->render("OnoMapBundle:Article:index.html.twig", array(
"articles" => $articles,
"themes" => $themes
));
}
public function showAction(Request $request){
$parameters = $request->attributes->all();
$numId = (int) $parameters["id"];
if(isset($parameters["tag"])){
$numTag = (int) $parameters["tag"];
}
$manager = $this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$article = $repoArticle->find($numId);
if(isset($numTag)){
$articles = $repoArticle->getFromTag($numTag);
if (count($articles)>1){
$article = $articles[floor(rand(0, count($articles)-1))];
}
}
if($article === null){
throw new NotFoundHttpException("La rรฉponse ร afficher n'existe pas.");
}
$themes = $themRepo->findAll();
return $this->render("OnoMapBundle:Article:show.html.twig", array(
"article" => $article,
"themes" =>$themes
));
}
public function addAction(Request $request){
$manager =$this->getDoctrine()->getManager();
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$tagRepo = $manager->getRepository("OnoMapBundle:Tag");
$articleRepo = $manager->getRepository("OnoMapBundle:Article");
$themes = $themRepo->findAll();
$article = new Article;
$article->setDtcreation(new \DateTime());
if($this->container->get('security.authorization_checker')->isGranted('ROLE_EDITOR')){
$user = $this->get('security.token_storage')->getToken()->getUser();
$article->setUser($user);
$form = $this->get('form.factory')->create(ArticleType::class, $article);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$article = $this->manageTagsType($article);
$manager->persist($article);
//On enregistre
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Article bien enregistrรฉe.');
return $this->redirectToRoute("ono_map_article_view", array(
"id" => $article->getId(),
"themes" => $themes
));
}
$routeName = $request->get('_route');
if($routeName === "ono_admin_add_article") {
return $this->render('OnoMapBundle:Admin:add-article.html.twig', array(
"article" => $article,
"form" => $form->createView()
));
}
return $this->render('OnoMapBundle:Article:add.html.twig', array(
'form' => $form->createView(),
"themes" => $themes
));
}
return $this->redirectToRoute("ono_map_article_index");
}
public function editAction(Request $request){
$numId = (int) $request->attributes->all()["id"];
$manager =$this->getDoctrine()->getManager();
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$tagRepo = $manager->getRepository("OnoMapBundle:Tag");
$themes = $themRepo->findAll();
$article = $repoArticle->find($numId);
$user = $this->get('security.token_storage')->getToken()->getUser();
if($article && $user instanceof User && $user->getId() === $article->getUser()->getId()){
if($this->container->get('security.authorization_checker')->isGranted('ROLE_EDITOR')){
$form = $this->get('form.factory')->create(ArticleType::class, $article);
if ($request->isMethod('POST') && $form->handleRequest($request)->isValid()) {
$article = $this->manageTagsType($article);
$manager->persist($article);
//On enregistre
$manager->flush();
$request->getSession()->getFlashBag()->add('notice', 'Article bien modifiรฉ.');
return $this->redirectToRoute("ono_map_article_view", array(
"id" => $article->getId(),
"themes" => $themes
));
}
$routeName = $request->get('_route');
if($routeName === "ono_admin_edit_article") {
return $this->render('OnoMapBundle:Admin:edit-article.html.twig', array(
"article" => $article,
"form" => $form->createView()
));
}
return $this->render('OnoMapBundle:Article:edit.html.twig', array(
'form' => $form->createView(),
"themes" => $themes,
"article" => $article
));
}
}
return $this->redirectToRoute("ono_map_article_view", array(
"id" => $numId
));
}
public function deleteAction(Request $request)
{
$numId = (int) $request->attributes->all()["id"];
$manager = $this->getDoctrine()->getManager();
// On rรฉcupรจre l'annonce $numId
$article = $manager->getRepository('OnoMapBundle:Article')->find($numId);
if (null === $article) {
throw new NotFoundHttpException("Le pays d'id ".$numId." n'existe pas.");
}
// On crรฉe un formulaire vide, qui ne contiendra que le champ CSRF
// Cela permet de protรฉger la suppression d'annonce contre cette faille
$form = $this->createFormBuilder()->getForm();
if ($form->handleRequest($request)->isValid()) {
$manager->remove($article);
$manager->flush();
$request->getSession()->getFlashBag()->add('info', "Le pays a bien รฉtรฉ supprimรฉe.");
return $this->redirect($this->generateUrl('ono_admin_list_articles'));
}
// Si la requรชte est en GET, on affiche une page de confirmation avant de supprimer
return $this->render('OnoMapBundle:Admin:delete.html.twig', array(
'object' => $article,
'title' => $article->getTitle(),
'pathDelete' => "ono_admin_delete_article",
'form' => $form->createView()
));
}
private function manageTagsType($article){
$manager = $this->getDoctrine()->getManager();
$tagRepo = $manager->getRepository("OnoMapBundle:Tag");
$repoArticle = $manager->getRepository("OnoMapBundle:Article");
//Stocke les tags
$tags=$article->getTags();
//Supprime les tags actuel de l'article
$article->removeTags();
for($i=0; $i<count($tags); $i++){
//Dรฉtache du persistage les tags รฉditรฉs du formulaire
dump($tags);
// exit;
$manager->detach($tags[$i]);
//Initialise un tag
$tagSearch = null;
//Test si le libellรฉ existe dans la bdd
$tagSearch = $tagRepo->findOneBy(array(
"libTag" => $tags[$i]->getlibTag()
));
//Si il n'y a pas de tag dans la bdd on le crรฉe
if(!$tagSearch){
$tagSearch = new Tag;
$tagSearch->setLibTag($tags[$i]->getlibTag());
$tagSearch->setUsedCount(1);
}
//Si le tag est dรฉja dans la bdd, on met ร jour le comptage
if($tagSearch->getId()){
$amount = $repoArticle->getNbUsedCount($tagSearch->getId())[0]["amount"];
$tagSearch->setUsedCount($amount+1);
}
//On rajoute le nouveau tag ร l'article
$article->addTag($tagSearch);
}
return $article;
}
}
<file_sep><?php
// src/Acme/UserBundle/Controller/RegistrationController.php
namespace Ono\UserBundle\Controller;
use Symfony\Component\HttpFoundation\RedirectResponse;
use FOS\UserBundle\Controller\ProfileController as BaseController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Finder\Exception\AccessDeniedException;
use Symfony\Component\Security\Core\User\UserInterface;
use FOS\UserBundle\Event\GetResponseUserEvent;
use FOS\UserBundle\FOSUserEvents;
use FOS\UserBundle\Event\FormEvent;
use FOS\UserBundle\Event\FilterUserResponseEvent;
// use Symfony\Component\Form\FormEvent;
use Symfony\Component\Form\FormEvents;
use Ono\UserBundle\Entity\User;
class ProfileController extends BaseController
{
/**
* Show the user.
*/
public function showAction()
{
$manager = $this->getDoctrine()->getManager();
$user = $this->get('security.token_storage')->getToken()->getUser();
$themes = $manager->getRepository("OnoMapBundle:Theme")->findAll();
// dump($user);
// exit;
if (!is_object($user) || !$user instanceof UserInterface) {
return $this->render('::logplease.html.twig', array(
'themes' => $themes
));
}
return $this->render('OnoUserBundle:Profile:show.html.twig', array(
'user' => $user,
'themes' => $themes
));
}
public function favorisAction(){
$manager = $this->getDoctrine()->getManager();
$themes = $manager->getRepository("OnoMapBundle:Theme")->findAll();
$reponseRepo = $manager->getRepository("OnoMapBundle:Response");
$articleRepo = $manager->getRepository("OnoMapBundle:Article");
if($this->container->get('security.authorization_checker')->isGranted('ROLE_USER')){
$user = $this->get('security.token_storage')->getToken()->getUser();
$articles = $user->getArticlesLiked();
$responses = $user->getResponsesLiked();
return $this->render('OnoUserBundle:Profile:favoris.html.twig', array(
'user' => $user,
'themes' => $themes,
'responses' => $responses,
'articles' => $articles
));
}
return $this->render('::logplease.html.twig', array(
'themes' => $themes
));
}
/**
* Edit the user.
*
* @param Request $request
*
* @return Response
*/
public function editAction(Request $request)
{
$manager = $this->getDoctrine()->getManager();
$user = $this->getUser();
if (!is_object($user) || !$user instanceof UserInterface) {
throw new AccessDeniedException('This user does not have access to this section.');
}
$themesRepo = $manager->getRepository("OnoMapBundle:Theme");
$themes = $themesRepo->findAll();
/** @var $dispatcher EventDispatcherInterface */
$dispatcher = $this->get('event_dispatcher');
$event = new GetResponseUserEvent($user, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_INITIALIZE, $event);
if (null !== $event->getResponse()) {
return $event->getResponse();
}
/** @var $formFactory FactoryInterface */
$formFactory = $this->get('fos_user.profile.form.factory');
$form = $formFactory->createForm();
$form->setData($user);
$form->handleRequest($request);
if ($form->isValid()) {
/** @var $userManager UserManagerInterface */
$userManager = $this->get('fos_user.user_manager');
$event = new FormEvent($form, $request);
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_SUCCESS, $event);
$userManager->updateUser($user);
if (null === $response = $event->getResponse()) {
$url = $this->generateUrl('fos_user_profile_show');
$response = new RedirectResponse($url);
}
$dispatcher->dispatch(FOSUserEvents::PROFILE_EDIT_COMPLETED, new FilterUserResponseEvent($user, $request, $response));
return $response;
}
return $this->render('OnoUserBundle:Profile:edit.html.twig', array(
'form' => $form->createView(),
"themes" => $themes
));
}
}
<file_sep><?php
namespace Ono\MapBundle\Repository;
use Doctrine\ORM\Query\Expr\Join;
/**
* ArticleRepository
*
* This class was generated by the Doctrine ORM. Add your own custom
* repository methods below.
*/
class ArticleRepository extends \Doctrine\ORM\EntityRepository
{
public function getArticlesWithThemes(array $themesId)
{
$qb = $this->createQueryBuilder('q');
$qb->innerJoin('q.themes', 't')
->addSelect('t')
->where($qb->expr()->in('t.id', $themesId));
return $qb
->getQuery()
->getResult()
;
}
public function getNbUsedCount($tagId){
// $em = $this->getDoctrine()->getManager();
$qb = $this->_em->createQueryBuilder();
$result = $qb->select('COUNT(u) AS amount')
->from('OnoMapBundle:Article' , 'u')
->innerJoin('u.tags','t')
->where('t.id = :tagId')
->setParameter("tagId", $tagId);
// La syntaxe du IN et d'autres expressions se trouve dans la documentation Doctrine
// Enfin, on retourne le rรฉsultat
return $qb
->getQuery()
->getResult()
;
}
}
<file_sep><?php
namespace Ono\UXInteractiveBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
class DefaultController extends Controller
{
public function indexAction()
{
return $this->render('OnoUXInteractiveBundle:Default:index.html.twig');
}
}
<file_sep>//Fonction d'initialisation de la carte
function initMap() {
mapGestion.map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 30, lng: 2.4},//Centre sur la france
// center: {lat: -26, lng: 28},//Centre sur la france
zoom: 3,
mapTypeControlOptions: {
mapTypeIds: [google.maps.MapTypeId.ROADMAP, 'map_style']
},
scrollwheel:false,
draggable: true,
disableDefaultUI: true,
disableDoubleClickZoom: true
});
mapGestion.init();
}
toHtml = function(str){
var fragment = document.createElement("fragment");
fragment.innerHTML = str;
console.log(fragment);
return fragment.firstChild;
}
//////////////////////////////
//
// Sidebar manage
//
///////////////////////////////
function ProtoGen(args){
this.events={};
if(args.parent){
this.parent = args.parent;
}
if(args.datas){
this.datas = args.datas;
}
if(args.tags){
this.tags = args.tags;
}
if(args.onclick){
this.events.onclick = args.onclick;
}
this.prototype = this.parent.getAttribute("data-prototype");
this.gen();
}
ProtoGen.prototype.gen = function(){
var output = this.prototype;
var datas = this.datas;
var tags = this.tags;
for( data in datas ){
output = output.replace(data, datas[data])
}
if (tags) {
console.log(tags);
var tagsOutput = "";
for(var i=0; i < tags.length; i++){
var tagPrototype = "<p class='tag-content' data-id='__idtag__'>__libtag__</p>";
tagPrototype = tagPrototype.replace("__idtag__", tags[i].id);
tagPrototype = tagPrototype.replace("__libtag__", tags[i].libTag);
tagsOutput += tagPrototype;
}
console.log(tagsOutput);
output = output.replace("__tag__", tagsOutput);
} else {
output = output.replace("__tag__", "");
}
this.result = toHtml(output);
this.html = output;
this.initEvent();
}
ProtoGen.prototype.initEvent = function(){
if(this.result){
var self = this;
this.result.onclick = function(){
self.events.onclick(this);
}
}
}
mapSidebarGestion = {
btn:{},
lists:{},
secure : {
state: [
"show-state",
"list-state"
],
},
hide:function(){
this.sidebar.className = this.sidebar.className.replace("sidebar-open", "sidebar-close");
},
display:function(){
this.sidebar.className = this.sidebar.className.replace("sidebar-close", "sidebar-open");
},
toggleState:function(actual, next){
if(this.secure.state.indexOf(actual) === -1 || this.secure.state.indexOf(next) === -1 ){
console.warn(actual+" ou "+next+" ne sont pas des รฉtats sรฉcurisรฉ");
return false;
}
this.body.className = this.body.className.replace(actual, next);
},
isOpen:function(){
if(this.sidebar.className.match("sidebar-open")){
return true;
} else {
return false;
}
},
initEvents:function(){
var self = this;
this.btn.close.addEventListener("click", function(e){
e.preventDefault();
self.hide();
return false;
}, false)
},
initItems:function(){
for(i=0; i<this.items.length; i++){
this.initClickItem(this.items[i]);
}
},
getParentState:function(el){
var test = false;
var testEl = el;
var state = null;
while(test === false && testEl.tagName != "BODY"){
for(i=0; i<this.secure.state.length; i++){
if(testEl.className.match(this.secure.state[i])) {
state = this.secure.state[i];
test=true;
}
}
if(test === false){
testEl = testEl.parentNode;
}
}
return state;
},
getNextState:function(actual){
for(i=0; i<this.secure.state.length; i++){
if(actual != this.secure.state[i]){
return this.secure.state[i];
}
}
},
getQuestion:function(id, isBest=false){
id= parseInt(id);
var question, response;
var object = {};
for(i=0; i<this.questions.length; i++){
if(this.questions[i].id===id){
question = this.questions[i];
response = question.responses[0];
}
}
if(question && response){
object.articleattr = "";
object.title = question.libQuestion;
object.author = response.author;
object.dtNaissance = response.dtnaissance.timestamp;
object.content = response.content;
object.resource = response.resource ? response.resource : "";
object.resourceLegend = response.resource ? response.resource : "";
object.country = response.country.libCountry;
object.likes = response.nbLikes;
object.id = response.id;
object.likePath = "";
object.showPath = config.responseShowPath.replace(/(\d)$/, response.id);
return object;
}
return null;
},
getArticle:function(id, isBest=false){
id= parseInt(id);
var article;
var object = {};
for(i=0; i<this.articles.length; i++){
if(this.articles[i].id===id){
article = this.articles[i];
}
}
if(article){
object.articleattr = "id='tagManageContent' data-prototypeTag='"+config.articleShowPath.replace(/show\/(\d)$/, article.id)+"/popup/0'",
object.tags = article.tags;
object.title = article.title;
object.author = "";
object.dtNaissance = "";
object.content = article.content;
object.resource = article.resource ? article.resource : "";
object.resourceLegend = article.resource ? article.resource : "";
object.country = article.country.libCountry;
object.likes = article.nbLikes;
object.id = article.id;
object.likePath = "";
object.showPath = config.articleShowPath.replace(/(\d)$/, article.id);
return object;
}
return null;
},
initClickItem:function(el){
var self = mapSidebarGestion;
el.onclick = function(){
//On cherche dans l'object questions
if(this.getAttribute("data-object")==="questions"){
var object = self.getQuestion(this.getAttribute("data-href"));
self.updateShow(object);
} else if(this.getAttribute("data-object")==="articles") {
var object = self.getArticle(this.getAttribute("data-href"));
self.updateShow(object);
}
//Bouge le panneau
var actual = self.getParentState(this);
setTimeout(function(){
self.toggleState(actual, self.getNextState(actual));
}, 100)
}
},
genLists:function(questions, articles){
var questionsItem = [];
var question;
for(i=0; i<questions.length; i++){
question = questions[i];
var proto = new ProtoGen({
parent : this.lists.questions.container,
datas: {
__object__ : "questions",
__id__: question.id,
__lib__ : question.libQuestion,
__count__: question.responses.length
},
onclick: this.initClickItem
});
questionsItem.push(proto.result);
}
this.lists.questions.els = questionsItem;
this.appendList(this.lists.questions.container, this.lists.questions.els);
var articlesItem = [];
var article;
for(i=0; i<articles.length; i++){
article = articles[i];
var proto = new ProtoGen({
parent : this.lists.articles.container,
datas: {
__object__ : "articles",
__id__: article.id,
__lib__ : article.title,
__count__: article.nbLikes
},
onclick: this.initClickItem
});
articlesItem.push(proto.result);
}
this.lists.articles.els = articlesItem;
this.appendList(this.lists.articles.container, this.lists.articles.els);
},
resetList:function(){
this.lists.questions.container.innerHTML="";
this.lists.articles.container.innerHTML="";
},
appendList:function(container, array){
for(i=0; i<array.length; i++){
container.appendChild(array[i]);
console.log("Elements Add", array[i]);
}
},
setCountry: function(str){
this.sidebar.getElementsByClassName("sidebar-title")[0].innerHTML = str;
},
manageListTitle:function(qCount, aCount){
this.lists.questions.title.className = qCount ? "list-title visible" : "list-title hidden";
this.lists.articles.title.className = aCount ? "list-title visible" : "list-title hidden";
},
updatePanel:function(questions, articles=null){
//Met ร jour les donnรฉes
this.questions = questions;
this.articles = articles;
this.manageListTitle(questions.length, articles.length);
this.toggleState("show-state", "list-state");
if(questions.length){
this.setCountry(questions[0].responses[0].country.libCountry);
} else {
this.setCountry(articles[0].country.libCountry);
}
this.resetList();
this.genLists(questions, articles);
},
initShowEvent:function(){
var items = this.show.querySelectorAll("*[data-href]");
for(i=0; i<items.length; i++){
this.initClickItem(items[i]);
}
},
updateShow:function(object){
this.show.innerHTML ="";
var proto = new ProtoGen({
parent : this.show,
datas: {
__articleattr__: object.articleattr,
__id__: object.id,
__title__: object.title,
__author__ : object.author,
__dt_naissance__: object.dtNaissance,
__content__: object.content,
__resource__: object.resource,
__resource_legend__: object.resourceLegend,
__country__: object.country,
__likes__: object.likes,
__is_liked__: "",
__like_path__: object.likePath,
__show_path__ : object.showPath
},
tags : object.tags
});
this.show.innerHTML = proto.html;
tagManage.init();
popupManage.init();
this.initShowEvent();
},
init:function(){
this.sidebar = document.getElementById("sidebarRight");
this.btn.close = this.sidebar.getElementsByClassName("sidebar-close-button")[0];
this.body = this.sidebar.getElementsByClassName("sidebar-body")[0];
this.show = document.getElementById("show-item");
this.lists.questions = {
container : this.sidebar.getElementsByClassName("list-question")[0],
title: this.sidebar.getElementsByClassName("list-title")[0]
};
this.lists.articles = {
container : this.sidebar.getElementsByClassName("list-article")[0],
title: this.sidebar.getElementsByClassName("list-title")[1]
}
//Devrons รชtre gรฉnรฉrรฉ aprรจs chaque mise ร jour
this.items = this.sidebar.querySelectorAll("[data-href]");
this.initItems();
if(this.sidebar && this.btn.close){
this.initEvents();
}
}
}
mapGestion = {
//Elements
mapEl : document.getElementById("map"),
//Variable initialisรฉ
zoom : 3,
markers: [],
questions:[],
articles:[],
previousQuestion: [],
//////////////////////////////////////////////////
// Mise ร jour des markers //
//////////////////////////////////////////////////
//Rajoute les question ainsi que leurs rรฉponse dans le tableau questions
//Post load
addQuestions: function(json){
var questions = json.questions;
var articles = json.articles;
for(i=0; i<questions.length; i++){
mapGestion.questions.push(questions[i]);
}
for(i=0; i<articles.length; i++){
mapGestion.articles.push(articles[i]);
}
},
// Met ร jour les markeurs de la cartes au changement de filtres
// Post Request
updateQuestionFromJson: function(json){
json = JSON.parse(json);
var questions = json.questions;
var articles = json.articles
//On transpose les nouvelles questions et les anciennes
mapGestion.previousQuestion = mapGestion.questions;
mapGestion.questions = questions;
mapGestion.articles = articles;
//On supprime tout, on recrรฉ
mapGestion.deleteAllMarkers();
mapGestion.createAllMarkers();
},
//Rajoute un objet Google Marker dans le tableau de marker
pushMarkerResponse:function(response, question){
this.markers.push(new google.maps.Marker({
position: {lat: response.country.lat, lng: response.country.ln},
map: mapGestion.map,
title: response.question.libQuestion,
icon: mapGestion.image,
id: response.id
}));
return this.markers[this.markers.length-1];
},
pushMarkerArticle:function(article){
this.markers.push(new google.maps.Marker({
position: {lat: article.country.lat, lng: article.country.ln},
map: mapGestion.map,
title: article.title,
icon: mapGestion.image,
id: article.id
}));
return this.markers[this.markers.length-1];
},
initMarkerEvent :function(marker, object){
google.maps.event.addListener(marker, 'click', function() {
if(!mapSidebarGestion.isOpen()){
mapSidebarGestion.display();
mapSidebarGestion.toggleState("show-state", "list-state");
}
mapGestion.map.panTo(marker.getPosition());
var idCountry = object.country.id;
var questionsFromPays = mapGestion.getQuestionsFromPays(idCountry);
var articlesFromPays = mapGestion.getArticlesFromPays(idCountry);
console.log(articlesFromPays);
mapSidebarGestion.updatePanel(questionsFromPays, articlesFromPays);
console.log(questionsFromPays);
})
},
//Rajoute un marker et ses รฉvenements depuis une rรฉponse
addMarkerFromResonse: function(response, question){
var marker = this.pushMarkerResponse(response, question);
this.initMarkerEvent(marker, response);
},
addMarkerFromArticle:function(article){
var marker = this.pushMarkerArticle(article);
this.initMarkerEvent(marker, article);
},
//Parcour les rรฉponses et rajoutes les markers
createAllMarkers:function(){
mapGestion.image = {
url : config.assetPath+"/img/marker.png",
size: new google.maps.Size(40, 44),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(20, 20)
};
for(i=0; i<mapGestion.questions.length; i++){
for(j=0; j<mapGestion.questions[i].responses.length; j++){
mapGestion.addMarkerFromResonse(mapGestion.questions[i].responses[j], mapGestion.questions[i]);
}
}
for(i=0; i<mapGestion.articles.length; i++){
mapGestion.addMarkerFromArticle(mapGestion.articles[i]);
}
},
//Supprimer tout les markers
deleteAllMarkers : function(){
for(i=0; i<mapGestion.markers.length; i++){
mapGestion.markers[i].setMap(null);
}
},
///////////////////////////////////////////////////////////
// Traitemnet des donnรฉes du json //
///////////////////////////////////////////////////////////
//Rรฉcupรจre les rรฉponse d'une question donnรฉe pour un pays donnรฉ
getResponseViewFromQuestion :function(question, idCountry){
var responseTab = [];
for(i=0; i<question.responses.length; i++){
if(question.responses[i].country.id === idCountry){
responseTab.push(question.responses[i]);
}
}
return responseTab;
},
//Rรฉcupรจre la liste des questions intervenant pour un pays donnรฉe
getQuestionsFromPays: function(id){
var questionReturn = [];
for(test = false, i=0; i<mapGestion.questions.length; i++, test=false){
for(j=0; j<mapGestion.questions[i].responses.length; j++){
if(mapGestion.questions[i].responses[j].country.id === id && test=== false){
questionReturn.push(mapGestion.questions[i]);
test=true;
}
}
}
return questionReturn;
},
getArticlesFromPays:function(id){
var articlesReturn =[];
for(i=0; i<mapGestion.articles.length; i++){
if(mapGestion.articles[i].country.id === id){
articlesReturn.push(mapGestion.articles[i]);
}
}
return articlesReturn;
},
///////////////////////////////////////////////////////////
// Fonctionnement d'initialisation
///////////////////////////////////////////////////////////
//Gรจre le resize de la fenรชtre
initSizeMap: function(){
setToWindowHeight(mapGestion.mapEl);
window.addEventListener("resize", function(){
setToWindowHeight(mapGestion.mapEl);
}, false)
},
//Intรจgre les รฉvenement de la map
initListenerMap:function(){
mapGestion.map.addListener("zoom_changed", function(){
mapGestion.zoom = mapGestion.map.getZoom();
});
mapGestion.map.addListener("center_changed", function(){
mapGestion.center = mapGestion.map.getCenter();
});
},
//Intรจgre le style ร la carte
initStyleMap: function(){
mapGestion.styledMap = new google.maps.StyledMapType(stylesArray,
{name: "Styled Map"});
mapGestion.map.mapTypes.set('map_style', mapGestion.styledMap);
mapGestion.map.setMapTypeId('map_style');
},
init:function(){
mapGestion.initSizeMap();
mapGestion.initStyleMap();
mapGestion.initListenerMap();
}
}
var stylesArray = [{"featureType":"administrative","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"administrative.country","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.province","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"administrative.land_parcel","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"landscape","elementType":"all","stylers":[{"saturation":"25"},{"lightness":"-3"},{"gamma":"1"},{"weight":"1"}]},{"featureType":"landscape.man_made","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"road","elementType":"geometry","stylers":[{"lightness":100},{"visibility":"simplified"}]},{"featureType":"road","elementType":"labels","stylers":[{"visibility":"off"}]},{"featureType":"transit.line","elementType":"all","stylers":[{"visibility":"off"}]},{"featureType":"water","elementType":"all","stylers":[{"color":"#085076"}]}]
<file_sep><?php
namespace Ono\MapBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Component\Form\Extension\Core\Type\IntegerType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
class CountryType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('libCountry', TextType::class)
->add('libCapital', TextType::class)
->add('cdCountry', TextType::class)
->add('lat', IntegerType::class)
->add('ln', IntegerType::class)
->add('Enregistrer', SubmitType::class)
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ono\MapBundle\Entity\Country'
));
}
}
<file_sep><?php
// src/OC/PlatformBundle/Form/IndefinitionAdminType.php
namespace Ono\MapBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Ono\MapBundle\Form\ResponseType;
class IndefinitionAdminType extends IndefinitionType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder->add('tag', EntityType::class, array(
'class' => 'OnoMapBundle:Tag',
'choice_label' => 'libTag',
'multiple' => false,
));
parent::buildForm($builder, $options);
}
public function getName()
{
return 'ono_admin_add_tag';
}
// public function getParent()
// {
// return new ResponseType();
// }
}
<file_sep><?php
namespace Ono\MapBundle\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\sfWebRequest;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Validator\Constraints\DateTime;
use Symfony\Component\Finder\Exception\AccessDeniedException;
//Response already use;
use Ono\MapBundle\Entity\Response as ResponseQ;
use Ono\MapBundle\Entity\Question;
use Ono\MapBundle\Entity\Theme;
use Ono\MapBundle\Form\ResponseType;
use Ono\MapBundle\Form\ResponseLogType;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
class MapController extends Controller
{
//Action affichant la page d'accueil avec la carte
public function indexAction(Request $request, $ids = null)
{
$manager = $this->getDoctrine()->getManager();
$questionRepo = $manager->getRepository("OnoMapBundle:Question");
$responseRepo = $manager->getRepository("OnoMapBundle:Response");
$articleRepo = $manager->getRepository("OnoMapBundle:Article");
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$themesActive = $request->getSession()->get("themes");
$isFirst = $request->getSession()->get("loggedVisit");
if(!$this->container->get('security.authorization_checker')->isGranted('ROLE_USER') && !$isFirst){
return $this->redirectToRoute("fos_user_security_login");
}
if(count($themesActive)>0){
$questions = $questionRepo->getQuestionsWithThemes($themesActive);
$articles = $articleRepo->getArticlesWithThemes($themesActive);
//Sinon on ne fait pas de distinction
} else {
$questions = $questionRepo->findAll();
$articles = $articleRepo->findAll();
}
if(!isset($questions) || !count($questions)){
$questions = $questionRepo->findAll();
}
if(!isset($articles) || !count($articles)){
$articles = $articleRepo->findAll();
}
$themes = $themRepo->findAll();
$json = $this->manageJson($articles, $questions, $responseRepo);
return $this->render('OnoMapBundle:Map:index.html.twig', array(
"json" =>$json,
"themes" => $themes
));
}
//Action mettant ร jour la page d'accueil ร l'aide d'une XHR et d'un retour en JSON
public function updateAction(Request $request)
{
//Initialisation
$manager = $this->getDoctrine()->getManager();
$questionRepo = $manager->getRepository("OnoMapBundle:Question");
$responseRepo = $manager->getRepository("OnoMapBundle:Response");
$articleRepo = $manager->getRepository("OnoMapBundle:Article");
$themesActive = $request->getSession()->get("themes");
if(count($themesActive)>0){
//Si on a des thรจmes ร filtrer on utilise cette mรฉthode
$questions = $questionRepo->getQuestionsWithThemes($themesActive);
$articles = $articleRepo->getArticlesWithThemes($themesActive);
//Sinon on ne fait pas de distinction
} else {
$questions = $questionRepo->findAll();
$articles = $articleRepo->findAll();
}
if(!isset($questions) || !count($questions)){
$questions = $questionRepo->findAll();
}
if(!isset($articles) || !count($articles)){
$articles = $articleRepo->findAll();
}
$responses= $responseRepo->findAll();
for($i=0; $i<count($questions); $i++){
if(count($questions[$i]->getResponses())<1){
array_splice($questions, $i, 1);
}
}
$json = $this->manageJson($articles, $questions, $responseRepo);
//Return response
return new Response($json);
}
public function menuAction($route){
$manager = $this->getDoctrine()->getManager();
$themRepo = $manager->getRepository("OnoMapBundle:Theme");
$themes = $themRepo->findAll();
//On retourne le tout
return $this->render('OnoMapBundle:Templates:header.html.twig', array(
"themes" => $themes,
"current_route" => $route
));
}
////////////////////////////////////////////
//
// JSON + FILEREADER + CIRCULARHANDLER
//
///////////////////////////////////////////
private function manageJson($articles, $questions, $responseRepo){
if($questions){
$circularHandler= $responseRepo->findBy(array("question"=>$questions[0]));
$questions = $this->deleteResponsesFiles($questions);
$json1 = $this->getJsonFor($questions, $circularHandler);
} else {
$json1 = "{}";
}
if($articles){
$articles = $this->deleteArticlesFiles($articles);
$articles = $this->deleteIndefs($articles);
$json2 = $this->getJsonFor($articles, $articles);
} else {
$json2 = "{}";
}
$json= '{"articles": '.$json2.', "questions": '.$json1.'}';
return $json;
}
private function deleteArticlesFiles($articles){
if($articles) {
for($i=0; $i<count($articles); $i++){
$articles[$i]->temporyDeleteResource();
$articles[$i]->temporyDeleteUser();
// for($j=0; $j<count($resources); $j++){
// $resources[$j]->setFile(null);
// }
}
}
// dump($articles);
// exit;
return $articles;
}
private function deleteIndefs($articles) {
for($i=0; $i<count($articles); $i++){
$articles[$i]->temporyDeleteTagsIndefs();
}
return $articles;
}
private function deleteResponsesFiles($questions){
for($i=0; $i<count($questions); $i++){
$responses = $questions[$i]->getResponses();
for($j=0; $j<count($responses); $j++){
$responses[$j]->temporyDeleteResource();
$responses[$j]->temporyDeleteUser();
}
}
return $questions;
}
private function getJsonFor($object, $normalizerRef=null){
$serializer = $this->get('serializer');
$encoder = new JsonEncoder();
$normalizer = new ObjectNormalizer();
if($normalizerRef){
$normalizer->setCircularReferenceHandler(function ($normalizerRef) {
return $normalizerRef->getId();
});
}
$serializer = new Serializer(array($normalizer), array($encoder));
$json = $serializer->serialize($object, 'json');
return $json;
}
/////////////////////////////////
// LANGUAGE
/////////////////////////////////
public function changeLanguageAction($cdLang)
{
return $this->redirectToRoute('ono_map_homepage', array(
"ids" => $ids
));
}
}
<file_sep><?php
namespace Ono\MapBundle\Form;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\CheckboxType;
use Symfony\Component\Form\Extension\Core\Type\DateType;
use Symfony\Component\Form\Extension\Core\Type\DateTimeType;
use Symfony\Component\Form\Extension\Core\Type\SubmitType;
use Symfony\Component\Form\Extension\Core\Type\TextareaType;
use Symfony\Component\Form\Extension\Core\Type\TextType;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use Ivory\CKEditorBundle\Form\Type\CKEditorType;
class ResponseType extends AbstractType
{
/**
* @param FormBuilderInterface $builder
* @param array $options
*/
public function buildForm(FormBuilderInterface $builder, array $options)
{
$builder
->add('content', CKEditorType::class, array(
'config' => array(
'uiColor' => '#ffffff',
)
))
->add('author', TextType::class)
->add('dtnaissance', DateType::class, array(
"required" => true,
"label" => "Date de naissance",
"years" => range(1900,2016),
"format" => "dd / MM / yyyy"
))
->add('country', EntityType::class, array(
'class' => 'OnoMapBundle:Country',
'choice_label' => 'libCountry',
'multiple' => false,
))
->add('language', EntityType::class, array(
'class' => 'OnoMapBundle:Language',
'choice_label' => 'libLanguageFr',
'multiple' => false,
))
->add('save', SubmitType::class)
;
}
/**
* @param OptionsResolver $resolver
*/
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'data_class' => 'Ono\MapBundle\Entity\Response'
));
}
}
|
8cb03a2cc279e062d90d5b888754ce60052631d0
|
[
"JavaScript",
"SQL",
"Markdown",
"PHP"
] | 55 |
PHP
|
SolalDR/Ono
|
06be45e0722d7cb725abd48c568510994b094462
|
59bc2b9fe122a4b809650006cbc8ebc697932df2
|
refs/heads/master
|
<file_sep>package com.example.appprogrammingproject;
import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import androidx.annotation.CheckResult;
import androidx.annotation.Nullable;
import com.example.appprogrammingproject.database.DatabaseHelper;
import com.example.appprogrammingproject.database.model.Note;
public class Stress extends Activity {
Button one, two, three, four;
int cnt = 0;
long now = System.currentTimeMillis();
Date dateTime = new Date(now);
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String getTime = simpleDate.format(dateTime);
final int[] select = {0};
private DatabaseHelper db;
private void createNote( int group,int id, int select) {
db.insertNote(id, group, select);
readData();
}
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stress);
db = new DatabaseHelper(this);
List<Note> n = db.getGroupNotes(2);
one = findViewById(R.id.one);
two = findViewById(R.id.two);
three = findViewById(R.id.three);
four = findViewById(R.id.four);
readData();
//๋ฒํผ์ ๋๋ ์๋ dialog ๋์ด ํ์ ์ฌ๋ฆฌํ
์คํธ ์งํ
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83D\uDC35 ์์ญ์ด", "\uD83D\uDC11 ์", "\uD83D\uDC2E ์",
"\uD83D\uDC34 ๋ง", "\uD83E\uDD81 ์ฌ์"};
final AlertDialog.Builder result = new AlertDialog.Builder(Stress.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Stress.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83D\uDC18 ์ด๋ค ๋๋ฌผ๊ณผ ์ฌํ์ ํจ๊ป ํด์ผํ๋ค๋ฉด, ์ด๋ค ๋๋ฌผ๊ณผ ํจ๊ป ํ๊ฒ ์ต๋๊น?").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0] = i;
if (i == 0) {
result.setTitle("\uD83D\uDC35 ์์ญ์ด๋ฅผ ์ ํํ ๋น์ !");
result.setMessage("์ฌ๋๊ณผ์ ๊ด๊ณ์์ ๋ฐ๋ ์คํธ๋ ์ค๊ฐ ๊ฐ์ฅ ์ฌํ๊ตฐ์. ์๋ค๊ฐ ๋ค๋ฅธ ์ฌ๋, ํญ์ ๋ฌด์ธ๊ฐ๋ฅผ ์๊ตฌํ๊ธฐ๋ง ํ๋ ์ฌ๋, " +
"์๊ธฐ์ฃผ์ฅ๋ง ํ๋ ์ฌ๋, ์๊ฐ ์์ด ๋ง ๋งํ๋ ์ฌ๋ ๋ฑ ์๋ฌด๋ฆฌ ์ดํดํ๋ ค๊ณ ํด๋ ์ฝ๊ฒ ์ดํด๋์ง ์๋ ์ฌ๋๋ค์ด ์์ด์. " +
"์คํด๊ฐ ๋ ์์ด๊ธฐ ์ ์ ๋ง์์ ํฐ๋๊ณ ๊น์ด ์๋ ๋ํ๊ฐ ํ์ํ์ง๋ง, ์ฝ์ง ์์ ์คํธ๋ ์ค๋ฅผ ๋ฐ๊ณ ์๋ค์.");
} else if (i == 1) {
result.setTitle("\uD83D\uDC11 ์์ ์ ํํ ๋น์ !");
result.setMessage("์ฌ๋ํ๋ ์ฌ๋๊ณผ์ ์ฐ์ ์์ ์ค๋ ์คํธ๋ ์ค๊ฐ ์๊ตฐ์. ๋์ ๋ค๋ฅธ ํ๊ฒฝ์์ ์ด์์จ ์ฐ์ธ์ ํ๋๊ณผ ์๊ฐ, " +
"์ํ๋ฐฉ์ ๋ฑ์ด ๋ง์ด ๋ค๋ฅด๋ค๋ ๊ฒ์ ์์ง๋ง, ์๋๋ฐฉ์ ํ๋์ด ์ดํด๋์ง ์๊ณ ์ง์ฆ๋๋ ์ํฉ๋ค์ด ๋ง์์. " +
"์ด๋ฐ ์ํฉ๋ค์ ๋ฐค์ ์๊ฐํ๋ค๋ฉด ์ ์ ๊ฑด๊ฐ์ ํด๋กญ๋ต๋๋ค. ๋ง์ฝ ์ฐ์ ๋ฅผ ํ์ง ์๊ณ ์ฑ๊ธ์ธ ๋น์ ์ด๋ผ๋ฉด ๋๊ตฐ๊ฐ๋ฅผ ๋ง๋ ์ฐ์ ๋ฅผ ํด์ผ ํ๋ค๋ ๊ฐ๋ฐ๊ด๋
์ด ์์ด์.");
} else if (i == 2) {
result.setTitle("\uD83D\uDC2E ์๋ฅผ ์ ํํ ๋น์ !");
result.setMessage("์ผ๊ณผ ์ฑ๊ณต์ ๋ํ ์คํธ๋ ์ค๊ฐ ๋ง๊ตฐ์! ๊ณต๋ถ์ ๋ฏธ๋์ ๋ํ ๊ฑฑ์ ๊ณผ ๊ณ ๋ฏผ์ด ๋ง์์. ๋ชจ๋ ์ผ์ ์๋ฒฝ์ ๊ธฐํ ํ์๋ ์๋ต๋๋ค. " +
"์ง๊ธ ๊ฐ๊ณ ์๋ ์ค์๊ฐ๊ณผ ๋ถ์์์ ๋ฒ์ด๋ ํ์๊ฐ ์์ด ๋ณด์ด๋ค์!");
} else if (i == 3) {
result.setTitle("\uD83D\uDC34 ๋ง์ ์ ํํ ๋น์ !");
result.setMessage("ํญ์ ๋๊ฐ์ ์ผ์์ ์ง๋ฃจํจ์ ๋๋ผ๋๊ตฐ์. ๋จ๋ค๊ณผ ๊ฐ์ ์ผ์์ ์ผ์ฆ์ ๋๋ผ์๋์? " +
"๋ ๋ฐ๋ณต๋๋ ํ๋ฃจ์ ์ง์น ๋น์ ์ ์ง์คํ๊ณ ์ฆ๊ธธ ์ ์๋ ์ผ์ ์ฐพ๊ณ ์์ด์. " +
"ํ์ง๋ง ์๋ก์ด ๊ด์ฌ์ฌ๋ ์๊ณ ์ผ์์์ ๋ฌด๋ฃํจ์ ๋๋ผ๋ฉด์ ์คํธ๋ ์ค๋ฅผ ๋ฐ๊ณ ์๋ค์!");
} else if (i == 4) {
result.setTitle("\uD83E\uDD81 ์ฌ์๋ฅผ ์ ํํ ๋น์ !");
result.setMessage("์์กด์ฌ์ด ๋ฌด์ฒ ๊ฐํ์๊ตฐ์. ๋ค๋ฅธ ์ฌ๋์ด ์์ ์ ๋ฌด์ํ๋ ํ๋๋ฅผ ๋ณด์ด๋ฉด ํ๊ฐ ๋๊ณ , ๋ค๋ฅธ ์ฌ๋๊ณผ ๋น๊ต ๋นํ๋ฉด ์ฝ๊ฒ ์์ฒ๋ฐ๊ธฐ๋ ํฉ๋๋ค. " +
"๋๊ตฐ๊ฐ ๋ด ํ๋์ ์ง์ ํ๋ ๊ฒ ๊ฐ์ผ๋ฉด ์์ถ๋๊ธฐ๋ ํด์. ์์กด์ฌ์ ์์ฒ๋ฅผ ๋ฐ์ ๋ ์คํธ๋ ์ค๋ฅผ ๋ฐ๊ณ ์๋ค์.");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote( 1,0, select[0]); //๊ทธ๋ฃน: ์ฌ๋ฆฌํ
์คํธ ๋ถ์ผ ์ค 2๋ฒ์งธ, id: ๊ฐ ๋ถ์ผ์์ ๋ฌธ์ ์ ๋ฒํธ(0๋ถํฐ ์์)
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83D\uDC74\uD83C\uDFFB ๊ธธ์ ์์ ๋
ธ์ธ", "\uD83D\uDE2D ์ฐ๋ ์์ด", "\uD83D\uDC69\u200Dโ ๋ฌผ๊ฑด์ ๋จ์ดํธ๋ฆฐ ๊ฐํธ์ฌ", "\uD83E\uDDB5 ๋์ด์ง๋ ค๋ ์ฌ๋"};
final AlertDialog.Builder result = new AlertDialog.Builder(Stress.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Stress.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83D\uDC81\uD83C\uDFFC ๋๊ตฌ๋ฅผ ๋จผ์ ๋์ฐ์๊ฒ ์ด์?").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0] = i;
if (i == 0) {
result.setTitle("\uD83D\uDC74\uD83C\uDFFB ๊ธธ์ ์์ ๋
ธ์ธ์ ์ ํํ์
จ๋ค์!");
result.setMessage("๋น์ ์ ์ ํต์ ์ธ ๋งค๋๋ฅผ ์งํต๋๋ค. ๋ฌด์จ ์ผ์ด ์ผ์ด๋๋๋ผ๋ ํญ์" +
"ํฉ๋ฆฌ์ฑ์ ๊ฐ์ง๊ณ ๊ฒฐ์ ์ ๋ด๋ฆฌ๋๊ตฐ์. ๋ ๊ฒฐ๊ณผ๊น์ง ์ผ๋์ ๋๊ณ ์๊ฐํ๋ ๋น์ !" +
"๋น์ ์ ๋ค๋ฅธ์ฌ๋๋ค์ด ๋ฐ๊ฒฌํ์ง ๋ชปํ ํํ์ง ์์ ๋ถ์ผ๋ฅผ ํ๊ตฌํ๊ณ ์ข์ํ์ง ์๋์?" +
"๊ทธ๋ฐ ๋ชจ์ต์ ๋ง์ ์ฌ๋๋ค์ด ์กด๊ฒฝํ๊ณ ์๋ค์.");
} else if (i == 1) {
result.setTitle("\uD83D\uDE2D ์ฐ๋ ์์ด๋ฅผ ์ ํํ์
จ๋ค์!");
result.setMessage("๋น์ ์ ๋๋จํ ๊ณต๊ฐ๋ฅ๋ ฅ๊ณผ ๋ฏผ๊ฐํ ๋ง์์ ๊ฐ์ง๊ณ ์์ด ์ข
์ข
์์ฒ๋ฅผ ์
๋๊ตฐ์. ๋น์ ์ ๋๊ฐ ์ฌ๋๋ค์ " +
"๋งค์ฐ ์ฝ๊ฒ ์ ๋ขฐํด์ ๋ฐฐ๋ฐ์ ๋นํ๋ฉด ์ถฉ๊ฒฉ์ ๋ง์ด ๋ฐ๋ ํ์
์
๋๋ค. ํ์คํ ๋น์ ์ ์น๊ตฌ๋ค์ ๋น์ ์๊ฒ \"" +
"์ด๋ ๊ฐ์ ๋นํ์ง ๋ง์๋ผ\"๋ผ๊ณ ๋งํ ์ ์ด ์๊ฒ ๊ตฐ์. ์ฌ์ค ์น๊ตฌ๋ค์ด ๊ทธ๋ฌ๋๊ฑด ๋ค ๊ฑฑ์ ๋๋ฌธ์ธ๊ฑฐ\n" +
" ์์์ฃ ? ๋น์ ์ ์ฌ๋์ค๋ฝ๊ฒ ์๊ฐํ๋ต๋๋ค.");
} else if (i == 2) {
result.setTitle("\uD83D\uDC69\u200Dโ๏ธ ๋ฌผ๊ฑด์ ๋จ์ดํธ๋ฆฐ ๊ฐํธ์ฌ๋ฅผ ์ ํํ๋ค์!");
result.setMessage("๋น์ ์ ์ ๋ง ๋์ฒ์ ์ธ ์ฌ๋์ด๊ตฐ์! ๋น์ ์ ๋ค๋ฅธ ์ฌ๋๋ค์ด ๋์น์ฑ์ง ๋ชปํ๋ ์๋ฆ๋ค์๊น์ง" +
"๋๋ ์ ์๋ ์ฌ๋์
๋๋ค. ๋ฌธ์ ๊ฐ ์์ ๋๋ง๋ค ๊ณตํํ ํ๋จ์ ๋ด๋ฆฌ๊ณ ์ถ์ดํ๊ณ ์. ์ถ์ด ๋๋๋ก" +
"์ด๋ ค์ ์ง์ง๋ผ๋, ๋น์ ์ ๋๊ด์ ์ธ ์ฑ๊ฒฉ์ ์ ์งํฉ๋๋ค. ๊ทธ๋์ ๋ชจ๋ ์ฌ๋๋ค์ด ๋น์ ๊ณผ ์ด์ธ๋ฆฌ๊ณ ์ถ์ด ํ๋๊ตฐ์!");
} else if (i == 3) {
result.setTitle("\uD83E\uDDB5 ๋์ด์ง๋ ค๋ ์ฌ๋์ ์ ํํ๋ค์!");
result.setMessage("๋น์ ์์ด ์ฆ๊ฒ๊ณ ์ฌ๋ฏธ์๋ ๋ชจ์์ ๊ฐ์ง ์ ์์๊ฑฐ์์. ๋ค๋ฅธ ์ฌ๋๋ค์ ๋น์ ์ " +
"๋ฆฌ๋๋ก ์๊ฐํด์. ๋น์ ์ ๋ณธ์ธ๋ ๋ชจ๋ฅด๊ฒ ์ฃผ๋ณ์ ๋์ด๋น๊ธฐ๊ณ ์ค๋ํ๋ ๋ฒ์ ์๊ณ ์์ต๋๋ค!" +
"๋ชฉํ๋ฅผ ํ๋ฒ ์ค์ ํ๋ฉด ๋ฉ์ถ ์ค ๋ชจ๋ฅด๋๊ตฐ์! ๊ทธ๋ฐ ๋ชจ์ต์ ๋ง์ ์ฌ๋๋ค์ด ๋น์ ์ ๋ฐ๋ฅด๋ ค๊ณ ํ๋ค์.");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote( 1,1, select[0]);
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
three.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83D\uDE2A ์ ๋ฉด์ผ๋ก", "\uD83D\uDE2B ์๋๋ ค์", "โฐ ์ผ์ชฝ์ผ๋ก", "\uD83D\uDCA4 ์ค๋ฅธ์ชฝ์ผ๋ก"};
final AlertDialog.Builder result = new AlertDialog.Builder(Stress.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Stress.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83D\uDECC ๋น์ ์ ์ ๋ค ๋ ์ด๋ค ๋ชจ์ต์ธ๊ฐ์?").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0]=i;
if (i == 0) {
result.setTitle("\uD83D\uDE2A ์ ๋ฉด์ผ๋ก");
result.setMessage("๋น์ ์ ์ฌ๊ณ ๋ฐฉ์์ด ๋
ํนํ ๊ฐ์ฑ์๋ ๋งค๋ ฅ์ ์์ ์์
๋๋ค. ์์ ๊ณผ ์ฃผ๊ด์ด ๋๋ ทํ๋ฉฐ " +
"์์ ๋ง์ ์ฌ๊ณ ๋ฐฉ์์ผ๋ก ๋๋ผ์ด ๋ฐ์์ ํ๋ค์. ๊ฐ์ ์ ์ธ ๋ฉด์์ ๋จ์ํ๊ณ ์ฒ์ง๋๋งํ๋ฉฐ ์ฆ์ค๋" +
"๋ฐฐ์ ๊ฐ์ ๊ฐ๊ฒ ๋์ด๋ ๊ธ์ธ ์๊ณ ๋จ์ณ๋ด๊ณ ์๋ค์.");
} else if (i == 1) {
result.setTitle("\uD83D\uDE2B ์๋๋ ค์");
result.setMessage("๋น์ ์ ์ฌ๋๋ค ์์ ์ ์ ๊ฒฝ์ฐ๋ ํธ์ด๋ฉฐ ์ฌ๋์ ์๋ ๊ฒ์ ๋ํ ๋๋ ค์์ด ์์ด" +
"์ธ์์ด ์๊ฒจ๋ ํญ์ ์ค๋ฆฝ์ ์
์ฅ์ ์ ์งํฉ๋๋ค. ๊ฒ์ผ๋ก๋ ์ฟจํด๋ณด์ด๊ณ ๋๋ํ์ง๋ง ์ฌ์ค ์์ผ๋ก๋ ์ฌ๋ฆฐ์ฌ๋!");
} else if (i == 2) {
result.setTitle("โฐ ์ผ์ชฝ์ผ๋ก");
result.setMessage("๋น์ ์ ๋งค์ฐ ์๋ฅํ๊ณ ์ฃผ๋ณ ์ฌ๋๋ค์๊ฒ ์ ๋ฒ ํธ๋ ์น์ ํ ์ฌ๋์
๋๋ค." +
"์ฐจ๋ถํ ์ฑ๊ฒฉ์ผ๋ก ์ด๋ค ์ผ์ด ๋ฅ์ณ๋ ์ฐจ๋ถํ๊ฒ ๋์ฒํฉ๋๋ค. ๋ง์์ด ์ฌ๋ ค์ ์ฝ๊ฒ ๊ฐ๋๋ฐ๊ณ " +
"๋๋ฌผ๋ ๋ง์ ํธ์ด๋ฉฐ ์ฃผ๋ณ ์ฌ๋๋ค์ ๋น์ ์๊ฒ ํฌ๊ทผํจ์ ๋๊ปด ๋น์ ์ ์์งํ๊ณ ๋ฐ๋ฆ
๋๋ค.");
} else if (i == 3) {
result.setTitle("\uD83D\uDCA4 ์ค๋ฅธ์ชฝ์ผ๋ก");
result.setMessage("์ฐธ์์ฑ์ด ๋ง์ ๋น์ ์ ์ ์ข์ ์ผ์ด ์๊ฒจ๋ ๋ง์์ ๋ด์ ๋๊ณ ์ธ๋ดํ๋ ํธ์
๋๋ค." +
"๊ฐ์์ฑ์ด ํ๋ถํ๊ณ ์ฌ๋ ค๊น์ ๋น์ ์ ์น๊ตฌ๋ค์ ์ด์ผ๊ธฐ๋ ์๊ธฐ์ผ์ฒ๋ผ ๊ณต๊ฐํ๋ฉฐ ๋ค์ด์ค๋๋ค.");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote( 1,2, select[0]);
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
}
private void readData() {
List<Note> notes = db.getGroupNotes(1);
for(Note n : notes){
String date = n.getTimestamp();
int select = n.getSelectitem();
Button btn = null;
switch (n.getId()) {
case 0:
btn=one;
one.setText("1. \uD83D\uDE1E ์คํธ๋ ์ค ์์ธ"+"\n(ํ
์คํธํ ๋ ์ง: " + date + ")"); //๋ฒํผ์ ํ
์คํธ์ ํ
์คํธํ ๋ ์ง๋ฅผ ๋ค์ ์ถ๊ฐ.
break;
case 1:
btn=two;
two.setText("2. \uD83D\uDC67 ๋จ๋ค์๊ฒ ๋ณด์ด๋ ๋ "+"\n(ํ
์คํธํ ๋ ์ง: " + date + ")");
break;
case 2:
btn=three;
three.setText("3. \uD83D\uDC66 ๋์ ์ฑ๊ฒฉ"+"\n(ํ
์คํธํ ๋ ์ง: " + date + ")");
break;
}
try {
btn.setBackgroundColor(Color.GRAY); //์ด๋ฏธ ๋๋ธ ์ฌ๋ฆฌํ
์คํธ๋ ๋ฐฐ๊ฒฝ์ ํ์๊ณผ ํฐํธ๋ ํฐ์์ผ๋ก ๋ฐ๊ฟ.
btn.setTextColor(Color.WHITE);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
<file_sep>package com.example.appprogrammingproject;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.widget.ImageView;
import android.widget.TextView;
import com.example.appprogrammingproject.Utils.FileUtiil;
import org.tensorflow.lite.Interpreter;
import org.tensorflow.lite.support.common.TensorProcessor;
import org.tensorflow.lite.support.image.TensorImage;
import org.tensorflow.lite.support.tensorbuffer.TensorBuffer;import org.tensorflow.lite.DataType;
import org.tensorflow.lite.support.common.TensorOperator;
import org.tensorflow.lite.support.common.ops.NormalizeOp;
import org.tensorflow.lite.support.image.ImageProcessor;
import org.tensorflow.lite.support.image.ops.ResizeOp;
import org.tensorflow.lite.support.image.ops.ResizeWithCropOrPadOp;
import org.tensorflow.lite.support.image.ops.Rot90Op;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.util.List;
import java.util.Map;
public class Face extends AppCompatActivity {
/**
* Float model does not need dequantization in the post-processing. Setting mean and std as 0.0f
* and 1.0f, repectively, to bypass the normalization.
*/
private static final float PROBABILITY_MEAN = 0.0f;
private static final float PROBABILITY_STD = 1.0f;
/** Image size along the x axis. */
private int imageSizeX;
/** Image size along the y axis. */
private int imageSizeY;
/** Input image TensorBuffer. */
private TensorImage inputImageBuffer;
/** Output probability TensorBuffer. */
private TensorBuffer outputProbabilityBuffer;
/** Processer to apply post processing of the output probability. */
private TensorProcessor probabilityProcessor;
Interpreter tflite;
private final Interpreter.Options tfliteOptions = new Interpreter.Options();
/** Labels corresponding to the output of the vision model. */
private static final int IMAGE_MEAN = 128;
private static final float IMAGE_STD = 128.0f;
private MappedByteBuffer tfliteModel;
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
TextView textView;
Bitmap imageBitmap;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_face);
textView = findViewById(R.id.textView);
imageView = findViewById(R.id.imageView);
dispatchTakePictureIntent();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
Bundle extras = data.getExtras();
Bitmap imageBitmap = (Bitmap) extras.get("data");
this.imageBitmap = imageBitmap;
imageView.setImageBitmap(imageBitmap);
predict();
}
}
private void predict(){
AssetManager assetManager = getApplicationContext().getAssets();
InputStream istr;
try {
tfliteModel = FileUtiil.loadMappedFile(this, "cat_dog_cnn_color.tflite");
//istr = assetManager.open("dog.4.jpg");
//imageBitmap = BitmapFactory.decodeStream(istr);
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, 224, 224, true);
} catch (IOException e) {
e.printStackTrace();
}
tflite = new Interpreter(tfliteModel, tfliteOptions);
int imageTensorIndex = 0;
int[] imageShape = tflite.getInputTensor(imageTensorIndex).shape();
imageSizeY = imageShape[1];
imageSizeX = imageShape[2];
DataType imageDataType = tflite.getInputTensor(imageTensorIndex).dataType();
int probabilityTensorIndex = 0;
int[] probabilityShape =
tflite.getOutputTensor(probabilityTensorIndex).shape(); // {1, NUM_CLASSES}
DataType probabilityDataType = tflite.getOutputTensor(probabilityTensorIndex).dataType();
float[] out = null;
// Creates the input tensor.
inputImageBuffer = new TensorImage(imageDataType);
// Creates the output tensor and its processor.
outputProbabilityBuffer = TensorBuffer.createFixedSize(probabilityShape, probabilityDataType);
// Creates the post processor for the output probability.
// fixme ๋ฃ์๊น ๋ง๊น?
probabilityProcessor = new TensorProcessor.Builder().add(getPostprocessNormalizeOp()).build();
inputImageBuffer = loadImage(imageBitmap,1);
tflite.run(inputImageBuffer.getBuffer(), outputProbabilityBuffer.getBuffer().rewind());
out = outputProbabilityBuffer.getFloatArray();
/*set text view*/
if (out[0] < 0.5f) {
textView.setText("๊ณ ์์ด");
} else {
textView.setText("๊ฐ์์ง");
}
}
private void dispatchTakePictureIntent() {
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
}
}
private TensorImage loadImage(Bitmap bitmap,int sensorOrientation) {
inputImageBuffer.load(bitmap);
int cropSize = Math.min(bitmap.getWidth(), bitmap.getHeight());
int numRotation = sensorOrientation / 90;
// TODO(b/143564309): Fuse ops inside ImageProcessor.
ImageProcessor imageProcessor =
new ImageProcessor.Builder()
.add(new ResizeWithCropOrPadOp(cropSize, cropSize))
.add(new ResizeOp(imageSizeX, imageSizeY, ResizeOp.ResizeMethod.NEAREST_NEIGHBOR))
.add(new Rot90Op(numRotation))
.add(getPreprocessNormalizeOp())
.build();
return imageProcessor.process(inputImageBuffer);
}
protected TensorOperator getPreprocessNormalizeOp() {
return new NormalizeOp(IMAGE_MEAN, IMAGE_STD);
}
protected TensorOperator getPostprocessNormalizeOp() {
return new NormalizeOp(PROBABILITY_MEAN, PROBABILITY_STD);
}
}
<file_sep>package com.example.appprogrammingproject;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import androidx.annotation.Nullable;
public class Stest extends Activity {
Button study,love,friend,stress;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.stest);
study=findViewById(R.id.study);
love=findViewById(R.id.love);
friend=findViewById(R.id.friend);
stress=findViewById(R.id.stress);
study.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent sd=new Intent(getApplicationContext(),Study.class);
startActivity(sd);
}
});
love.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent lv=new Intent(getApplicationContext(),Love.class);
startActivity(lv);
}
});
friend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent fi=new Intent(getApplicationContext(),Friend.class);
startActivity(fi);
}
});
stress.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent st=new Intent(getApplicationContext(),Stress.class);
startActivity(st);
}
});
}
}
<file_sep>package com.example.appprogrammingproject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import com.example.appprogrammingproject.database.DatabaseHelper;
import com.example.appprogrammingproject.database.model.Note;
import java.io.File;
import java.io.FileWriter;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import androidx.annotation.CheckResult;
import androidx.annotation.Nullable;
public class Study extends Activity {
Button one, two, three, four;
long now = System.currentTimeMillis();
Date dateTime = new Date(now);
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String getTime = simpleDate.format(dateTime);
private DatabaseHelper db;
private void createNote( int group,int id, int select) {
db.insertNote(id, group, select);
readData();
}
final int[] select = {0};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.study);
db = new DatabaseHelper(this);
List<Note> n = db.getAllNotes();
one = findViewById(R.id.one);
two = findViewById(R.id.two);
three = findViewById(R.id.three);
four = findViewById(R.id.four);
readData();
//๋ฒํผ์ ๋๋ ์๋ dialog ๋์ด ํ์ ์ฌ๋ฆฌํ
์คํธ ์งํ
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83D\uDEB6\u200Dโ๏ธ ๊ณ์ ๊ฑท๋๋ค", "\uD83D\uDE83 ๋ง์ฐจ",
"\uD83D\uDE96 ํ์", "\uD83D\uDC68\u200Dโค๏ธ\u200D\uD83D\uDC68 ์น๊ตฌ์ ๊ฑท๋๋ค"};
final AlertDialog.Builder result = new AlertDialog.Builder(Study.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Study.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83D\uDEE3๏ธ ๊ธธ์ ๊ฑท๊ณ ์๋ ๋น์ , ๋ญ๊ฐ๋ฅผ ํ ์ ์๋ค๋ฉด ์ ํํ ์๋จ์ ๊ณจ๋ผ์ฃผ์ธ์").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0] = i;
if (i == 0) {
result.setTitle("\uD83D\uDEB6\u200Dโ ์ญ ๊ฑธ์ด์๋๋ฐ, ๋ญ ๊ณ์ ๊ฑท์!");
result.setMessage("๋น์ ์ ์ธ์ ๋ ์์ ์ ๋ฌธ์ ๋ฅผ ์ค์ค๋ก ํด๊ฒฐํ๋ ํ์
์
๋๋ค. ์๋ฆฝ์ ์ด๋ผ๋ ๋ง ์์ฃผ ๋ฃ์ง ์๋์? ๋์ ๋๋ " +
"ํ์
์ ์๋์ง๋ง ํผ์ ๊ถ๊ธํ ์ ์ ์ฐจ๋ถํ ํด๊ฒฐํด ๋๊ฐ๋ ํธ์ผ๋ก, ๋ฌธ์ ์์์ ๋ฅ๋์ ์ธ ํ๋๋ฅผ ๋ณด์
๋๋ค.");
} else if (i == 1) {
result.setTitle("\uD83D\uDE83 ๊ท์กฑ์ฒ๋ผ ๋ง์ฐจ๋ฅผ ํ๊ณ ๊ฐ์!");
result.setMessage("๋น์ ์ ์ด๋ค ๋ฌธ์ ๋ฅผ ๋ง์ฃผํด๋ ๊ฒ๋จน์ง ์๊ณ ์ ๊ทน์ ์ผ๋ก ํ์ด๋๊ฐ๋ ๋น์ฐฌ ํ์
์
๋๋ค. ํผ์์ ํด๊ฒฐํ๊ธฐ ๋ณด๋ค๋ ํด๊ฒฐ์ ์ํด์๋ผ๋ฉด ์ด๋ค " +
"๋ฐฉ๋ฒ์ด๋ ์ ๊ทน์ ์ผ๋ก ๋์๊ณ ์ง๋ฌธํฉ๋๋ค. ๋ฐ๋ผ์ ๋ค๋ฅธ ์น๊ตฌ๋ค์ ๊ถ๊ธ์ฆ๊น์ง ๋๋งก์ ํด๊ฒฐํด์ฃผ๋ ๊ณ ๋ง์ด ํ์
์
๋๋ค. ๊ณต๋ถ ๋ฐฉ๋ฒ๋ ์ ์๋, ์ ๋ฐฐ๋ค์๊ฒ ์ง๋ฌธํ๋ฉด์ ์ง์์ ์ป๋ ํธ์
๋๋ค.");
} else if (i == 2) {
result.setTitle("\uD83D\uDE96 ์ญ์ ๋น ๋ฅด๊ฒ ๊ฐ ๋ ํ์์ง!");
result.setMessage("๋น์ ์ ๊ณต๋ถ์ ํ์ํ ์ ๋ณด๋ค์ ์ ๋ฆฌํ๋ ํ์ํ ๋ฅ๋ ฅ์ ์์ ์์
๋๋ค. ๊ณต๋ถ ๋ฐฉ๋ฒ๋ ๋
ธํธ ์ ๋ฆฌ ์์ฃผ๋ก ํฉ๋๋ค. ๋ค๋ฅธ ์น๊ตฌ๋ค์ ๋นํด ๋
ธํธ ํ๊ธฐ๊ฐ ๊ผผ๊ผผํ ํ
๋ฐ์. " +
"ํ์ง๋ง ๋จ์ ์ด ์๋ค๋ฉด, ๊ณต๋ถ๋ฅผ ์์ํ๊ธฐ ์ ์ฑ
์ ์ ๋ฆฌ๋ถํฐ ์์ํด ๊ณต๋ถ ์๊ฐ์ ๋ง์ด ๋นผ์๊ธธ ์๋ ์์ต๋๋ค.");
} else if (i == 3) {
result.setTitle("\uD83D\uDC68\u200Dโค๏ธ\u200D\uD83D\uDC68 ์ธ๋กญ์ง ์๊ฒ ์น๊ตฌ์ ๊ฑธ์ด์ผ์ง!");
result.setMessage("๋น์ ์ ์ด์ผ๊ธฐ๋ฅผ ์ข์ํ๋ ์๋ค์์ด ํ์
์
๋๋ค. ์น๊ตฌ์ ํจ๊ป ๋ฌธ์ ๋ฅผ ํ๊ฑฐ๋ ์ค๋ช
ํด ์ฃผ๊ณ ํด์ฆ๋ฅผ ๋ด๋ฉด์ ๊ณต๋ถํ๋ ๊ฒ์ ์ฆ๊น๋๋ค. " +
"์ธ์ ๋ ์น๊ตฌ์ ํจ๊ป ํ๋ ๊ฒ์ ์ข์ํ๋ ๋น์ ์ ๋งํ๋ ๊ฑธ ์ข์ํด์ ํ ๋ก ๋ฅ๋ ฅ์ด ๋จ๋ค๋ณด๋ค ๋ฐ์ด๋ฉ๋๋ค.");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@SuppressLint("SetTextI18n")
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote(0,0,select[0]);
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83D\uDD32 ์ ์ฌ๊ฐํ", "โฌ ์ง์ฌ๊ฐํ", "\uD83D\uDD3A ์ผ๊ฐํ", "โญ ๋๊ทธ๋ผ๋ฏธ", "\uD83C\uDF2B๏ธ ๊ตฌ๋ถ๊ตฌ๋ถํ ์ "};
final AlertDialog.Builder result = new AlertDialog.Builder(Study.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Study.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83E\uDDF1 ๋ง์์ ๋๋ ๋ํ์ ์ ํํด์ฃผ์ธ์").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0] = i;
if (i == 0) {
result.setTitle("\uD83D\uDD32 ์ ์ฌ๊ฐํ");
result.setMessage("์์ ์ ์ธ ํ๊ฒฝ๊ณผ ๋ถ๋ช
ํ ๋ฐฉํฅ์ด ์ ์๋์์ ๋ ํธ์ํจ์ ๋๋ผ๋ ์ฌ๋์
๋๋ค. ๋ณด์์ ์ธ ์ฑํฅ์ด ์์ผ๋ฉฐ ๋ฑ ๋ง์๋จ์ด์ง๊ณ ์ ๋๋ ๊ฒ์ ์ข์ํฉ๋๋ค. " +
"์๋ฌด๋ฆฌ ๋ฐ๋ณต์ ์ด๊ณ ์ฑ๊ฐ์ ์ผ์ด๋๋ผ๋ ์ผ์ด ๋๋ ๋๊น์ง ์๋ฒฝํ ํด๋ด๋ ์๋ฒฝ์ฃผ์์์
๋๋ค. " +
"๊ทธ๋์ ๊ณต๋ถ๋ ์ด๋์ ํ ๋๋ ์ ํํ ๊ณํ์ด ์ธ์์ ธ ์์ด์ผ ์์ฌ์ด ๋๊ณ ๋ชฉํ๋ฅผ ํฅํด ๋ฌ๋ ค๊ฐ ์ ์์ต๋๋ค.");
} else if (i == 1) {
result.setTitle("โฌ ์ง์ฌ๊ฐํ");
result.setMessage("์ ์ฌ๊ฐํ์ ์ข์ํ๋ ์ฌ๋๊ณผ ๋น์ทํ๊ฒ ๊ท์น์ ์ธ ๊ฒ๊ณผ ์ ๋๋ ๊ฒ์ ์ข์ํฉ๋๋ค. ํ์ง๋ง ์ผ์ ํ ๋ ์์ฐจ๋ก ํ์๋ฅผ ๊ฑฐ์น๋ ๋ฑ " +
"์ ํด์ง ๋ฃฐ์ ๋ฒ์ด๋์ง ์์ผ๋ ค๊ณ ํ๋ ๋ฉด์ด ์์ต๋๋ค. ๋ํ ๋งค์ฐ ์ธ์ฌํ๊ณ ๊ณํ์ ์ธ ์ฌ๋์ด๋ผ๊ณ ํ ์ ์์ต๋๋ค.");
} else if (i == 2) {
result.setTitle("\uD83D\uDD3A ์ผ๊ฐํ");
result.setMessage("๋ชฉํ์งํฅ์ ์ธ ์ฌ๋์
๋๋ค. ์ด๋์ด๋ ํ์
์ ํ๊ธฐ ์ ๊ณํํ์ฌ ์คํํฉ๋๋ค. ์ฑ์ทจ๊ฐ์ ๋ค์ ๋๊ธฐ๋ถ์ฌ๋ฅผ ๋ฐ๋ ์ฌ๋์ด์ฃ . " +
"ํฌ๊ณ ์ฅ๊ธฐ์ ์ธ ๋ชฉํ์ ์ด์ ์ ๋ง์ถ๋ ํธ์
๋๋ค. ๊ทธ๋์ ๋๋ก๋ ์์ ๋ํ
์ผ์ ๋์น๋ ๊ฒฝ์ฐ๊ฐ ์์ต๋๋ค.");
} else if (i == 3) {
result.setTitle("โญ ๋๊ทธ๋ผ๋ฏธ");
result.setMessage("์ฌ๊ต์ ์ด๊ณ ์์ฌ์ํต์ด ์ํํ๋ฉฐ ์ฌ๊ธ์ฌ๊ธํ ์ฑ๊ฒฉ์
๋๋ค. ์ด๋ฐ ์ฌ๋์ ์ฅ์ ์ ๋ฐ๋ก ์ ํต์ฑ์ด ์๋ค๋ ๊ฒ์ด์ฃ . " +
"๊ณํํ๋ ์ผ์ด ์์ด๋ ์ํฉ์ ๋ฐ๋ผ ์กฐ๊ธ์ฉ ๋ฐฉํฅ์ ์์ ํด ๋๊ฐ๋๋ค. " +
"๋ํ ์์ฌ์ํต์ ์ข์ํ๊ธฐ ๋๋ฌธ์ ๊ณํ์ ์ธ์ธ ๋ ์ฃผ์ ์ฌ๋๋ค์ ์๊ฒฌ์ ๋ง์ด ๋ฃ๊ณ ์ฐธ๊ณ ํ๋ ๊ฒฝํฅ์ด ์์ต๋๋ค.");
} else if (i == 4) {
result.setTitle("\uD83C\uDF2B๏ธ ๊ตฌ๋ถ๊ตฌ๋ถํ ์ ");
result.setMessage("์์ธกํ ์ ์์ผ๋ฉฐ ์ฐฝ์์ ์ธ ์ฌ๋์
๋๋ค. ์๋ก์ด ์ผ์ ํ ๋ ๊ฐ์ฅ ๊ธฐ๋ถ์ด ์ข์์ง๋ฉฐ ๋ฐ๋ณต์ ์ธ ๊ฒ์ ์ซ์ดํฉ๋๋ค. ์ด๋ค ์ผ์ด ์ฃผ์ด์ง๋ฉด ๊ฐ์ฅ " +
"์๋กญ๊ณ ์ฐฝ์์ ์ธ ์์ด๋์ด๋ฅผ ๋ ์ฌ๋ฆฝ๋๋ค. ๊ทธ๋์ ๊ณํ์ ์ธ์ฐ๊ณ ์ด๋ค ์ผ์ ํ๊ธฐ ๋ณด๋ค๋ ์ฆํฅ์ ์ธ ๋ฉด์ด ์์ต๋๋ค. " +
"๋๋ก๋ ์ด๋ฌํ ๊ณํ์ฑ์ด ์ข์ ๊ฒฐ๊ณผ๋ฅผ ๋ด๊ธฐ๋ ํ์ง๋ง, ๋๋ก๋ ๋ชฉํ์ ๋๋ฌํ์ง ๋ชปํ ๋๊ฐ ์์ด ์กฐ์ฌํด์ผ ํ ํ์๋ ์์ต๋๋ค.");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote(0,1,select[0]);
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
three.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83D\uDE32 ๋์์ ๋ง์ฃผ๋ณธ๋ค", "\uD83D\uDC81\u200Dโ๏ธ ๋์์ ๋ชธ์ ๊ธฐ๋๋ค", "\uD83E\uDD38 ๋์์ ํ์์๊ณ ๋๋ง์ ํฌ์ฆ๋ฅผ ์ทจํ๋ค", "\uD83D\uDC68\u200D\uD83D\uDC66 ์ด๊นจ๋๋ฌด๋ฅผ ํ๋ค"};
final AlertDialog.Builder result = new AlertDialog.Builder(Study.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Study.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83D\uDDFD ๋น์ ์ ๋ฉ์ง ๋์์ ๋ฐ๊ฒฌํ์ต๋๋ค! ์ด๋ค ์์ธ๋ก ์ฌ์ง์ ์ฐ์ ๊ฑด๊ฐ์?").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0] = i;
if (i == 0) {
result.setTitle("\uD83D\uDE32 ๋ค์ ํ๊ฒ ๋์์ ๋ง์ฃผ๋ณด๊ณ ํฌ์ฆ๋ฅผ ์ทจํ๋ค");
result.setMessage("๊ณต๋ถ์ ๋ํ ์์ฌ, ์ฑ๊ณต์ ๋ํ ์์ฌ์ด ๋ง์ ์ฌ๋์
๋๋ค. ๋๊ตฐ๊ฐ์๊ฒ ์ง๊ธฐ ์ซ์ด์ ๋๊ตฌ๋ณด๋ค ์ด์ฌํ ํ๋ ํ์ ์คํ์ผ์
๋๋ค.");
} else if (i == 1) {
result.setTitle("\uD83D\uDC81\u200Dโ๏ธ ๋์์ ๊ธฐ๋๋ ํธ์ํ ํฌ์ฆ๋ฅผ ์ทจํ๋ค");
result.setMessage("๊ณต๋ถ์ ๋ณ๋ก ๊ด์ฌ์ด ์๊ตฐ์! ์ฐ๋งํ๋ค๋ ์๋ฆฌ๋ฅผ ๋ง์ด ๋ฃ์ง๋ง ์ข์ํ๋ ๋ถ์ผ๊ฐ ์๊ธฐ๋ฉด ์ด์ฌํ ํ๋ ์์ ๋ก์ด ์คํ์ผ์
๋๋ค.");
} else if (i == 2) {
result.setTitle("\uD83E\uDD38 ๋์์ ๋ฌด์ํ๊ณ ์์ ๋ง์ ํฌ์ฆ๋ฅผ ์ทจํ๋ค");
result.setMessage("๊ณต๋ถ๋ณด๋ค๋ ์์ฒด๋ฅ์ ์ฌ๋ฅ์ด ๋ ๋ง๊ตฐ์! ์ด๋๋ก ํ์ง ๋ชจ๋ฅด๋ ์ฑ๊ฒฉ์ผ๋ก, ๊ณต๋ถ์ ์ ๋
ํด์ ์คํธ๋ ์ค๋ฅผ ๋ฐ๋ ๊ฒ๋ณด๋จ ์์ฒด๋ฅ์ ๋์ ํด๋ณด์ธ์!");
} else if (i == 3) {
result.setTitle("\uD83D\uDC68\u200D\uD83D\uDC66 ์ด๊นจ๋๋ฌด๋ฅผ ํ๊ณ ์ฌ์ง์ ์ฐ๋๋ค");
result.setMessage("๊ณต๋ถ๋ฅผ ๊ณ์ํด์ ํ๋ ์คํ์ผ์ ์๋์ง๋ง, ๊ฝค ๋ง์กฑํ๋ ์ฑ์ ์ด ๋์ค๋ ๊ฒ ๊ฐ๋ค์. ๊ณต๋ถ์ ๋ํ ๊ฑฐ๋ถ๊ฐ์ด ์์ด ํ์ต์์ฃผ๋ก ๊ณต๋ถํด ๋ณด์ธ์!");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote(0,2,select[0]);
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
}
private void readData() {
List<Note> notes = db.getGroupNotes(0);
for(Note n : notes){
String date = n.getTimestamp();
int select = n.getSelectitem();
Button btn = null;
switch (n.getId()) {
case 0:
btn=one;
one.setText("1. \uD83D\uDCDC ๋์ ๊ณต๋ถ ํ๋"+"\n(ํ
์คํธํ ๋ ์ง: " + date + ")"); //๋ฒํผ์ ํ
์คํธ์ ํ
์คํธํ ๋ ์ง๋ฅผ ๋ค์ ์ถ๊ฐ.
break;
case 1:
btn=two;
two.setText("2. \uD83D\uDCD6 ๋์ ๊ณํ์ฑ"+"\n(ํ
์คํธํ ๋ ์ง: " + date + ")");
break;
case 2:
btn=three;
three.setText("3. \uD83D\uDCD3 ๋์ ๊ณต๋ถ ์คํ์ผ"+"\n(ํ
์คํธํ ๋ ์ง: " + date + ")");
break;
case 3:
btn = four;
break;
}
try {
btn.setBackgroundColor(Color.GRAY); //์ด๋ฏธ ๋๋ธ ์ฌ๋ฆฌํ
์คํธ๋ ๋ฐฐ๊ฒฝ์ ํ์๊ณผ ํฐํธ๋ ํฐ์์ผ๋ก ๋ฐ๊ฟ.
btn.setTextColor(Color.WHITE);
}catch (Exception e){
e.printStackTrace();
}
}
}
}
<file_sep>import tensorflow as tf
import matplotlib.pyplot as plt
import cv2
import os
import numpy as np
import random
x_train = []
y_train = []
x_test = []
y_test = []
foldernames = os.listdir('../catdog/training_set/training_set')
for k, folder in enumerate(foldernames):
len = 0
for c, file in enumerate(os.listdir('../catdog/training_set/training_set' + '/' + folder)):
if c > 150:
len = c
break
img = cv2.imread('../catdog/training_set/training_set' + '/' + folder + '/' + file)
img = cv2.resize(img, (224, 224))
img = img.reshape(224, 224, 3)
x_train.append(img)
y_train += [k] * len
foldernames = os.listdir('../catdog/test_set/test_set')
for k, folder in enumerate(foldernames):
len = 0
for c, file in enumerate(os.listdir('../catdog/test_set/test_set' + '/' + folder)):
if c > 10:
len = c
break
img = cv2.imread('../catdog/test_set/test_set' + '/' + folder + '/' + file)
img = cv2.resize(img, (224, 224))
img = img.reshape(224, 224, 3)
x_test.append(img)
y_test += [k] * len
x_train = np.array(x_train)
y_train = np.array(y_train)
x_test = np.array(x_test)
y_test = np.array(y_test)
x_train = x_train / 255.0
x_test = x_test / 255.0
y_train = tf.keras.utils.to_categorical(y_train)
y_test = tf.keras.utils.to_categorical(y_test)
print(y_train)
model = tf.keras.Sequential([
tf.keras.layers.Convolution2D(filters=64, kernel_size=(3, 3),
padding='same', activation='relu', input_shape=(224, 224, 3)),
tf.keras.layers.Convolution2D(filters=64, kernel_size=(3, 3), activation='relu', strides=(2, 2)),
tf.keras.layers.Convolution2D(filters=64, kernel_size=(3, 3), activation='relu', strides=(2, 2)),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
strides=(1, 1), padding='valid'),
tf.keras.layers.Convolution2D(filters=128, kernel_size=(3, 3), activation='relu', strides=(2, 2)),
tf.keras.layers.Convolution2D(filters=128, kernel_size=(3, 3), activation='relu', strides=(2, 2)),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
strides=(1, 1), padding='valid'),
tf.keras.layers.Convolution2D(filters=256, kernel_size=(3, 3), activation='relu'),
tf.keras.layers.Convolution2D(filters=256, kernel_size=(3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
strides=(1, 1), padding='valid'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(2, activation='softmax')
])
print(model.summary())
# model.compile(optimizer=tf.keras.optimizers.Adam(), loss='categorical_crossentropy', metrics=['accuracy'])
#
# his = model.fit(x_train, y_train, epochs=2, batch_size=100)
#
# test_loss, test_acc = model.evaluate(x_test, y_test, verbose=2)
# print(test_acc)
#
# model.save('./model/cat_dog_cnn')
#
# converter = tf.lite.TFLiteConverter.from_saved_model('./model/cat_dog_cnn')
#
# tflite_model = converter.convert()
# open("./liteModel/cat_dog_cnn.tflite", "wb").write(tflite_model)
<file_sep>package com.example.appprogrammingproject;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.PersistableBundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.example.appprogrammingproject.database.DatabaseHelper;
import com.example.appprogrammingproject.database.model.Note;
import java.util.Collections;
import java.util.List;
import androidx.annotation.Nullable;
public class Recommend extends Activity {
TextView study, stress, love, friend;
Button studyBtn,stressBtn,loveBtn,friendBtn;
private DatabaseHelper db;
private void createNote(int group, int id, int select) {
db.insertNote(id, group, select);
}
final int[] select = {0};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.recommend);
db = new DatabaseHelper(this);
List<Note> n = db.getAllNotes();
study = findViewById(R.id.study);
stress = findViewById(R.id.stress);
love = findViewById(R.id.love);
friend = findViewById(R.id.friend);
studyBtn=findViewById(R.id.studyBtn);
stressBtn=findViewById(R.id.stressBtn);
loveBtn=findViewById(R.id.loveBtn);
friendBtn=findViewById(R.id.friendBtn);
String getSelet = getIntent().getStringExtra("select");
readData();
studyBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),Study.class);
startActivity(intent);
}
});
loveBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),Love.class);
startActivity(intent);
}
});
friendBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),Friend.class);
startActivity(intent);
}
});
stressBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent=new Intent(getApplicationContext(),Stress.class);
startActivity(intent);
}
});
}
private void readData() {
List<Note> notes = db.getAllNotes();
for (Note n : notes) {
switch (n.getGroupitem()) {
case 0://์ฌ๋ฆฌํ
์คํธ ๊ณต๋ถ๋ฅผ ์ ํํ์ ๋
switch (n.getId()) {
case 0://๊ณต๋ถ ์ฌ๋ฆฌํ
์คํธ ์ค ์ฒ์ ์ฌ๋ฆฌํ
์คํธ ์ ํ
study.setTextSize(20);
stress.setTextSize(20);
love.setTextSize(20);
friend.setTextSize(20);
switch (n.getSelectitem()) {
case 0:
study.setText(study.getText() + "\n๊ณต๋ถํ๊ธฐ ์ข์ ์ฅ์ : ๋
์์ค\n");
break;
case 1:
study.setText(study.getText() + "\n๊ณต๋ถํ๊ธฐ ์ข์ ์ฅ์ : ์คํฐ๋ ๊ทธ๋ฃน ๋ฐฉ\n");
break;
case 2:
study.setText(study.getText() + "\n๊ณต๋ถํ๊ธฐ ์ข์ ์ฅ์ : ์ง\n");
break;
}
break;
case 1:
switch (n.getSelectitem()) {
case 0:
study.setText(study.getText() + "\n๊ณต๋ถํ๋ ๋ฐฉ๋ฒ : ๋ชฉํ ๋จผ์ ์ธ์ฐ๊ธฐ\n");
break;
case 1:
study.setText(study.getText() + "\n๊ณต๋ถํ๋ ๋ฐฉ๋ฒ : ์คํฐ๋ํ๋๋ ์ฌ์ฉ\n");
break;
case 2:
study.setText(study.getText() + "\n๊ณต๋ถํ๋ ๋ฐฉ๋ฒ : ํฌ์คํธ์์ ๋ชฉํ ์จ๋๊ณ ๋๊ธฐ ๋ถ์ฌ\n");
break;
}
break;
case 2:
switch (n.getSelectitem()) {
case 0:
study.setText(study.getText() + "\n๊ณต๋ถ ์กฐ์ธ : ์ง๊ธ์ฒ๋ผ ์ด์ฌํ ๋
ธ๋ ฅํ์ธ์!\n");
break;
case 1:
study.setText(study.getText() + "\n๊ณต๋ถ ์กฐ์ธ : ์ข์ํ๋ ๋ถ์ผ๋ฅผ ๋จผ์ ์ฐพ์๋ณด์ธ์!\n");
break;
case 2:
study.setText(study.getText() + "\n๊ณต๋ถ ์กฐ์ธ : ์
๊ธฐ๋ ๋
ธ๋, ๋ฏธ์ ๋ฑ์ผ๋ก ๊ณต๋ถ๋ก ๋ฐ์ ์คํธ๋ ์ค๋ฅผ ํ์ด๋ณด์ธ์!\n");
break;
case 3:
study.setText(study.getText() + "\n๊ณต๋ถ ์กฐ์ธ : ํ์ต ์์ฃผ๋ก ๊ณต๋ถ ํด๋ณด์ธ์!\n");
break;
}
break;
}
break;
case 1://์ฌ๋ฆฌํ
์คํธ ์ฌ๋ฆฌ๋ฅผ ์ ํํ์ ๋
switch (n.getId()) {
case 0://๊ณต๋ถ ์ฌ๋ฆฌํ
์คํธ ์ค ์ฒ์ ์ฌ๋ฆฌํ
์คํธ ์ ํ
switch (n.getSelectitem()) {
case 0:
stress.setText(stress.getText() + "\n์คํธ๋ ์ค๋ฅผ ์ค์ด๋ ๋ฐฉ๋ฒ : ์คํด๊ฐ ์๊ธด๋ค๋ฉด ๋ฐ๋ก ํ์ด๋ณด๋ ค๊ณ ๋
ธ๋ ฅํด๋ณด์ธ์.\n");
break;
case 1:
stress.setText(stress.getText() + "\n์คํธ๋ ์ค๋ฅผ ์ค์ด๋ ๋ฐฉ๋ฒ : ์ฌ๋์ ๋น์ฐํ ์๋ก ๋ค๋ฅผ ์ ๋ฐ์ ์๋ค๋ ์ ์ ๋ช
์ฌํ๊ณ ์ดํดํ์ธ์.\n");
break;
case 2:
stress.setText(stress.getText() + "\n์คํธ๋ ์ค๋ฅผ ์ค์ด๋ ๋ฐฉ๋ฒ : ๋ชจ๋ ์ผ์ ์๋ฒฝํ ์ ์๋ค๋ ์ ์ ๊ธฐ์ตํ์ธ์.\n");
break;
case 3:
stress.setText(stress.getText() + "\n์คํธ๋ ์ค๋ฅผ ์ค์ด๋ ๋ฐฉ๋ฒ : ์์ ์ ์ทจํฅ์ ๋ง๋ ์๋ก์ด ๋ถ์ผ๋ฅผ ์ฐพ์์ ์ธ์์ ๋ฌด๋ฃํจ์ ์์ ๋ณด์ธ์.\n");
break;
case 4:
stress.setText(stress.getText() + "\n์คํธ๋ ์ค๋ฅผ ์ค์ด๋ ๋ฐฉ๋ฒ : ๋ชจ๋ ์ฌ๋์ด ์์ ์ ์ข์ํ ์ ์๋ค๋ ์ ์ ๊ธฐ์ตํ์ธ์.\n");
break;
}
break;
case 1:
switch (n.getSelectitem()) {
case 0:
stress.setText(stress.getText() + "\n๋ง์์ ๋ค์ค๋ฆฌ๋ ๋ฒ : ๋ค๋ฅธ ์ฌ๋์ด ๋ฐ๊ฒฌํ์ง ๋ชปํ ํํ์ง ์์ ๋ถ์ผ๋ฅผ ๊ณต๋ถํด๋ณด์ธ์.\n");
break;
case 1:
stress.setText(stress.getText() + "\n๋ง์์ ๋ค์ค๋ฆฌ๋ ๋ฒ : ์น๊ตฌ๋ค๊ณผ ํจ๊ป ๋ํ๋ฅผ ๋ง์ด ํด๋ณด์ธ์.\n");
break;
case 2:
stress.setText(stress.getText() + "\n๋ง์์ ๋ค์ค๋ฆฌ๋ ๋ฒ : ์ฃผ๊ด์ ์ด์ง ์๊ณ ๊ฐ๊ด์ ์ธ ํ๋จ์ ๋ด๋ ค๋ณด์ธ์.\n");
break;
case 3:
stress.setText(stress.getText() + "\n๋ง์์ ๋ค์ค๋ฆฌ๋ ๋ฒ : ํ๊ฐ ๋ ๋๋ ์ฃผ๋ณ์ฌ๋์ ์ค๋ํ์ฌ ๋ฌธ์ ๋ฅผ ํด๊ฒฐํด๋ณด์ธ์.\n");
break;
}
break;
case 2:
switch (n.getSelectitem()) {
case 0:
stress.setText(stress.getText() + "\n์ฑ๊ฒฉ์ ๋ง๋ ์์
: ํ์ก\n");
break;
case 1:
stress.setText(stress.getText() + "\n์ฑ๊ฒฉ์ ๋ง๋ ์์
: ํด๋์\n");
break;
case 2:
stress.setText(stress.getText() + "\n์ฑ๊ฒฉ์ ๋ง๋ ์์
: ์ฌ์ฆ\n");
break;
case 3:
stress.setText(stress.getText() + "\n์ฑ๊ฒฉ์ ๋ง๋ ์์
: ์ปจํธ๋ฆฌ ์์
\n");
break;
}
break;
}
break;
case 2://์ฌ๋ฆฌํ
์คํธ ์ฌ๋์ ์ ํํ์ ๋
switch (n.getId()) {
case 0://๊ณต๋ถ ์ฌ๋ฆฌํ
์คํธ ์ค ์ฒ์ ์ฌ๋ฆฌํ
์คํธ ์ ํ
switch (n.getSelectitem()) {
case 0:
love.setText(love.getText() + "\n๋์ ์ฐ์ ์คํ์ผ: ์น๊ตฌ๊ฐ์ ํธํ ์ฐ์ \n");
break;
case 1:
love.setText(love.getText() + "\n๋์ ์ฐ์ ์คํ์ผ : ํ์ค์ ์ด๊ณ ๊ณํ์ ์ธ ์ฐ์ \n");
break;
case 2:
love.setText(love.getText() + "\n๋์ ์ฐ์ ์คํ์ผ : ์ด์ ์ ์ด๊ณ ํ์ ์ ์ธ ์ฐ์ \n");
break;
case 3:
love.setText(love.getText() + "\n๋์ ์ฐ์ ์คํ์ผ : ์์ ์ ์ทจํฅ์ ๋ง๋ ์๋ก์ด ๋ถ์ผ๋ฅผ ์ฐพ์์ ์ธ์์ ๋ฌด๋ฃํจ์ ์์ ๋ณด์ธ์.\n");
break;
case 4:
love.setText(love.getText() + "\n๋์ ์ฐ์ ์คํ์ผ : ์์ํ์ง๋ง ์ฑ์ํ ์ฐ์ \n");
break;
}
break;
case 1:
switch (n.getSelectitem()) {
case 0:
love.setText(love.getText() + "\n์๋ง์ ๋ฐ์ดํธ ์ฅ์: ์ฝ์ํธ\n");
break;
case 1:
love.setText(love.getText() + "\n์๋ง์ ๋ฐ์ดํธ ์ฅ์: ๋ฒ๊ฝ ๋์ด\n");
break;
case 2:
love.setText(love.getText() + "\n์๋ง์ ๋ฐ์ดํธ ์ฅ์: ์นดํ\n");
break;
case 3:
love.setText(love.getText() + "\n์๋ง์ ๋ฐ์ดํธ ์ฅ์: ๋งํ๋ฐฉ\n");
break;
}
break;
case 2:
switch (n.getSelectitem()) {
case 0:
love.setText(love.getText() + "\n์ ์ธ๊ณผ ๊ฐ์ด ๋ณด๋ฉด ์ข์ ์ํ : ๋ก๋งจ์ค ์ํ\n");
break;
case 1:
love.setText(love.getText() + "\n์ ์ธ๊ณผ ๊ฐ์ด ๋ณด๋ฉด ์ข์ ์ํ : ๊ณตํฌ ์ํ\n");
break;
case 2:
love.setText(love.getText() + "\n์ ์ธ๊ณผ ๊ฐ์ด ๋ณด๋ฉด ์ข์ ์ํ : ์ฝ๋ฏธ๋ ์ํ\n");
break;
case 3:
love.setText(love.getText() + "\n์ ์ธ๊ณผ ๊ฐ์ด ๋ณด๋ฉด ์ข์ ์ํ : ์ด๋๋ฒ์ค ์ํ\n");
break;
}
break;
case 3:
switch (n.getSelectitem()) {
case 0:
love.setText(love.getText() + "\n๋น์ ์ ์ด์ํ : ์ง์งํ๊ณ ๊ผผ๊ผผํ ์ฐ์\n");
break;
case 1:
love.setText(love.getText() + "\n๋น์ ์ ์ด์ํ : ๋ง์ ์ํ๊ณ ๋งค๋๊ฐ ์ข์ ์ฌ๋\n");
break;
case 2:
love.setText(love.getText() + "\n๋น์ ์ ์ด์ํ : ์ด์ ์ ์ผ๋ก ์ฌ๋์ ํผ์ฃผ๋ ์ฌ๋\n");
break;
case 3:
love.setText(love.getText() + "\n๋น์ ์ ์ด์ํ : ์์ํ๊ณ ๋ฐ๋ปํ ๋ด๋ฉด์ ๊ฐ์ง ์ฌ๋\n");
break;
case 4:
love.setText(love.getText() + "\n๋น์ ์ ์ด์ํ : ์์ ์ ๋ณดํธํด์ฃผ๊ณ ๊ฐ์ธ์ฃผ๋ ์ฐํ\n");
break;
}
break;
}
break;
case 3://์ฌ๋ฆฌํ
์คํธ ์ธ๊ฐ๊ด๊ณ๋ฅผ ์ ํํ์ ๋
switch (n.getId()) {
case 0://๊ณต๋ถ ์ฌ๋ฆฌํ
์คํธ ์ค ์ฒ์ ์ฌ๋ฆฌํ
์คํธ ์ ํ
switch (n.getSelectitem()) {
case 0:
friend.setText(friend.getText() + "\n์น๊ตฌ๋ฅผ ์ฌ๊ท๋ ํ : ์นํด์ง๊ณ ์ถ์ ์น๊ตฌ๊ฐ ์๋ค๋ฉด ํ์คํ ๋ง์์ ํํํด์ฃผ์ธ์.\n");
break;
case 1:
friend.setText(friend.getText() + "\n์น๊ตฌ๋ฅผ ์ฌ๊ท๋ ํ : ์ซ์ ๋ด์์ ๊ฒ์ผ๋ก ๋๋ฌ๋ด์ง ์๊ณ ๋์ ํ ํ๋๋ฅผ ์ค์ด์ธ์.\n");
break;
case 2:
friend.setText(friend.getText() + "\n์น๊ตฌ๋ฅผ ์ฌ๊ท๋ ํ : ์ฉ๊ธฐ๋ฅผ ๋ด์ ์น๊ตฌ์๊ฒ ๋ค๊ฐ๊ฐ ๋ณด์ธ์.\n");
break;
}
break;
case 1:
switch (n.getSelectitem()) {
case 0:
friend.setText(friend.getText() + "\n๋น์ ์ด ์ก์์ผ ํ ์ฌ๋์ ํน์ง : ์ฌ์ํ ๊ฒ ํ๋๊น์ง๋ ์ ๊ฒฝ ์จ์ฃผ๋ ์ฌ๋\n");
break;
case 1:
friend.setText(friend.getText() + "\n๋น์ ์ด ์ก์์ผ ํ ์ฌ๋์ ํน์ง : ๋น์ ์ ์จ๊ฒจ์ง ๋ฉด๊น์ง ๋ฐ๊ฒฌํด์ฃผ๋ ์ฌ๋\n");
break;
case 2:
friend.setText(friend.getText() + "\n๋น์ ์ด ์ก์์ผ ํ ์ฌ๋์ ํน์ง : ๋น์ ๊ณผ ํจ๊ป ๋ชจ๋ ์ทจ๋ฏธ ํ๋์ ํจ๊ป ํด์ค ์ฌ๋\n");
break;
}
break;
case 2:
switch (n.getSelectitem()) {
case 0:
friend.setText(friend.getText() + "\n์น๊ตฌ๋ฅผ ์ ์งํ ์ ์๋ ํ : ๋น์ ์ ๋ด๋ฉด ์์ ์ด์ผ๊ธฐ๋ฅผ ํธ์ด๋์ ๊น์ํ ์ฌ์ด๋ฅผ ์ ์งํด ๋ณด์ธ์.\n");
break;
case 1:
friend.setText(friend.getText() + "\n์น๊ตฌ๋ฅผ ์ ์งํ ์ ์๋ ํ : ์คํด๊ฐ ์๊ธฐ๊ฑฐ๋ ์์ดํ ์ผ์ด ์๋ค๋ฉด ์์๋์ง ์๊ณ ๋ฐ๋ก ๋งํด๋ณด์ธ์!\n");
break;
case 2:
friend.setText(friend.getText() + "\n์น๊ตฌ๋ฅผ ์ ์งํ ์ ์๋ ํ : ๋น์ ์ด ์น๊ตฌ๋ฅผ ์๋ผ๋ ๋ง์์ ์น๊ตฌ์๊ฒ ํํํด ๋ณด์ธ์.\n");
break;
case 3:
friend.setText(friend.getText() + "\n์น๊ตฌ๋ฅผ ์ ์งํ ์ ์๋ ํ : ์น๊ตฌ๊ฐ ์ ํด๋ธ ์ผ์ด ์๋ค๋ฉด, ์งํฌ๊ฐ ์๋ ์ถํํ๋ค๋ ๋ฉ์ธ์ง๋ฅผ ์ ํด๋ณด์ธ์.\n");
break;
}
break;
}
break;
}
}
}
}
<file_sep>import tensorflow as tf
import tensorflow as tf
import matplotlib.pyplot as plt
import cv2
import os
import numpy as np
import time
model = tf.keras.models.load_model('./model/cat_dog.hdf5')
x_test = []
y_test = []
foldernames = os.listdir('../catdog/training_set/training_set')
for k, folder in enumerate(foldernames):
len = 0
for c, file in enumerate(os.listdir('../catdog/test_set/test_set' + '/' + folder)):
if c > 3:
len = c
break
img = cv2.imread('../catdog/test_set/test_set' + '/' + folder + '/' + file)
pp = plt.imread('../catdog/test_set/test_set' + '/' + folder + '/' + file)
img = cv2.resize(img, (224, 224))
img = img.reshape(224, 224, 3)
plt.imshow(pp)
print('a')
time.sleep(3)
x_test.append(img)
y_test += [k] * len
x_test = np.array(x_test)
y_test = np.array(y_test)
x_test = x_test / 255.0
loss, acc = model.evaluate(x_test, y_test, verbose=2)
print("๋ณต์๋ ๋ชจ๋ธ์ ์ ํ๋: {:5.2f}%".format(100*acc))<file_sep>package com.example.appprogrammingproject.database.model;
public class Note {
public static final String TABLE_NAME = "notes";
public static final String COLUMN_ID = "id"; // ๋ฌด์์ ์๊ณ ์ถ๋์
public static final String COLUMN_GROUPITEM = "groupitem"; // ๋ฌด์์ ํ
์คํธ ํด๋ณผ๊น์
public static final String COLUMN_TIMESTAMP = "timestamp";
public static final String COLUMN_SELECTITEM = "selectitem"; // ์ ํํ ๊ฒ
private int id;
private String timestamp;
public int getSelectitem() {
return selectitem;
}
private int selectitem = 0;
private int groupitem = 0;
public int getGroupitem() {
return groupitem;
}
public void setGroupitem(int groupitem) {
this.groupitem = groupitem;
}
public void setSelectitem(int selectitem) {
this.selectitem = selectitem;
}
// Create table SQL query
public static final String CREATE_TABLE =
"CREATE TABLE " + TABLE_NAME + "("
+ COLUMN_ID + " INTEGER,"
+ COLUMN_GROUPITEM + " INTEGER,"
+ COLUMN_SELECTITEM + " INTEGER,"
+ COLUMN_TIMESTAMP + " DATETIME DEFAULT CURRENT_TIMESTAMP"
+ ")";
public Note() {
}
public Note(int id, int groupitem, int selectitem, String timestamp) {
this.id = id; //๊ฐ ๋ถ์ผ์ ์ฌ๋ฆฌํ
์คํธ๋ค
this.groupitem = groupitem; //์ฌ๋ฆฌ ํ
์คํธ 4๊ฐ์ง ๋ถ์ผ
this.selectitem = selectitem; //์ฌ๋ฆฌํ
์คํธ ๊ฒฐ๊ณผ
this.timestamp = timestamp;
}
public int getId() {
return id;
}
public String getTimestamp() {
return timestamp;
}
public void setId(int id) {
this.id = id;
}
public void setTimestamp(String timestamp) {
this.timestamp = timestamp;
}
}
<file_sep>package com.example.appprogrammingproject;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import com.example.appprogrammingproject.database.DatabaseHelper;
import com.example.appprogrammingproject.database.model.Note;
import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import androidx.annotation.CheckResult;
import androidx.annotation.Nullable;
public class Friend extends Activity {
Button one, two, three, four;
long now = System.currentTimeMillis();
Date dateTime = new Date(now);
SimpleDateFormat simpleDate = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String getTime = simpleDate.format(dateTime);
private DatabaseHelper db;
private void createNote(int group, int id, int select) {
db.insertNote(id, group, select);
readData();
}
final int[] select = {0};
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.friend);
db = new DatabaseHelper(this);
List<Note> n = db.getAllNotes();
one = findViewById(R.id.one);
two = findViewById(R.id.two);
three = findViewById(R.id.three);
four = findViewById(R.id.four);
readData();
//๋ฒํผ์ ๋๋ ์๋ dialog ๋์ด ํ์ ์ฌ๋ฆฌํ
์คํธ ์งํ
one.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83C\uDF4A ๋ฒ ์ด์ง๋ ์ค๋ ์ง์ ๊ณ์ด", "\uD83C\uDF3A ํํฌ ๋๋ ๊ฝ๋ฌด๋ฌ", "\uD83D\uDC0B ๋ธ๋ฃจ, ๊ทธ๋ฆฐ ๊ณ์ด"};
final AlertDialog.Builder result = new AlertDialog.Builder(Friend.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Friend.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83D\uDD6F๏ธ ์ํ๋ณด๋ฅผ ๋ฐ๊พธ๋ ค๋ ๋น์ , ๋ฌด์จ ์์ผ๋ก ๋ฐ๊ฟ๊น?").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0] = i;//์ ํํ ๊ฒ์ select์ ๋ฃ์ด์ค
if (i == 0) {
result.setTitle("\uD83C\uDF4A ๋ฒ ์ด์ง๋ ์ค๋ ์ง์ ๊ณ์ด");
result.setMessage("์ด๋ค ์ฌ๋์ด๋ผ๋ ์น๊ตฌ๊ฐ ๋ ์ค๋น๊ฐ ๋์ด์๋ค์. ๋น์ ์ ์ด๋ค ์ฌ๋์ด๋ผ๋" +
"์๋นํ ๊ด์ฉ์ ์ผ๋ก ๋ฐ์๋ค์ผ ์ ์๋ ์ฌ๋์
๋๋ค. ํ์ง๋ง ๊ทธ๋ฐ ํ๋๊ฐ ์ฃผ์์์ ๋ณด๋ฉด" +
"'์๋ฌด์๊ฒ๋ ์ํ๋ ์ฌ๋'์ผ๋ก ๋ณด์ฌ์ง ์๋ ์์ผ๋ ํ์คํ ํ๋๊ฐ ํ์ํด์!");
} else if (i == 1) {
result.setTitle("\uD83C\uDF3A ํํฌ ๋๋ ๊ฝ๋ฌด๋ฌ");
result.setMessage("์ข๊ณ ์ซ์์ด ๋๋ ทํ์ฌ ์ฌ๋์ ๋ํ๋ ํ๋์๋ ํฌ๊ฒ ์ฐจ์ด๊ฐ ๋๋ ํ์
์
๋๋ค." +
"์ข์ํ๋ ์ฌ๋์๊ฒ๋ ๋จผ์ ๋ค๊ฐ๊ฐ ๊ฐ๋์ ์ฃผ์ง๋ง, ์ซ์ดํ๋ ์ฌ๋์๊ฒ๋ ๋์ ํ ํ๋๋ฅผ ํฐ๊ฐ๋๊ฒ ์ทจํ๋ค์." +
"์ ์ด๋ ์ซ์ ๋ด์์ ๊ฒ์ผ๋ก ๋๋ฌ๋ด์ง ์๋ ํ๋๋ ํ์ํ ๋ฏ ์ถ๋ค์.");
} else if (i == 2) {
result.setTitle("\uD83D\uDC0B ๋ธ๋ฃจ, ๊ทธ๋ฆฐ ๊ณ์ด");
result.setMessage("์ค์ค๋ก ๊ด๊ณ๋ฅผ ํผํด๋ฒ๋ฆฌ๋ ํ์
! ๋น์ ์ ์ฌ๋์ ๋ง๋๊ธฐ ๋๋ ค์ํ๋ค์." +
"๊ฐ๋์ ์ฉ๊ธฐ๋ฅผ ๋ด์ ๋จผ์ ๋ค๊ฐ๊ฐ๋ณด์ธ์!");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote(3, 0, select[0]);
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
two.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83D\uDC48 ์ผ์ชฝ ์๋ฆฌ", "\uD83C\uDF1F ๊ฐ์ด๋ฐ ์๋ฆฌ", "\uD83D\uDC49 ์ค๋ฅธ์ชฝ ์๋ฆฌ"};
final AlertDialog.Builder result = new AlertDialog.Builder(Friend.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Friend.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83C\uDF78 ์๋น์ ํผ์ ๊ฐ ๋น์ , ์ด๋์ ์์ผ์๊ฒ ์ต๋๊น?").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0] = i;
if (i == 0) {
result.setTitle("\uD83D\uDC48 ์ผ์ชฝ์๋ฆฌ๋ฅผ ์ ํํ์
จ๋ค์!");
result.setMessage("๋ชจ๋ ์ฌ๋์๊ฒ ์น์ ์ ๋ฒ ํธ๋ ๋น์ ์ ๋์ธ๊ด๊ณ๋ ๊ณ์ ํ์ฅ ์ค!" +
"์์ ์ธ์ฐ๊น์ง ๋ชจ๋ ์์คํ๊ฒ ์ฌ๊ธฐ๊ธฐ ๋๋ฌธ์ ๋ง์ฃผ์น๋ ์ฌ๋์๊ฒ ์๋ฅํ ์ธ์ฌ๋ ๊ธฐ๋ณธ! " +
"ํญ์ ๋จผ์ ๋ค๊ฐ๊ฐ๋ค๋ ์ธ์์ ์ฃผ๊ณ ์์ต๋๋ค. ์๋๋ฐฉ ๋ํ ๋น์ ์๊ฒ ํธ๊ฐ์ ๋๋ผ๊ธฐ ๋๋ฌธ์ ์๊ฐ์ด ์ง๋ ์๋ก ์น๊ทผ๊ฐ์ ๊ฐ๊ฒ ๋ฉ๋๋ค!" +
"์ด๋ฐ ๊ณผ์ ์ ๊ฑฐ์ณ ๋น์ ์ ์ธ๋งฅ์ ์๊ฐ์ด ์ง๋ ์๋ก ๋์ด์ง๊ฒ ๋ฉ๋๋ค. ์ ๊ตญ ํ๋ ์๋, ์ ์ธ๊ณ ์ฌ๋๊ณผ ๋ชจ๋ ์น๊ตฌ๊ฐ ๋ ์ ์๋ ๊ฐ๋ฅ์ฑ์ ์ง๋๊ณ ์๋ค์!!");
} else if (i == 1) {
result.setTitle("\uD83C\uDF1F ๊ฐ์ด๋ฐ ์๋ฆฌ๋ฅผ ์ ํํ์
จ๋ค์!");
result.setMessage("์ง๊ธ ๋ด ์ฌ๋์๊ฒ ์ต์ ์ ๋คํ๋ ๋น์ ์ ๋์ธ๊ด๊ณ๋ ์ง์คํ!" +
"์ง๊ธ๊น์ง ๋ด ์์ ์์ด์ฃผ๊ณ ํจ๊ป ํด ์จ ์ฌ๋๋ค์ ๋ํ ์๋ฆฌ๊ฐ ๋งค์ฐ ๊น์ผ๋ฉฐ ์ด ์ฐ์ ๊ณผ ์ฌ๋์ ํ์ ๊ฐ์งํ๊ธธ ์ํ๊ณ ์์ต๋๋ค. " +
"์๋ก์ด ๊ฒ๋ณด๋ค๋ ์ต์ํ ๊ฒ์ ๋ ์ข์ํ๋ ์ฑํฅ์ด ์๋ ํธ์ด๋ค์" +
"์๊ฐ์ด ์ง๋จ์ ๋ฐ๋ผ ์ฌ๋ฌ ์ฌ๋์ ๋ง๋๊ฒ ๋์ง๋ง, ๊ฐ์ ์๋ 100% ๋ฆฌ์ผํ๊ฒ ํธํ ์๋๋ฅผ ๋ง๋๊ธฐ๋ ์ฝ์ง ์์ฃ ! " +
"ํ ๋ฒ ๋งบ์ ์ธ์ฐ์ ํ์ ๊ฐ์งํ๋ ์์ ํ, ์๋ฆฌํ์
๋๋ค!!");
} else if (i == 2) {
result.setTitle("\uD83D\uDC49 ์ค๋ฅธ์ชฝ ์๋ฆฐ๋ฅผ ์ ํํ๋ค์!");
result.setMessage("๋ณต์กํ๊ฒ ์ฝํ๊ณ ์ฅํ๋ ๊ฒ์ ์ซ์ดํ๋ ๋น์ ์ ๋์ธ๊ด๊ณ๋ ์์ ํ! " +
"๊ฐ๋ฉ์ด๋ ๋ณต์กํ ์ธ์ ์ธ๊ฐ๊ด๊ณ๊น์ง ๋ณต์กํ๊ฒ ์๊ฐํ๊ธฐ๋ฅผ ๊ฑฐ๋ถํ๋ ์์ ๋ก์ด ์ํผ์ ์์ ์! " +
"์ง์ฐฉ๋ณด๋ค๋ ํ์ฌ์ ๊ธฐ๋ถ๊ณผ ์ํฉ์ ์ฐ์ ์ํ๋ ์ฑํฅ์ผ๋ก ์์ธก ๋ถ๊ฐ๋ฅํ ํตํต ํ๋ ๋งค๋ ฅ์ ๊ฐ์ง๊ณ ์๋ค์" +
"์ฟจํ ์ฑ๊ฒฉ ํ์ ๊ฐ์์ด ์์ผ๋ฉฐ ์ข๊ณ ์ซ์ ๊ฒ์ ํํํ๋ ๋ฐ ์ต์ํฉ๋๋ค! ์คํ๋ ค ์ด๋ฐ ์์ ๋ก์ด ๋ถ์๊ธฐ์ ์ด๋๋ ค " +
"๋น์ ์ ์ฐพ๋ ์ฌ๋๋ค์ด ์ฃผ๋ณ์ ๋งค์ฐ ๋ง์ ๊ฐ๋ฅ์ฑ์ด ๋์ ๋ณด์ด๋ค์!!");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote(3, 1, select[0]);
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
three.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
final String[] item = new String[]{"\uD83D\uDD90 ์์๊ฑด", "\uD83D\uDC96 ๋ด๊ฐ ์ข์ํ๋ ๊ฒ", "\uD83E\uDD57 ๋ด๊ฐ ์ง์ ๋ง๋ ๊ฒ", "\uD83C\uDF1F ์์ฆ ์ธ๊ธฐ์๋ ๋ฌผ๊ฑด"};
final AlertDialog.Builder result = new AlertDialog.Builder(Friend.this);
final AlertDialog.Builder a = new AlertDialog.Builder(Friend.this);
result.setPositiveButton("ํ์ผ๋ก ๋์๊ฐ๊ธฐ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
final Intent main = new Intent(getApplicationContext(), MainActivity.class);
startActivity(main);
finish();
}
});
result.setNegativeButton("๊ณ์ ํ๊ธฐ", null);
a.setTitle("\uD83C\uDF81 ๋น์ ์ ์นํ ์น๊ตฌ์๊ฒ ์ด๋ค ์ ๋ฌผ์ ์ค๊ฑด๊ฐ์?").setSingleChoiceItems(item, -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
select[0] = i;
if (i == 0) {
result.setTitle("\uD83D\uDD90 ์์๊ฑด");
result.setMessage("๋น์ ์ ์น๊ตฌ์ ๋ถ๋ช
ํ ๊ณผ๊ณ๋ฅผ ๋งบ๋ ์คํ์ผ์ ์๋๋ค์. " +
"์ฃผ๋ณ์ ์ฌ๋์ด ๋ง๊ธฐ๋ ํ์ง๋ง ์น๊ตฌ๋ผ ํ๊ธฐ์ ์ ๋งคํ ๊ด๊ณ๊ฐ ๋ง์ต๋๋ค. " +
"์ง์ ํ ์น๊ตฌ๊ฐ ์๋ค๊ณ ๋๊ปด ๋ถํํ๊ธฐ๋ ํ์ง๋ง ์ธ๋ก์์ ์ ํ์ง ์๋ ํ์
์ด๋ค์.");
} else if (i == 1) {
result.setTitle("\uD83D\uDC96 ๋ด๊ฐ ์ข์ํ๋ ๊ฒ");
result.setMessage("๋น์ ์ ์น๊ตฌ๋ฅผ ๊ฐ๋ ค์ ์ฌ๊ท๋ ํธ์ด์ง๋ง ๊ฒฐ์ฝ ๋ชจ๋ ์ข์ ์น๊ตฌ๋ ์๋๋๋ค." +
"์ธ์์ ๋๋ฅผ ์ค์ฌ์ผ๋ก ์์ง์ธ๋ค๊ณ ์๊ฐํ์ฌ ์์ ์ด ๋ง์์ ๋ค์ง ์์ผ๋ฉด ์ฝ๊ฒ ๊ด๊ณ๋ฅผ ๋์ด๋ฒ๋ฆฝ๋๋ค. " +
"๊ทธ๋ ๊ธฐ ๋๋ฌธ์ ๋น์ ์ด ์ํ๋ ์น๊ตฌ๊ด๊ณ๋ฅผ ์ด๋ฃจ๋ ๊ฒ์ ์ฝ์ง ์์ ๊ฒ ๊ฐ๋ค์. ");
} else if (i == 2) {
result.setTitle("\uD83E\uDD57 ๋ด๊ฐ ์ง์ ๋ง๋ ๊ฒ");
result.setMessage("๋น์ ์ ํ์ธ์๊ฒ ํผํด๋ฅผ ์ฃผ์ง ์์ผ๋ ค๊ณ ๋ฐฐ๋ ค์ฌ์ด ๊น์ ํ๋๋ค์ ๋ณด์ฌ์ฃผ๋ค์." +
"๊ธฐ๋ณธ์ ์ผ๋ก ๋น์ ์ ์ฐ์ ์ ์ค์์ ์ฌ๊ฒจ ์ข์ ์น๊ตฌ๊ด๊ณ๋ฅผ ์ ์งํ๊ณ ์๋ค์.");
} else if (i == 3) {
result.setTitle("\uD83C\uDF1F ์์ฆ ์ธ๊ธฐ์๋ ๋ฌผ๊ฑด");
result.setMessage("๋น์ ์ ๋น์ ์ ๋๋ณด์ด๊ฒ ํ ์ ์๋ ์น๊ตฌ๋ฅผ ์ฌ๊ท๋ ํธ์ด๊ตฐ์." +
"๊ฐํน๊ฐ๋ค ์น๊ตฌ๋ฅผ ์งํฌํ๊ธฐ๋ ํ๊ณ ์. ๋ฌผ๋ก ๋น์ฐํ ํ์์ด์ง๋ง, ์กฐ๊ธ ๋ " +
"๊ฐ๊น์ด์์ ์ข์ ์น๊ตฌ๋ฅผ ์ฌ๊ท์ด ๋ณด๋๊ฑด ์ด๋จ๊น์?");
}
}
});
a.setPositiveButton("ํ์ธ", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
createNote(3, 2, select[0]);
result.show();
}
});
a.setNegativeButton("์ทจ์", null);
a.show();
}
});
}
private void readData() {
List<Note> notes = db.getGroupNotes(3);
for (Note n : notes) {
String date = n.getTimestamp();
int select = n.getSelectitem();
Button btn = null;
Intent intent=new Intent(getApplicationContext(),Recommend.class);
intent.putExtra("select","select");
switch (n.getId()) {
case 0:
btn = one;
one.setText("1. \uD83D\uDE0A ๋์ ์ธ๊ฐ๊ด๊ณ" + "\n(ํ
์คํธํ ๋ ์ง: " + date + ")"); //๋ฒํผ์ ํ
์คํธ์ ํ
์คํธํ ๋ ์ง๋ฅผ ๋ค์ ์ถ๊ฐ.
break;
case 1:
btn = two;
two.setText("2. \uD83D\uDC6A ๋ด๊ฐ ์ํด์๋ ๋์ธ๊ด๊ณ ์ ํ " + "\n(ํ
์คํธํ ๋ ์ง: " + date + ")");
break;
case 2:
btn = three;
three.setText("3. \uD83D\uDE4B ๋ด๊ฐ ์ธ๊ฐ๊ด๊ณ๋ฅผ ๋ง๋ค์ด๊ฐ๋ ๋ฐฉ๋ฒ" + "\n(ํ
์คํธํ ๋ ์ง: " + date + ")");
break;
}
try {
btn.setBackgroundColor(Color.GRAY); //์ด๋ฏธ ๋๋ธ ์ฌ๋ฆฌํ
์คํธ๋ ๋ฐฐ๊ฒฝ์ ํ์๊ณผ ํฐํธ๋ ํฐ์์ผ๋ก ๋ฐ๊ฟ.
btn.setTextColor(Color.WHITE);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}<file_sep># ์ก๋คํ ํ
์คํธ ๊ธฐ๊ณ
## Contributor
[111111022](https://github.com/111111022) ์ฌ๋ฆฌํ
์คํธ ์ ์
[SHSongs](https://github.com/SHSongs) AI ๋ชจ๋ธ ์ ์
## App Summary
๊ฐ๋จํ ์ฌ๋ฆฌ ํ
์คํธ์ AI๋ฅผ ํ์ฉํ Image Classification
## Flow chart

## ๋ด๋ถ ์ฌ์ง





<file_sep>import tensorflow as tf
import os
import cv2
import numpy as np
img = cv2.imread('../catdog/training_set/training_set/dogs/dog.17.jpg')
img = cv2.resize(img, (224, 224))
img = img.reshape(1,224,224,3)
x_test = []
foldernames = os.listdir('../catdog/test_set/test_set')
for k, folder in enumerate(foldernames):
for c, file in enumerate(os.listdir('../catdog/test_set/test_set' + '/' + folder)):
if c >= 1:
break
print(file)
img = cv2.imread('../catdog/test_set/test_set' + '/' + folder + '/' + file)
img = cv2.resize(img, (224, 224))
img = img.reshape(224, 224, 3)
x_test.append(img)
x_test = np.array(x_test)
model = tf.keras.models.load_model('./model/cat_dog.hdf5')
model.save('./model/t_cat_dog')
converter = tf.lite.TFLiteConverter.from_saved_model('./model/t_cat_dog')
tflite_model = converter.convert()
open("./liteModel/t_cat_dog.tflite", "wb").write(tflite_model)
result = model.predict(x_test)
print(result)
<file_sep>import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.layers.Convolution2D(filters=64, kernel_size=(3, 3),
padding='same', activation='relu', input_shape=(224, 224, 3)),
tf.keras.layers.Convolution2D(filters=64, kernel_size=(3, 3), activation='relu', strides=(2, 2)),
tf.keras.layers.Convolution2D(filters=64, kernel_size=(3, 3), activation='relu', strides=(2, 2)),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
strides=(1, 1), padding='valid'),
tf.keras.layers.Convolution2D(filters=128, kernel_size=(3, 3), activation='relu', strides=(2, 2)),
tf.keras.layers.Convolution2D(filters=128, kernel_size=(3, 3), activation='relu', strides=(2, 2)),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
strides=(1, 1), padding='valid'),
tf.keras.layers.Convolution2D(filters=256, kernel_size=(3, 3), activation='relu'),
tf.keras.layers.Convolution2D(filters=256, kernel_size=(3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
strides=(1, 1), padding='valid'),
tf.keras.layers.Convolution2D(filters=512, kernel_size=(3, 3), activation='relu'),
tf.keras.layers.Convolution2D(filters=512, kernel_size=(3, 3), activation='relu'),
tf.keras.layers.MaxPooling2D(pool_size=(2, 2),
strides=(1, 1), padding='valid'),
tf.keras.layers.Flatten(),
tf.keras.layers.Dense(100, activation='relu'),
tf.keras.layers.Dense(2, activation='softmax')
])
print(model.summary())<file_sep>rootProject.name='AppProgrammingProject'
include ':app'
|
fb0e26c6fedfd80dbcea708f68e6ca2c1435be4e
|
[
"Markdown",
"Java",
"Python",
"Gradle"
] | 13 |
Java
|
SHSongs/AiAnimalApp
|
db1e7ec6db66114b10b83c98f645b0606e9e778a
|
e184b6a8d0587d794bcafbe10efd7766c85453ba
|
refs/heads/master
|
<repo_name>YWONG018/LastStable<file_sep>/ionic/src/app/apiurls/serverurls.js
//AWS - Public DNS
//export const apiKey = 'http://18.222.185.105/'
// export const apiKey = 'http://18.222.91.54/'
// export const apiKey = 'http://18.217.37.143/'
// export const apiKey = 'http://3.1.204.22/'
// export const apiKey = 'http://18.136.196.234/'
export const apiKey = 'http://54.169.214.70/'
//Huawei Router IPv4 address
// export const apiKey = 'http://192.168.8.100:8000/'
// export const apiKey = 'http://192.168.8.101:8000/'
// export const apiKey = 'http://192.168.8.102:8000/'
// export const apiKey = 'http://192.168.1.50:8000/'
// export const apiKey = 'http://192.168.1.31:8000/'
//Company Internet Line
// export const apiKey = 'http://10.178.26.216:8000/'
//Singtel Mobile Device
// export const apiKey = 'http://192.168.43.188:8000/'<file_sep>/ionic/src/app/app.component.ts
import { Component,ViewChild } from '@angular/core';
import { Platform, Nav, MenuClose, LoadingController } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AuthProvider } from '../providers/auth/auth';
import { TabsPage } from '../pages/tabs/tabs';
import { OperatorstabsPage } from '../pages/operatorstabs/operatorstabs'
import { LoginPage } from '../pages/login/login';
import { TranslateService } from '@ngx-translate/core';
import { KakaoCordovaSDK, AuthTypes } from 'kakao-sdk';
import { ProfilePage } from '../pages/profile/profile';
import { Storage } from '@ionic/storage';
import { HomePage } from '../pages/home/home';
import { AppProvider } from '../providers/app/app';
export interface PageInterface {
title:string;
pageName: any;
pageComponent?: any;
icon: string;
index?: number;
}
@Component({
templateUrl: 'app.html'
})
export class MyApp {
rootPage:any ; //rootPage will link to app.html file. this means everything of no specific page.
@ViewChild(Nav) nav: Nav;
toggleButton: boolean = false;
show: boolean = true;
pages:PageInterface[] = [
{title: 'Profile', pageName: ProfilePage, icon: 'person'}
]
access_token: string;
Role: any = 1;
loading: any;
constructor(platform: Platform,
statusBar: StatusBar,
public authService: AuthProvider,
public appprov: AppProvider,
splashScreen: SplashScreen,
private menu: MenuClose,
private storage: Storage,
public kakao: KakaoCordovaSDK,
private _translate : TranslateService) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
this._initTranslate();
});
this.authService.checkAuthentication().then((res)=>{
console.log("res:" + res);
if(res === ''){
this.pages;
this.rootPage = LoginPage;
}
else{
this.rootPage = TabsPage;
}
});
storage.ready().then(() => {
storage.get('access_token').then((val) => {
this.access_token = val.toString();
this.appprov.checkRole(this.access_token).then((res) => {
let data = JSON.stringify(res);
data = JSON.parse(data);
// this.loading.dismiss();
if (data['result'] == "1") {
this.Role = 1;
}
else if (data['result'] == "0") {
this.Role = 0;
}
else {
console.log("Not in database");
}
}, err => {
console.log(err);
});
// this.loading.dismiss();
});
});
}
/* EDIT HERE TO DO TRANSLATION */
private _initTranslate(){
//this._translate.setDefaultLang('kr');
this._translate.setDefaultLang('en');
// if (this._translate.getBrowserLang() !== undefined){
// this._translate.use(this._translate.getBrowserLang());
// }
// else{
// this._translate.use('en');
// }
}
openPage(page: PageInterface){
// let params = {};
// if(page.index){
// params = {tabIndex: page.index};
// }
// if(this.nav.getActiveChildNav() && page.index != undefined){
// this.nav.getActiveChildNav().select(page.index);
// }
// else {
// this.nav.setRoot(page.pageName, params);
// this.nav.setRoot(page.pageName);
// this.nav.push(page.pageName, {toggled: this.toggleButton});
this.nav.setRoot(page.pageName, {toggled: this.toggleButton});
// }
}
checkRole_() {
if(this.Role == 1) {
this.toggleProfile();
}
else {
return;
}
}
toggleProfile(){
if(this.toggleButton == true){
this.nav.setRoot(OperatorstabsPage);
this.menu.close();
}
else{
this.nav.setRoot(TabsPage);
this.menu.close();
}
}
}
<file_sep>/ionic/src/pages/profile/profile.ts
import { Component, ViewChild } from '@angular/core';
import { NavController, AlertController, NavParams, Tab, LoadingController, ViewController } from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { LoginPage } from '../login/login';
import { Http } from '@angular/http';
import { AuthProvider } from '../../providers/auth/auth';
import { AppProvider } from '../../providers/app/app';
import { Storage } from '@ionic/storage';
import { Chart } from 'chart.js';
import { KakaoCordovaSDK, AuthTypes } from 'kakao-sdk';
import { TranslateService } from '@ngx-translate/core';
import { HomePage } from '../home/home';
import { OperatorstabsPage } from '../operatorstabs/operatorstabs';
import { MyApp } from '../../app/app.component';
// import { Component, ViewChild } from '@angular/core';
// import { NavController, AlertController, NavParams, Tab } from 'ionic-angular';
// import { TabsPage } from '../tabs/tabs';
// import { LoginPage } from '../login/login';
/**
* Generated class for the ProfilePage page.
*
* See https://ionicframework.com/docs/components/#navigation for more info on
* Ionic pages and navigation.
*/
@Component({
selector: 'page-profile',
templateUrl: 'profile.html',
})
export class ProfilePage {
public title: string;
public welcome: string;
public forecast: string;
public fleet: string;
public jobstats: string;
public companyName: string;
public companyAdd: string;
public email: string;
public phone_no: string;
public language: string;
public result: any;
public userinfo:any;
public Uname: any;
public Udob: any;
public Uemail:any;
public uimg:any;
public Ucompany: any;
public Ucompanyadd: any;
public Unum: any;
profile: any;
private access_token:string;
loading: any;
Role: any;
toggled: any;
constructor(public navCtrl: NavController,
public http: Http,
public authService:AuthProvider,
public alertCtrl:AlertController,
private view: ViewController,
public navParams:NavParams,
public loadingCtrl: LoadingController,
public appprov:AppProvider,
private storage: Storage,
public kakao: KakaoCordovaSDK,
public _translate: TranslateService) {
this.toggled = navParams.data.toggled;
storage.ready().then(() => {
storage.get('access_token').then((val) => {
this.access_token = val.toString();
this.getUserInfo();
this._initializeTranslation();
this.appprov.checkRole(this.access_token).then((res) => {
let data = JSON.stringify(res);
data = JSON.parse(data);
// this.loading.dismiss();
if (data['result'] == "1") {
this.Role = 1;
}
else if (data['result'] == "0") {
this.Role = 0;
}
else {
console.log("Not in database");
}
}, err => {
console.log(err);
});
});// end of storage.get('access_token').then((val)
});//end of storage.ready().then(()
}// constructor
/*app starts here. meaning all the id, translation, user info, job info, vehicle info, and all the info etc
All are functions
*/
ionViewDidEnter(){
// this.getUserInfo();
this._initializeTranslation();
}
ionViewDidLoad(){
this._initializeTranslation();
}
public changeLanguage(): void{
this._translateLanguage();
}
private _translateLanguage() : void{
// this._translate.use(this.language);
this._translate.setDefaultLang(this.language);
this._initializeTranslation();
}
private _initializeTranslation(): void{
setTimeout(()=>{
this.title = this._translate.instant("home.title");
this.welcome = this._translate.instant("home.welcome");
this.forecast = this._translate.instant("home.forecast");
this.fleet = this._translate.instant("home.fleet");
this.jobstats = this._translate.instant("home.jobstats");
}, 200);
// this.title = this._translate.instant("home.title");
// this.title = this._translate.instant("profile.title");
// this.companyName = this._translate.instant("profile.companyName");
// this.companyAdd = this._translate.instant("profile.companyAdd");
// this.email = this._translate.instant("profile.email");
// this.phone_no = this._translate.instant("profile.phone_no");
}
popToHome(){
if(this.Role == 1 && this.toggled == true) {
this.navCtrl.push(OperatorstabsPage);
}
else if(this.Role ==1 && this.toggled == false) {
this.navCtrl.push(TabsPage)
}
else {
this.navCtrl.push(OperatorstabsPage);
}
}
getUserInfo(){
this.authService.getUserinfo(this.access_token).then((result) => {
this.userinfo = result;
this.userinfo = JSON.parse(this.userinfo._body);
this.Uemail = this.userinfo.email;
this.Udob = this.userinfo.dob;
this.Uname = this.userinfo.name;
this.uimg = this.userinfo.profile_image_url;
this.Ucompany = this.userinfo.company_name;
this.Ucompanyadd = this.userinfo.company_add;
this.Unum = this.userinfo.phone_no;
this.appprov.setemail(this.userinfo.email);
}, (err) => {
console.log(err);
});
}
}//ProfilePage
|
3502ffd37b47374d80dd9b60f52c422b3bd735a6
|
[
"JavaScript",
"TypeScript"
] | 3 |
JavaScript
|
YWONG018/LastStable
|
af556e91db41fc2b7d06a5ee6ea640426b2aafd3
|
f43239f869a6896961e7e1aca88b84cbd92635ed
|
refs/heads/master
|
<repo_name>IvanBreslauer/GpsTransposer<file_sep>/GPSTransposer/GPSTransposer.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Jil;
using IvanB.GPSTransposer.Models;
namespace IvanB.GPSTransposer
{
public class GPSTransposer
{
#region Properties
/// <summary> List of GPS points extracted from a .GPX file or other similar source of GPS data </summary>
public static List<GpsPoint> GpsPoints { get; set; }
/// <summary> List of transposed points expressed in pixels (for computer graphic coordinate system usage) </summary>
private static List<ImgPoint> _imgPoints = new List<ImgPoint>();
/// <summary> Transposer parameters </summary>
public static TransposerParams _params;
// Helper fields
private static double _maxLng; // Max longitude
private static double _maxLat; // Max latitude
private static double? _maxElev; // Highest elevation point
private static double? _minElev; // Lowest elevation point
private static double _scalingFactorX; // Coefficient for horizontal scaling of the route
private static double _scalingFactorY; // Coefficient for vertical scaling of the route
private static double _offsetX; // Offset for correct positioning of the starting point of the route (X)
private static double _offsetY; // Offset for correct positioning of the starting point of the route (Y)
//
#endregion
#region Factory methods
/// <summary>
/// Parses .GPX file content and transposes it using provided calibration parameters.
/// </summary>
/// <param name="p">Calibration parameters used for transposing the points.</param>
/// <param name="gpxFileContent">The string content of a .GPX file.</param>
/// <returns>List of point objects.</returns>
public static List<ImgPoint> TransposeToList(TransposerParams p, string gpxFileContent)
{
GpsPoints = Deserializer.ToGpsList(gpxFileContent);
return Transpose(p, GpsPoints);
}
/// <summary>
/// Parses .GPX file content and transposes it using provided calibration parameters.
/// </summary>
/// <param name="p">Calibration parameters used for transposing the points.</param>
/// <param name="gpxFileContent">The string content of a .GPX file.</param>
/// <returns>List of point objects as a JSON string.</returns>
public static string TransposeToJSON(TransposerParams p, string gpxFileContent)
{
GpsPoints = Deserializer.ToGpsList(gpxFileContent);
Transpose(p, GpsPoints);
return JSON.Serialize<List<ImgPoint>>(_imgPoints);
}
private static List<ImgPoint> Transpose(TransposerParams p, List<GpsPoint> pts)
{
_params = p;
if (pts.Count > 0)
{
_maxLng = pts.Min(pl => pl.Lon);
_maxLat = pts.Max(pl => pl.Lat);
CalculateFactorAndOffset();
PointDistanceOptimization();
}
return _imgPoints;
}
#endregion
#region Helper methods
/// <summary>
/// Calculates the scaling factor of a route as well as x/y offset for correct points positioning
/// </summary>
private static void CalculateFactorAndOffset()
{
GpsPoint firstGpsPoint = new GpsPoint(_params.GpsStartPoint.Lon, _params.GpsStartPoint.Lat, null);
firstGpsPoint = TransposePoint(firstGpsPoint);
GpsPoint lastGpsPoint = new GpsPoint (_params.GpsEndPoint.Lon, _params.GpsEndPoint.Lat, null);
lastGpsPoint = TransposePoint(lastGpsPoint);
_scalingFactorX = Math.Abs(_params.ImgStartPoint.X - _params.ImgEndPoint.X) / Math.Abs(firstGpsPoint.Lon - lastGpsPoint.Lon);
_scalingFactorY = Math.Abs(_params.ImgStartPoint.Y - _params.ImgEndPoint.Y) / Math.Abs(firstGpsPoint.Lat - lastGpsPoint.Lat);
firstGpsPoint = DislocatePointByFactor(firstGpsPoint);
_offsetX = _params.ImgStartPoint.X > firstGpsPoint.Lon ? _params.ImgStartPoint.X - firstGpsPoint.Lon : firstGpsPoint.Lon - _params.ImgStartPoint.X;
_offsetY = _params.ImgStartPoint.Y > firstGpsPoint.Lat ? _params.ImgStartPoint.Y - firstGpsPoint.Lat : firstGpsPoint.Lat - _params.ImgStartPoint.Y;
}
/// <summary>
/// Transposes a GPS point into a coordinate system point
/// </summary>
/// <param name="point">GPS point</param>
/// <returns>Transposed point for coordinate system</returns>
private static GpsPoint TransposePoint(GpsPoint point)
{
double factorX = _maxLng < 0 ? Math.Abs(_maxLng) : _maxLng * -1;
double factorY = _maxLat < 0 ? Math.Abs(_maxLat) : _maxLat * -1;
point.Lon += factorX;
point.Lat = Math.Abs(point.Lat + factorY);
return point;
}
// pomnoลพi koordinate toฤke s koeficijentom za ispravnu veliฤinu rute (scaling)
/// <summary>
/// Corrects the position of the point by a calculated offset
/// </summary>
/// <param name="point">Input point</param>
/// <returns>Correctly positioned point after offset is applied</returns>
private static GpsPoint DislocatePointByFactor(GpsPoint point)
{
point.Lon *= _scalingFactorX;
point.Lat *= _scalingFactorY;
return point;
}
/// <summary>
/// Optimizes the distance between points so that too dense and too sparse areas of points are evened-out.
/// </summary>
private static void PointDistanceOptimization()
{
GpsPoint lastPushed = new GpsPoint();
GpsPoint current = new GpsPoint();
for(int i = 0; i < GpsPoints.Count; i++)
{
current = TransposePoint(GpsPoints[i]);
current = DislocatePointByFactor(current);
current.Lon = Math.Abs(current.Lon) + _offsetX;
current.Lat = Math.Abs(current.Lat) + _offsetY;
// check if this is the last point of the list to optimize, if yes then add it and break the loop
if (Math.Sqrt(Math.Pow(current.Lon - _params.ImgEndPoint.X, 2) + Math.Pow(current.Lat - _params.ImgEndPoint.Y, 2)) < _params.StepLength / 1000)
{
if (i == GpsPoints.Count - 1)
{
current.Lon = _params.ImgEndPoint.X;
current.Lat = _params.ImgEndPoint.Y;
_imgPoints.Add(new ImgPoint(current.Lon, current.Lat, current.Elev));
break;
}
}
if (i == 0)
{
lastPushed = current;
_imgPoints.Add(new ImgPoint(lastPushed.Lon, lastPushed.Lat, lastPushed.Elev));
}
else
{
double distPx = Math.Sqrt(Math.Pow(current.Lon - lastPushed.Lon, 2) + Math.Pow(current.Lat - lastPushed.Lat, 2)); // distance between the current and the preceeding point
double angle = Math.Acos(Math.Abs(current.Lon - lastPushed.Lon) / distPx); // angle between the current and the preceeding point
double distPxRnded = Math.Round(distPx * 1000);
double offsetX = Math.Cos(angle) * (_params.StepLength / 1000);
double offsetY = Math.Sin(angle) * (_params.StepLength / 1000);
GpsPoint filler = new GpsPoint();
if (distPxRnded >= _params.StepLength && distPxRnded < 2 * _params.StepLength)
{
// acceptable point distance, add the point to the list
lastPushed = current;
_imgPoints.Add(new ImgPoint(lastPushed.Lon, lastPushed.Lat, lastPushed.Elev));
}
else if (distPxRnded >= 2 * _params.StepLength)
{
// add additional points to fill up too scarse area of points
if (lastPushed.Lon == current.Lon) // if the points are on the same vertical line
{
filler.Lon = lastPushed.Lon;
filler.Lat = lastPushed.Lat < current.Lat ? lastPushed.Lat + _params.StepLength / 1000 : lastPushed.Lat - _params.StepLength / 1000;
filler.Elev = lastPushed.Elev;
lastPushed = filler;
_imgPoints.Add(new ImgPoint(lastPushed.Lon, lastPushed.Lat, lastPushed.Elev));
}
else if (lastPushed.Lat == current.Lat) // if the points are on the same horizontal line
{
filler.Lat = lastPushed.Lat;
filler.Lon = lastPushed.Lon < current.Lon ? lastPushed.Lon + _params.StepLength / 1000 : lastPushed.Lon - _params.StepLength / 1000;
filler.Elev = lastPushed.Elev;
lastPushed = filler;
_imgPoints.Add(new ImgPoint(lastPushed.Lon, lastPushed.Lat, lastPushed.Elev));
}
else
{
// calculate and add the "filler" point
do
{
filler.Lon = lastPushed.Lon < current.Lon ? lastPushed.Lon + offsetX : lastPushed.Lon - offsetX;
filler.Lat = lastPushed.Lat < current.Lat ? lastPushed.Lat + offsetY : lastPushed.Lat - offsetY;
filler.Elev = lastPushed.Elev;
lastPushed = filler;
_imgPoints.Add(new ImgPoint(lastPushed.Lon, lastPushed.Lat, lastPushed.Elev));
distPx = Math.Sqrt(Math.Pow(current.Lon - lastPushed.Lon, 2) + Math.Pow(current.Lat - lastPushed.Lat, 2));
distPxRnded = Math.Round(distPx * 1000);
} while (distPxRnded >= 2 * _params.StepLength);
}
}
}
}
}
#endregion
}
public class TransposerParams
{
public TransposerParams(ImgPoint imgA, ImgPoint imgB, GpsPoint gpsA, GpsPoint gpsB, int step)
{
_imgStartPoint = imgA;
_imgEndPoint = imgB;
_gpsStartPoint = gpsA;
_gpsEndPoint = gpsB;
_stepLength = step;
}
private ImgPoint _imgStartPoint = new ImgPoint();
/// <summary>First point expressed in pixels, used for scaling and position calibration.</summary>
public ImgPoint ImgStartPoint { get { return _imgStartPoint; } }
private ImgPoint _imgEndPoint = new ImgPoint();
/// <summary>Last point expressed in pixels, used for scaling and position calibration.</summary>
public ImgPoint ImgEndPoint { get { return _imgEndPoint; } }
private int _stepLength = 1000;
/// <summary>Distance between two points, expressed in one thousanth of a pixel.</summary>
public int StepLength { get { return _stepLength; } }
private GpsPoint _gpsStartPoint = new GpsPoint();
/// <summary>First point expressed in GPS coordinates, used for scaling and position calibration.</summary>
public GpsPoint GpsStartPoint { get { return _gpsStartPoint; } }
private GpsPoint _gpsEndPoint = new GpsPoint();
/// <summary>Last point expressed in GPS coordinates, used for scaling and position calibration.</summary>
public GpsPoint GpsEndPoint { get { return _gpsEndPoint; } }
}
}
<file_sep>/GPSTransposer/Models/GPSTransposerModels.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace IvanB.GPSTransposer.Models
{
/// <summary>
/// Class representing cartesian coordinate system point, transposed from a GPS point.
/// Holds the X and Y coordinates (with X values incrementing from left to right and Y values incrementing from top to bottom) and Elevation data
/// </summary>
public class ImgPoint
{
/// <summary>X value (longitude), expressed in pixels</summary>
public double X { get; set;}
/// <summary>Y value (latitude), expressed in pixels</summary>
public double Y { get; set;}
/// <summary>Current elevation, taken from GPS data</summary>
public double? Elev { get; set;}
public ImgPoint() { }
public ImgPoint (double x, double y, double? elev)
{
this.X = x;
this.Y = y;
this.Elev = elev;
}
}
/// <summary>
/// Class representing a GPS point.
/// Holds the Logitude, Latitude and Elevation data.
/// </summary>
public class GpsPoint
{
/// <summary>Longitude, expressed in pixels</summary>
public double Lon { get; set; }
/// <summary>Latitude, expressed in pixels</summary>
public double Lat { get; set; }
/// <summary>Current elevation, taken from GPS data</summary>
public double? Elev { get; set; }
public GpsPoint() { }
public GpsPoint(double lon, double lat, double? elev)
{
this.Lon = lon;
this.Lat = lat;
this.Elev = elev;
}
}
}
<file_sep>/GPSTransposer/Helpers/Deserializer.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using IvanB.GPSTransposer.Models;
using System.Xml.Serialization;
using System.IO;
using System.Xml;
namespace IvanB.GPSTransposer
{
public class Deserializer
{
public static List<GpsPoint> ToGpsList(string xml)
{
List<GpsPoint> mapPoints = new List<GpsPoint>();
var serializer = new XmlSerializer(typeof(GPX));
GPX parsedGpx;
string parsedResult = string.Empty;
using (TextReader reader = new StringReader(xml))
{
try
{
parsedGpx = (GPX)serializer.Deserialize(reader);
if (parsedGpx != null && parsedGpx.Trk != null && parsedGpx.Trk.TrkSegList != null && parsedGpx.Trk.TrkSegList.Length > 0)
{
foreach (TrkSeg seg in parsedGpx.Trk.TrkSegList)
foreach (Trkpt point in seg.TrkPtList)
{
double d;
mapPoints.Add(new GpsPoint() { Lon = XmlConvert.ToDouble(point.Lon), Lat = XmlConvert.ToDouble(point.Lat), Elev = string.IsNullOrEmpty(point.Ele) ? 0 : XmlConvert.ToDouble(point.Ele) });
}
}
}
catch (Exception ex)
{
// log here
}
}
return mapPoints;
}
#region XML classes
[XmlRoot(ElementName = "gpx", Namespace = "http://www.topografix.com/GPX/1/1", DataType = "string", IsNullable = true)]
public class GPX
{
[XmlElement("trk")]
public Trk Trk { get; set; }
}
public class Trk
{
[XmlElement("name")]
public string Name { get; set; }
[XmlElement("link")]
public Link Link { get; set; }
[XmlElement("trkseg")]
public TrkSeg[] TrkSegList { get; set; }
}
public class Link
{
[XmlAttribute("href")]
public string Href;
}
public class TrkSeg
{
[XmlElement("trkpt")]
public Trkpt[] TrkPtList { get; set; }
}
public class Trkpt
{
[XmlAttribute(AttributeName = "lat")]
public string Lat { get; set; }
[XmlAttribute(AttributeName = "lon")]
public string Lon { get; set; }
[XmlElement(ElementName = "ele")]
public string Ele { get; set; }
}
#endregion
}
}
<file_sep>/GPSTransposerTests/GPSTransposerTest.cs
๏ปฟusing System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using IvanB.GPSTransposer;
using IvanB.GPSTransposer.Models;
using System.IO;
namespace GPSTransposerTests
{
[TestClass]
public class GPSTransposerTest
{
[TestMethod]
public void TestTranspose()
{
var p = new TransposerParams(
new ImgPoint(219, 686, null),
new ImgPoint(1167, 64, null),
new GpsPoint(2.42463, 39.577310000000004, null),
new GpsPoint(3.07493, 39.90439000000001, null),
1000);
string filePath = Environment.CurrentDirectory + "\\GpxData.txt";
StreamReader streamReader = new StreamReader(filePath);
string gpxContent = streamReader.ReadToEnd();
streamReader.Close();
var transposed = GPSTransposer.TransposeToJSON(p, gpxContent);
Assert.IsNotNull(transposed);
}
}
}
|
1732bdbf24ae62fc724d13858444244a594d899d
|
[
"C#"
] | 4 |
C#
|
IvanBreslauer/GpsTransposer
|
5aa54e7356d94c3ea1ae94f11914f4af52ba434a
|
b2f4b942d58e260762099bb6e20cc65aba4c67e7
|
refs/heads/main
|
<repo_name>dev-everaldo-cyrino/exercicios-de-raciocinio-17<file_sep>/README.md
# exercicios-de-raciocinio-17
exercicios que medem a capacidade do aluno/entrevistado
Faรงa um programa que leia um conjunto de
nรบmeros (X) e imprima a quantidade de
nรบmeros pares (QPares) e a quantidade de
nรบmeros impares (QImpares) lidos.<file_sep>/main.py
impares = 0
pares = 0
num = int(input('digite um numero: '))
for x in range(num):
x +=1
if x %2 ==1:
impares +=1
else:
pares +=1
print('''
numa lista de {} numeros
{} sรฃo impares e {} sรฃo pares'''.format(num,impares,pares))
|
72198f31f8db7a916eb73e38b0cf6e95509dc1e4
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
dev-everaldo-cyrino/exercicios-de-raciocinio-17
|
5fd6b01a87c1cda5e651c256469bbf6ae6aa820b
|
1cb002c073593389f06bdc2cd648f9a9d1c52bf0
|
refs/heads/master
|
<file_sep>#! /usr/bin/env python
import h5py
import numpy as np
#
# You can use this file in two ways: You can call it as a program from
# a directory with a "shake_result.hdf" file in it, and it will spit out
# some slightly interesting information. You might do that as a test. Or
# you can put it in a directory with your code and do:
#
# from hdf2dict import get_result_dict
#
# and then call get_result_dict() with the path to a shake_result.hdf file
# as an argument, and it will return a dictionary with stuff in it.
#
def get_result_dict(filename):
"""
This function is called with the path to a shake_result.hdf file. It
returns a dictionary with the following keys:
'mean': A grid of the conditional mean MMI
'mean_metadata': A metadata dictionary for the mean grid
'std': A grid of the conditional total standard deviation of MMI
'std_metadata': A metadata dictionary for the std grid
'phi': A grid of the prior within-event standard deviation of MMI
'phi_metadata': A metadata dictionary for the phi grid
'tau': A grid of the conditional between-event standard deviation of MMI
'tau_metadata': A metadata dictionary for the tau grid
The metadata dictionaries should be all the same. They have the following
keys:
'digits': some unknown thing
'dx': the grid spacing in the X dimension
'dy': the grid spacing in the Y dimension
'nx': the number of grid points in the X dimension
'ny': the number of grid points in the Y dimension
'units': the physical units of the grids (intensity)
'xmax': the maximum longitude of the grid
'xmin': the minimum longitude of the grid
'ymax': the maximum latitude of the grid
'ymin': the minimum latitude of the grid
The grids themselves will be of dimension (ny x nx) (rows x cols).
"""
ddict = {}
hdfobj = h5py.File(filename, "r+")
group = hdfobj['arrays']['imts']['GREATER_OF_TWO_HORIZONTAL']['MMI']
for name in ('mean', 'std', 'phi', 'tau'):
dset = group[name]
ddict[name] = dset[()].astype(np.float64)
metadata = {}
for key, value in dset.attrs.items():
metadata[key] = value
ddict[name + '_metadata'] = metadata
hdfobj.close()
return ddict
if __name__ == '__main__':
ddict = get_result_dict("shake_result.hdf")
print("ddict keys: ", ddict.keys())
print()
print("Metadata:")
print(ddict['mean_metadata'].items())
print()
print("Array shape: ", ddict['mean'].shape)
<file_sep>#! /usr/bin/env python
import json
import numpy as np
#
# You can use this file in two ways: You can call it as a program from
# a directory with a "stationlist.json" file in it, and it will spit out
# some slightly interesting information. You might do that as a test. Or
# you can put it in a directory with your code and do:
#
# from json2dict import get_station_dict
#
# and then call get_station_dict() with the path to a stationlist.json file
# as an argument, and it will return a dictionary with stuff in it.
#
def get_station_dict(filename):
"""
This function is called with the path to a stationlist.json file. It
returns a dictionary with the following keys:
'lons': An array of station longitudes
'lats': An array of station latitudes
'intensity': An array of observed intensities
'residuals': An array of residuals (observed - predicted) (not
including bias)
'phi': An array of within-event stddev of the predictions
'tau': An array of between-event stddev of the predictions
'extra_sigma': An array of the additional stddev of the observations
'bias': An array of the bias of the data at the observation points
'bias_stddev': An array of the stddev of the bias at the observation
points
"""
lonlist = []
latlist = []
intensitylist = []
residuallist = []
philist = []
taulist = []
extra_sigma_list = []
bias_list = []
bias_sigma_list = []
with open(filename) as f:
sdata = json.load(f)
for station in sdata['features']:
properties = station['properties']
if not properties['source'] == 'DYFI':
continue
if not properties['intensity_flag'] == '0':
continue
intensity = properties['intensity']
if intensity is None or intensity == 'null':
continue
intensitylist.append(float(intensity))
extra_sigma_list.append(float(properties['intensity_stddev']))
for pred in properties['predictions']:
if not pred['name'] == 'mmi':
continue
residuallist.append(float(intensity) - float(pred['value']))
philist.append(float(pred['phi']))
taulist.append(float(pred['tau']))
bias_list.append(float(pred['bias']))
bias_sigma_list.append(float(pred['bias_sigma']))
break
lonlist.append(float(station['geometry']['coordinates'][0]))
latlist.append(float(station['geometry']['coordinates'][1]))
sdict = {
'lons': np.array(lonlist),
'lats': np.array(latlist),
'intensity': np.array(intensitylist),
'residuals': np.array(residuallist),
'phi': np.array(philist),
'tau': np.array(taulist),
'extra_sigma': np.array(extra_sigma_list),
'bias': np.array(bias_list),
'bias_sigma': np.array(bias_sigma_list)
}
return sdict
if __name__ == '__main__':
sdict = get_station_dict("stationlist.json")
print("sdict keys: ", sdict.keys())
print()
print("Number of stations:")
nsta = len(sdict['lons'])
print(nsta)
print()
print("Min lon, Max lon, Min lat, Max lat:")
if nsta > 0:
print(np.min(sdict['lons']), np.max(sdict['lons']),
np.min(sdict['lats']), np.max(sdict['lats']))
else:
print("No data")
<file_sep>import numpy as np
from openquake.hazardlib import const
class AbrahamsonBhasin2020(object):
"""
Module to make conditional conversions from SA(T) to PGV. The user
provides a magnitude when an instance and the instance can report back
what period of SA is appropriate to use for computing PGV. The module
is based upon:
<NAME>., and <NAME>. (2020) Conditional ground-motion model
for peak ground velocity for active crustal regions. PEER Report 2020/05,
Pacific Earthquake Engineering Research Center, U.C. Berkeley.
"""
def __init__(self, mag):
self.mag = mag
mag_T = [(3.5, 0.20),
(4.5, 0.28),
(5.5, 0.40),
(6.5, 0.95),
(7.5, 1.40),
(8.5, 2.80)]
self.Tref = 0
for mm, tt in mag_T:
if mag <= mm:
self.Tref = tt
break
if self.Tref == 0:
self.Tref = tt
self.coeff = {
'a1': 5.39,
'a2': 0.799,
'a3': 0.654,
'a4': 0.479,
'a5': -0.062,
'a6': -0.359,
'a7': -0.134,
'a8': 0.023,
'phi': 0.29,
'tau': 0.16,
'sigma': 0.33
}
def getTref(self):
"""
Returns the period of the SA amps suitable for conversion to PGV.
Args:
None.
Returns:
(float): The period of the SA amps to supply to getPGVandSTDDEVS()
"""
return self.Tref
def getPGVandSTDDEVS(self, psa, stddevs, sdtypes, rrup, vs30):
"""
Function to compute the PGVs and inflate the uncertainties based on
the input SA amps and uncertainties.
Args:
psa (np.array): An array os SA amp of the appropriate period.
stddevs(np.arrays): A list of one or more array of standard
deviations of the psa amps. The list may also contain arrays
of the stddevs inflated by the point-source adjustments. Each
array must be the same shape as the psa array.
sdtypes (list): A list of the types of the standard deviations in
stddevs (in order). These are OpenQuake const.StdDev types.
rrup (np.array): Rupture distance to the points in psa. Must be
the same shape as psa.
vs30 (np.array): The Vs30 value at the points in psa. Must be the
same shape as psa.
Returns:
(tuple: ndarray, list): An array of PGV values, and a list of
stddev arrays corresponding to the input stddev types, now
with the uncertainty propagated through the conversion.
"""
c = self.coeff
m = self.mag
if m < 5:
f1 = c['a2']
elif m <= 7.5:
f1 = c['a2'] + (c['a3'] - c['a2']) * (m - 5.0) / 2.5
else:
f1 = c['a3']
pgv = c['a1'] + f1 * psa + c['a4'] * (m - 6.0) + \
c['a5'] * (8.5 - m)**2 + \
c['a6'] * np.log(rrup + 5.0 * np.exp(0.4 * (m - 6.0))) + \
(c['a7'] + c['a8'] * (m - 5.0)) * np.log(vs30 / 425)
#
# ShakeMap will often produce lists of stddevs that are twice
# as long as sdtypes: one set that has been inflated by the
# point-source to finite-fault factors, and one that has not.
# Here we modify both, if they are present.
#
stddevs_out = []
mytypes = sdtypes.copy()
if len(stddevs) == 2 * len(sdtypes):
mytypes.extend(sdtypes)
for i, sdtype in enumerate(mytypes):
if sdtype == const.StdDev.INTER_EVENT:
sdout = np.sqrt(f1**2 * stddevs[i]**2 + c['tau']**2)
elif sdtype == const.StdDev.INTRA_EVENT:
sdout = np.sqrt(f1**2 * stddevs[i]**2 + c['phi']**2)
else:
sdout = np.sqrt(f1**2 * stddevs[i]**2 + c['sigma']**2)
stddevs_out.append(sdout)
return pgv, stddevs_out
class AbrahamsonBhasin2020PGA(AbrahamsonBhasin2020):
"""
An alternative to AbrahamsonBhasin2020 when only PGA is available for
conversion.
"""
def __init__(self, mag):
self.mag = mag
self.Tref = 0
self.coeff = {
'a1': 4.77,
'a2': 0.738,
'a3': 0.484,
'a4': 0.275,
'a5': -0.036,
'a6': -0.332,
'a7': -0.44,
'a8': 0.0,
'phi1': 0.32,
'phi2': 0.42,
'phi': 0.0,
'tau1': 0.12,
'tau2': 0.26,
'tau': 0.0,
'sigma1': 0.34,
'sigma2': 0.49,
'sigma': 0.0,
'm1': 5.0,
'm2': 7.0
}
c = self.coeff
mref = (self.mag - c['m1']) / (c['m2'] - c['m1'])
#
# Here we set the magnitude-dependent phi, tau, and sigma
# to be used in the parent cless' getPGVandSTDDEVS()
#
if self.mag < c['m1']:
c['phi'] = c['phi1']
c['tau'] = c['tau1']
c['sigma'] = c['sigma1']
elif self.mag <= c['m2']:
c['phi'] = c['phi1'] + (c['phi2'] - c['phi2']) * mref
c['tau'] = c['tau1'] + (c['tau2'] - c['tau2']) * mref
c['sigma'] = c['sigma1'] + (c['sigma2'] - c['sigma2']) * mref
else:
c['phi'] = c['phi2']
c['tau'] = c['tau2']
c['sigma'] = c['sigma2']
class AbrahamsonBhasin2020SA1(AbrahamsonBhasin2020):
"""
An alternative to AbrahamsonBhasin2020 when only SA(1.0) is available for
conversion.
"""
def __init__(self, mag):
self.mag = mag
self.Tref = 1.0
self.coeff = {
'a1': 4.80,
'a2': 0.82,
'a3': 0.55,
'a4': 0.27,
'a5': 0.054,
'a6': -0.382,
'a7': -0.21,
'a8': 0.0,
'phi1': 0.28,
'phi2': 0.38,
'phi': 0.0,
'tau1': 0.12,
'tau2': 0.17,
'tau': 0.0,
'sigma1': 0.30,
'sigma2': 0.42,
'sigma': 0.0,
'm1': 5.0,
'm2': 7.0
}
c = self.coeff
mref = (self.mag - c['m1']) / (c['m2'] - c['m1'])
#
# Here we set the magnitude-dependent phi, tau, and sigma
# to be used in the parent cless' getPGVandSTDDEVS()
#
if self.mag < c['m1']:
c['phi'] = c['phi1']
c['tau'] = c['tau1']
c['sigma'] = c['sigma1']
elif self.mag <= c['m2']:
c['phi'] = c['phi1'] + (c['phi2'] - c['phi2']) * mref
c['tau'] = c['tau1'] + (c['tau2'] - c['tau2']) * mref
c['sigma'] = c['sigma1'] + (c['sigma2'] - c['sigma2']) * mref
else:
c['phi'] = c['phi2']
c['tau'] = c['tau2']
c['sigma'] = c['sigma2']
<file_sep>#!/usr/bin/env python
# Standard library imports
import os.path
import sys
# Third party imports
import numpy as np
import pytest
# Local imports
from shakelib.conversions.imt.abrahamson_bhasin_2020 import (
AbrahamsonBhasin2020, AbrahamsonBhasin2020PGA, AbrahamsonBhasin2020SA1)
from openquake.hazardlib import const
homedir = os.path.dirname(os.path.abspath(__file__)) # where is this script?
shakedir = os.path.abspath(os.path.join(homedir, '..', '..', '..', '..'))
sys.path.insert(0, shakedir)
def test_abrahamsonbhasin2020():
# Inputs
mag = 8.0
ab2020 = AbrahamsonBhasin2020(mag)
Tref = ab2020.getTref()
psa = np.array([2.0, 1.8, 1.6, 1.4, 1.2, 1.0, 0.8, 0.6, 0.4, 0.2, 0.1])
sigma = np.array([0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72,
0.72, 0.72])
tau = np.array([0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4])
phi = np.array([0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6])
sdtypes = [const.StdDev.TOTAL, const.StdDev.INTER_EVENT,
const.StdDev.INTRA_EVENT]
rrup = np.array([2.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0,
90.0, 100.0])
vs30 = np.array([200.0, 180.0, 420.0, 630.0, 740.0, 550.0, 360.0, 270.0,
480.0, 290.0, 600.0])
pgv, stddevs = ab2020.getPGVandSTDDEVS(psa, [sigma, tau, phi], sdtypes,
rrup, vs30)
# print(repr(pgv))
# print(repr(stddevs[0]))
# print(repr(stddevs[1]))
# print(repr(stddevs[2]))
pgv_ref = \
np.array([6.76516894, 6.47038352, 6.14539197, 5.88822518, 5.66883031,
5.4931866 , 5.33554182, 5.17621557, 4.96628769, 4.83086164,
4.68435124])
np.testing.assert_almost_equal(pgv, pgv_ref)
sig_ref = \
np.array([0.57500259, 0.57500259, 0.57500259, 0.57500259, 0.57500259,
0.57500259, 0.57500259, 0.57500259, 0.57500259, 0.57500259,
0.57500259])
np.testing.assert_almost_equal(sig_ref, stddevs[0])
tau_ref = \
np.array([0.30665055, 0.30665055, 0.30665055, 0.30665055, 0.30665055,
0.30665055, 0.30665055, 0.30665055, 0.30665055, 0.30665055,
0.30665055])
np.testing.assert_almost_equal(tau_ref, stddevs[1])
phi_ref = \
np.array([0.48793213, 0.48793213, 0.48793213, 0.48793213, 0.48793213,
0.48793213, 0.48793213, 0.48793213, 0.48793213, 0.48793213,
0.48793213])
np.testing.assert_almost_equal(phi_ref, stddevs[2])
def test_abrahamsonbhasin2020sa1():
# Inputs
mag = 7.4
ab2020 = AbrahamsonBhasin2020SA1(mag)
Tref = ab2020.getTref()
psa = np.array([2.0, 1.8, 1.6, 1.4, 1.2, 1.0, 0.8, 0.6, 0.4, 0.2, 0.1])
sigma = np.array([0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72,
0.72, 0.72])
tau = np.array([0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4])
phi = np.array([0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6])
sdtypes = [const.StdDev.TOTAL, const.StdDev.INTER_EVENT,
const.StdDev.INTRA_EVENT]
rrup = np.array([2.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0,
90.0, 100.0])
vs30 = np.array([200.0, 180.0, 420.0, 630.0, 740.0, 550.0, 360.0, 270.0,
480.0, 290.0, 600.0])
pgv, stddevs = ab2020.getPGVandSTDDEVS(psa, [sigma, tau, phi], sdtypes,
rrup, vs30)
# print(repr(pgv))
# print(repr(stddevs[0]))
# print(repr(stddevs[1]))
# print(repr(stddevs[2]))
pgv_ref = \
np.array([5.61589861, 5.31341327, 4.86006093, 4.54874047, 4.31509445,
4.1939768 , 4.11077608, 4.0071555 , 3.72850462, 3.68138081,
3.43577395])
np.testing.assert_almost_equal(pgv, pgv_ref)
sig_ref = \
np.array([0.58261055, 0.58261055, 0.58261055, 0.58261055, 0.58261055,
0.58261055, 0.58261055, 0.58261055, 0.58261055, 0.58261055,
0.58261055])
np.testing.assert_almost_equal(sig_ref, stddevs[0])
tau_ref = \
np.array([0.28145952, 0.28145952, 0.28145952, 0.28145952, 0.28145952,
0.28145952, 0.28145952, 0.28145952, 0.28145952, 0.28145952,
0.28145952])
np.testing.assert_almost_equal(tau_ref, stddevs[1])
phi_ref = \
np.array([0.50756161, 0.50756161, 0.50756161, 0.50756161, 0.50756161,
0.50756161, 0.50756161, 0.50756161, 0.50756161, 0.50756161,
0.50756161])
np.testing.assert_almost_equal(phi_ref, stddevs[2])
def test_abrahamsonbhasin2020pga():
# Inputs
mag = 7.4
ab2020 = AbrahamsonBhasin2020PGA(mag)
Tref = ab2020.getTref()
psa = np.array([2.0, 1.8, 1.6, 1.4, 1.2, 1.0, 0.8, 0.6, 0.4, 0.2, 0.1])
sigma = np.array([0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72, 0.72,
0.72, 0.72])
tau = np.array([0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4, 0.4])
phi = np.array([0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6, 0.6])
sdtypes = [const.StdDev.TOTAL, const.StdDev.INTER_EVENT,
const.StdDev.INTRA_EVENT]
rrup = np.array([2.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0,
90.0, 100.0])
vs30 = np.array([200.0, 180.0, 420.0, 630.0, 740.0, 550.0, 360.0, 270.0,
480.0, 290.0, 600.0])
pgv, stddevs = ab2020.getPGVandSTDDEVS(psa, [sigma, tau, phi], sdtypes,
rrup, vs30)
# print(repr(pgv))
# print(repr(stddevs[0]))
# print(repr(stddevs[1]))
# print(repr(stddevs[2]))
pgv_ref = \
np.array([5.64284705, 5.40573036, 4.7921966 , 4.4158703 , 4.17001613,
4.13980353, 4.17526695, 4.15793101, 3.76625139, 3.85369198,
3.45235077])
np.testing.assert_almost_equal(pgv, pgv_ref)
sig_ref = \
np.array([0.60554952, 0.60554952, 0.60554952, 0.60554952, 0.60554952,
0.60554952, 0.60554952, 0.60554952, 0.60554952, 0.60554952,
0.60554952])
np.testing.assert_almost_equal(sig_ref, stddevs[0])
tau_ref = \
np.array([0.32660535, 0.32660535, 0.32660535, 0.32660535, 0.32660535,
0.32660535, 0.32660535, 0.32660535, 0.32660535, 0.32660535,
0.32660535])
np.testing.assert_almost_equal(tau_ref, stddevs[1])
phi_ref = \
np.array([0.51411076, 0.51411076, 0.51411076, 0.51411076, 0.51411076,
0.51411076, 0.51411076, 0.51411076, 0.51411076, 0.51411076,
0.51411076])
np.testing.assert_almost_equal(phi_ref, stddevs[2])
if __name__ == '__main__':
test_abrahamsonbhasin2020()
test_abrahamsonbhasin2020sa1()
test_abrahamsonbhasin2020pga()
<file_sep>#!/usr/bin/env python
# -*- coding: utf-8 -*-
import argparse
import json
from collections import OrderedDict
import pandas as pd
from libcomcat.search import get_event_by_id
def main():
desc = "Program to get CSV file of station data from ShakeMap."
parser = argparse.ArgumentParser(
description=desc)
parser.add_argument('eventid', help='Comcat event ID.')
args = parser.parse_args()
evid = args.eventid
# Download stationlist
event = get_event_by_id(evid)
shakemap = event.getProducts('shakemap')[0]
json_file = evid + "_stationlist.json"
shakemap.getContent('stationlist.json', json_file)
with open(json_file) as f:
station_dict = json.load(f)
# Extract info in tabular form
out_dict = OrderedDict()
out_dict['lat'] = []
out_dict['lon'] = []
out_dict['rjb'] = []
out_dict['repi'] = []
out_dict['pga_percent_g'] = []
out_dict['pgv_cm_s'] = []
for f in station_dict['features']:
if f['properties']['station_type'] == 'seismic':
out_dict['lon'].append(f['geometry']['coordinates'][0])
out_dict['lat'].append(f['geometry']['coordinates'][1])
out_dict['rjb'].append(f['properties']['distances']['rjb'])
out_dict['repi'].append(f['properties']['distances']['repi'])
out_dict['pga_percent_g'].append(f['properties']['pga'])
out_dict['pgv_cm_s'].append(f['properties']['pgv'])
out_file = evid + "_stationlist.csv"
out_df = pd.DataFrame(out_dict)
out_df.to_csv(out_file, index=False)
if __name__ == '__main__':
main()
<file_sep>#!/bin/bash
unamestr=`uname`
if [ "$unamestr" == 'Linux' ]; then
prof=~/.bashrc
mini_conda_url=https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
matplotlibdir=~/.config/matplotlib
elif [ "$unamestr" == 'FreeBSD' ] || [ "$unamestr" == 'Darwin' ]; then
prof=~/.bash_profile
mini_conda_url=https://repo.continuum.io/miniconda/Miniconda3-latest-MacOSX-x86_64.sh
matplotlibdir=~/.matplotlib
else
echo "Unsupported environment. Exiting."
exit
fi
CC_PKG=c-compiler
source $prof
# Name of virtual environment
VENV=shakemap
developer=0
openquake_deps=0
py_ver=3.8
while getopts p:d:q FLAG; do
case $FLAG in
p)
py_ver=$OPTARG
;;
d)
echo "Installing developer packages."
developer=1
;;
q)
echo "Installing full OpenQuake dependencies."
openquake_deps=1
;;
esac
done
#if [ $py_ver == '3.8' ] && [ "$unamestr" == 'Linux' ]; then
# echo "WARNING: ShakeMap on Python v3.8 on some versions of Linux "
# echo "may fail in unexpected ways. We are enforcing the use "
# echo "of Python v3.7 until this warning disappears."
# echo ""
# py_ver=3.7
#fi
echo "Using python version $py_ver"
echo ""
# create a matplotlibrc file with the non-interactive backend "Agg" in it.
if [ ! -d "$matplotlibdir" ]; then
mkdir -p $matplotlibdir
# if mkdir fails, bow out gracefully
if [ $? -ne 0 ];then
echo "Failed to create matplotlib configuration file. Exiting."
exit 1
fi
fi
matplotlibrc=$matplotlibdir/matplotlibrc
if [ ! -e "$matplotlibrc" ]; then
echo "backend : Agg" > "$matplotlibrc"
echo "NOTE: A non-interactive matplotlib backend (Agg) has been set for this user."
elif grep -Fxq "backend : Agg" $matplotlibrc ; then
:
elif [ ! grep -Fxq "backend" $matplotlibrc ]; then
echo "backend : Agg" >> $matplotlibrc
echo "NOTE: A non-interactive matplotlib backend (Agg) has been set for this user."
else
sed -i '' 's/backend.*/backend : Agg/' $matplotlibrc
echo "###############"
echo "NOTE: $matplotlibrc has been changed to set 'backend : Agg'"
echo "###############"
fi
# Is conda installed?
conda --version
if [ $? -ne 0 ]; then
echo "No conda detected, installing miniconda..."
command -v curl >/dev/null 2>&1 || { echo >&2 "Script requires curl but it's not installed. Aborting."; exit 1; }
curl -L $mini_conda_url -o miniconda.sh;
# if curl fails, bow out gracefully
if [ $? -ne 0 ];then
echo "Failed to download miniconda installer shell script. Exiting."
exit 1
fi
echo "Install directory: $HOME/miniconda"
bash miniconda.sh -f -b -p $HOME/miniconda
# if miniconda.sh fails, bow out gracefully
if [ $? -ne 0 ];then
echo "Failed to run miniconda installer shell script. Exiting."
exit 1
fi
. $HOME/miniconda/etc/profile.d/conda.sh
# remove the shell script
rm miniconda.sh
else
echo "conda detected, installing $VENV environment..."
fi
echo "Installing mamba from conda-forge"
conda install mamba -y -n base -c conda-forge
echo "Installing packages from conda-forge"
# Choose an environment file based on platform
# only add this line if it does not already exist
grep "/etc/profile.d/conda.sh" $prof
if [ $? -ne 0 ]; then
echo ". $_CONDA_ROOT/etc/profile.d/conda.sh" >> $prof
fi
# Start in conda base environment
echo "Activate base virtual environment"
eval "$(conda shell.bash hook)"
conda activate base
# Remove existing shakemap environment if it exists
conda remove -y -n $VENV --all
conda clean -y --all
# Extra packages to install with dev option
dev_list=(
"autopep8>=1.5.7"
"flake8>=3.9.2"
"pyflakes>=2.3.1"
"rope>=0.19.0"
"yapf>=0.31.0"
"sphinx>=4.0.2"
"sphinx-argparse>=0.2.5"
)
openquake_list=(
"decorator>=4.3"
"django>=3.2"
"requests>=2.20"
"setuptools"
"toml"
)
# Required package list:
package_list=(
"python=$py_ver"
"$CC_PKG"
"cartopy>=0.20"
"configobj>=5.0.6"
"cython>=0.29.23"
"defusedxml>=0.7.1"
"descartes>=1.1.0"
"docutils>=0.14"
"fiona>=1.8.13"
"gdal>=3.0.2"
"h5py>=2.10.0"
"impactutils>=0.8.28"
"ipython>=7.22.0"
"libcomcat>=2.0.12"
"lockfile>=0.12.2"
"mapio>0.7.27"
"matplotlib-base>=3.4.2"
"numpy==1.20"
"obspy>=1.2.2"
"openmp>=8.0.1"
"pandas>=1.2.5"
"ps2ff>=1.5.2"
"psutil>=5.6.7"
"pyproj>=2.6.1"
"pytest>=6.2.4"
"pytest-cov>=2.12.1"
"python-daemon>=2.3.0"
"pytest-faulthandler>=2.0.1"
"pytest-azurepipelines>=0.8.0"
"pyzmq<20.0"
"rasterio==1.2.5"
"scikit-image>=0.16.2"
"scipy>=1.4.1"
"shapely>=1.7.1"
"simplekml>=1.3.5"
"strec>=2.1.7"
"versioneer>=0.20"
"vcrpy>=4.1.1"
)
if [ $developer == 1 ]; then
package_list=( "${package_list[@]}" "${dev_list[@]}" )
echo ${package_list[*]}
fi
if [ $openquake_deps == 1 ]; then
package_list=( "${package_list[@]}" "${openquake_list[@]}" )
echo ${package_list[*]}
fi
# Create a conda virtual environment
conda config --add channels 'conda-forge'
conda config --add channels 'defaults'
conda config --set channel_priority flexible
echo "Creating the $VENV virtual environment:"
mamba create -y -n $VENV ${package_list[*]}
# Bail out at this point if the conda create command fails.
# Clean up zip files we've downloaded
if [ $? -ne 0 ]; then
echo "Failed to create conda environment. Resolve any conflicts, then try again."
exit 1
fi
# Activate the new environment
echo "Activating the $VENV virtual environment"
conda activate $VENV
# if conda activate fails, bow out gracefully
if [ $? -ne 0 ];then
echo "Failed to activate ${VENV} conda environment. Exiting."
exit 1
fi
# upgrade pip, mostly so pip doesn't complain about not being new...
pip install --upgrade pip
# if pip upgrade fails, complain but try to keep going
if [ $? -ne 0 ];then
echo "Failed to upgrade pip, trying to continue..."
exit 1
fi
# The presence of a __pycache__ folder in bin/ can cause the pip
# install to fail... just to be safe, we'll delete it here.
if [ -d bin/__pycache__ ]; then
rm -rf bin/__pycache__
fi
if [ $developer == 1 ]; then
pip install sphinx-argparse
fi
# Install OQ from github to get NGA East since it isn't in a release yet.
echo "Installing OpenQuake from github..."
pip install --upgrade --no-dependencies https://github.com/gem/oq-engine/archive/refs/tags/v3.12.0.tar.gz
if [ $? -ne 0 ];then
echo "Failed to pip install OpenQuake. Exiting."
exit 1
fi
# This package
echo "Installing ${VENV}..."
pip install --no-deps -e .
# if pip install fails, bow out gracefully
if [ $? -ne 0 ];then
echo "Failed to pip install this package. Exiting."
exit 1
fi
# Tell the user they have to activate this environment
echo "Type 'conda activate $VENV' to use this new virtual environment."
|
05da7a1e2c1b667673608fd566b3cb7e958d47a5
|
[
"Python",
"Shell"
] | 6 |
Python
|
vinceq-usgs/shakemap
|
81e3905354ad05087861af6ed4fb4be1324b0a2c
|
80889e0c3842cd14e0e77bb6fba5be4261c4c344
|
refs/heads/master
|
<repo_name>AstroFields/ExampleMetaBox<file_sep>/README.md
# AstroFields MetaBox
[](https://packagist.org/packages/wecodemore/astroexamples-metabox)
[](https://packagist.org/packages/wecodemore/astroexamples-metabox)
[](https://packagist.org/packages/wecodemore/astroexamples-metabox)
[](https://packagist.org/packages/wecodemore/astroexamples-metabox)
_Example plugin_<file_sep>/Bootstrap.php
<?php
namespace WCM\AstroFields\Examples\MetaBox;
/**
* Plugin Name: (WCM) AstroFields MetaBox Example
* Description: MetaBox example plugin
*/
// Composer autoloader
if ( file_exists( __DIR__."/vendor/autoload.php" ) )
require_once __DIR__."/vendor/autoload.php";
use WCM\AstroFields\Core\Mediators\Entity;
use WCM\AstroFields\Core\Commands\ViewCmd;
use WCM\AstroFields\Security\Commands\SanitizeString;
use WCM\AstroFields\Security\Commands\SanitizeMail;
use WCM\AstroFields\MetaBox\Commands\MetaBox as MetaBoxCmd;
use WCM\AstroFields\MetaBox\Templates\Table as MetaBoxTmpl;
use WCM\AstroFields\PostMeta\Commands\SaveMeta;
use WCM\AstroFields\PostMeta\Commands\DeleteMeta;
use WCM\AstroFields\PostMeta\Receivers\PostMetaValue;
use WCM\AstroFields\Standards\Templates\SelectFieldTmpl;
use WCM\AstroFields\Standards\Templates\TextareaFieldTmpl;
use WCM\AstroFields\HTML5\Templates\EmailFieldTmpl;
### META BOX/POST META
add_action( 'wp_loaded', function()
{
if ( ! is_admin() )
return;
// Commands
$mail_view = new ViewCmd;
$mail_view
->setProvider( new PostMetaValue )
->setTemplate( new EmailFieldTmpl );
// Entity: Field
$mail_field = new Entity( 'wcm_test', array(
'post',
'page',
) );
// Attach Commands
$mail_field
->attach( $mail_view, array(
'attributes' => array(
'size' => 40,
'class' => 'foo bar baz',
),
) )
->attach( new SaveMeta )
->attach( new DeleteMeta )
->attach( new SanitizeMail );
// Commands
$select_view = new ViewCmd;
$select_view
->setProvider( new PostMetaValue )
->setTemplate( new SelectFieldTmpl );
// Entity: Field
$select_field = new Entity( 'wcm_select', array(
'post',
) );
// Attach Commands
$select_field
->attach( $select_view, array(
'attributes' => array(
'size' => 40,
'class' => 'foo bar baz',
),
'options' => array(
'' => '-- select --',
'bar' => 'Bar',
'foo' => 'Foo',
'baz' => 'Baz',
'dragons' => 'Dragons',
),
) )
->attach( new DeleteMeta )
->attach( new SaveMeta )
->attach( new SanitizeString );
// Commands
$textarea_view = new ViewCmd;
$textarea_view
->setProvider( new PostMetaValue )
->setTemplate( new TextareaFieldTmpl );
// Entity: Field
$textarea_field = new Entity( 'wcm_textarea', array(
'post',
) );
// Attach Commands
$textarea_field
->attach( $textarea_view, array(
'attributes' => array(
'class' => 'attachmentlinks',
'rows' => 5,
'cols' => 40,
),
) )
->attach( new DeleteMeta )
->attach( new SaveMeta )
->attach( new SanitizeString );
// Command: MetaBox
$meta_box_cmd = new MetaBoxCmd( 'Test Box' );
$meta_box_cmd
->attach( $select_field, 10 )
->attach( $textarea_field, 20 )
->attach( $mail_field, 30 )
->setTemplate( new MetaBoxTmpl );
// Entity: MetaBox
$meta_box = new Entity( 'wcm_meta_box', array(
'post',
'page',
) );
$meta_box->attach( $meta_box_cmd );
} );
|
035ebeedb1c581fbc313ae99a9f5144b44dbabce
|
[
"Markdown",
"PHP"
] | 2 |
Markdown
|
AstroFields/ExampleMetaBox
|
973a9814cff6cb25db75db7189ed93f688bbb3ab
|
aaa145da91b7ceb432e4a90aec8d26ef54b4e7e6
|
refs/heads/master
|
<repo_name>ahackel/name-generator<file_sep>/README.md
# name-generator
A name generator written in javascript. It can generate (mostly) German names and variations of these. I created it to find a name for my son.
[Run Name Generator](https://andreashackel.de/name-generator)
## Usage
Just click **"New Name"**. By default it generates just random names. Alternatively enter a name into **"Template Name"**. Then the generator will create variations of this name.
If you like one of the generated names but want to create more variations of it just click it and it becomes the new template name.
## Favorites
Click the star in front of a name to make it a favorite. Favorite names stay in the list when you reload the page.
## Edit the source list
You can enter your own source names into **parts.txt**. Each line contains a single name split into syllables.
<file_sep>/js/namegen.js
'use strict';
export class NameGen {
constructor (partsFile) {
this.MAX_COUNT = 50000;
this.MIN_LENGTH = 4;
this.MIN_PARTS = 1;
this.MIN_SIMILARITY = 0.6;
this.parts = [];
this.names = [];
this.loadParts(partsFile);
}
loadParts(partsFile) {
function longer(s1, s2){
return s2.length - s1.length;
}
fetch(partsFile)
.then(response => {
if (response.ok) {
return Promise.resolve(response);
}
else {
return Promise.reject(new Error('Failed to load ' + partsFile))
}
})
.then(response => response.text())
.then(data => {
var lines = data.split(/\n/);
for (var line of lines) {
var parts = line.split(' ');
for (var c = 0; c < parts.length; c++)
this.addUnique(this.parts, parts[c].toLowerCase());
}
this.parts.sort(longer);
})
.catch(function(error) {
console.log(`Error: ${error.message}`);
});
}
addUnique(a, item) {
if (a.includes(item) == false)
a.push(item);
}
randomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
randomItem (_array) {
return _array[this.randomInt(0, _array.length)];
}
getRandomPart(start) {
var parts = this.parts;
var validParts = parts;
if (start && start.length > 0)
validParts = parts.filter(function(s){ return s.startsWith(start.substr(0, s.length)); });
if (validParts.length > 0) {
return this.randomItem(validParts);
}
else
return '';
}
getRandomPartReverse(end) {
var parts = nameGen.parts;
var validParts = parts;
if (end && end.length > 0) {
validParts = parts.filter(function(s){ return s.endsWith(end.substr(-s.length)); });
}
if (validParts.length > 0) {
return this.randomItem(validParts);
}
else
return '';
}
generateName(start, maxParts) {
start = start || "";
maxParts = maxParts || 3;
start = start.toLowerCase();
var name = "";
var count = 0;
do {
name = "";
count++;
var numParts = this.randomInt(this.MIN_PARTS, maxParts + 1);
var _start = start;
for (var i = 0; i < numParts; i++) {
var part = this.getRandomPart(_start);
_start = _start.substr(part.length);
name += part;
if (name.length == 0) continue;
}
} while ((name.length < this.MIN_LENGTH || this.names.includes(name)) && count < this.MAX_COUNT)
if (count == this.MAX_COUNT)
name = "";
if (name.length > 0) {
this.names.push(name);
name = name[0].toUpperCase() + name.slice(1);
}
return name;
}
generateNameReverse(end, maxParts) {
end = end || "";
maxParts = maxParts || 3;
end = end.toLowerCase();
var name = "";
var count = 0;
do {
name = "";
count++;
var numParts = this.randomInt(this.MIN_PARTS, maxParts + 1);
var _end = end;
for (var i = 0; i < numParts; i++) {
var part = this.getRandomPartReverse(_end);
_end = _end.substr(0, _end.length - part.length);
name = part + name;
if (name.length == 0) continue;
}
} while ((name.length < this.MIN_LENGTH || this.names.includes(name)) && count < this.MAX_COUNT)
if (count == this.MAX_COUNT)
name = "";
if (name.length > 0) {
this.names.push(name);
name = name[0].toUpperCase() + name.slice(1);
}
return name;
}
generateSimilarName(orgName, maxParts) {
if (!orgName) {
return this.generateName('', maxParts);
}
maxParts = maxParts || 3;
orgName = orgName.toLowerCase();
var name = "";
var count = 0;
do {
name = "";
count++;
var numParts = this.randomInt(this.MIN_PARTS, maxParts + 1);
for (var i = 0; i < numParts; i++) {
var part = this.getRandomPart();
name += part;
if (name.length == 0) continue;
}
} while ((name.length < this.MIN_LENGTH || name == orgName || this.names.includes(name) ||
this.similarName(orgName, name) < this.MIN_SIMILARITY) && count < this.MAX_COUNT)
if (count == this.MAX_COUNT)
name = "";
if (name.length > 0) {
this.names.push(name);
name = name[0].toUpperCase() + name.slice(1);
}
return name;
}
breakName(name) {
name = name.toLowerCase();
function isVowel(s) {
return (/^[aeiouรครผรถy]$/i).test(s);
}
var broken = "";
var len = name.length;
var lastVowelPos = -1;
var lastSplitPos = 0;
for (var i = 0; i < len; i++) {
if (isVowel(name[i])) {
if (lastVowelPos > -1) {
if (lastVowelPos + 1 == i) {
var part = name[i - 1] + name[i];
if (part == "au" || part == "รคu" || part == "eu" || part == "ei" || part == "ie" || part == "ou" || part == "ai")
continue;
}
var newSplitPos = i;
if (lastVowelPos + 1 < i) {
var lastPart = name.substr(i - 4, 4);
if (lastPart == "schr" || lastPart == "schr")
newSplitPos -= 4;
else {
var lastPart = name.substr(i - 3, 3);
if (lastPart == "sch")
newSplitPos -= 3;
else {
lastPart = name.substr(i - 2, 2);
if (lastPart == "ch" || lastPart == "ck" || lastPart == "br" || lastPart == "dr" || lastPart == "tr" || lastPart == "sp" || lastPart == "st" || lastPart == "th" || lastPart == "ph" || lastPart == "pf")
newSplitPos -= 2;
else
newSplitPos -= 1;
}
}
}
var part = name.substr(lastSplitPos, newSplitPos - lastSplitPos);
if (broken.length > 0)
broken += "-";
broken += part;
lastSplitPos = newSplitPos;
}
lastVowelPos = i;
}
}
var part = name.substr(lastSplitPos);
if (broken.length > 0)
broken += "-";
broken += part;
return broken;
}
similarName(s1, s2) {
function editDistance(s1, s2) {
s1 = s1.toLowerCase();
s2 = s2.toLowerCase();
var costs = new Array();
for (var i = 0; i <= s1.length; i++) {
var lastValue = i;
for (var j = 0; j <= s2.length; j++) {
if (i == 0)
costs[j] = j;
else {
if (j > 0) {
var newValue = costs[j - 1];
if (s1.charAt(i - 1) != s2.charAt(j - 1))
newValue = Math.min(Math.min(newValue, lastValue),
costs[j]) + 1;
costs[j - 1] = lastValue;
lastValue = newValue;
}
}
}
if (i > 0)
costs[s2.length] = lastValue;
}
return costs[s2.length];
}
var longer = s1;
var shorter = s2;
if (s1.length < s2.length) {
longer = s2;
shorter = s1;
}
var longerLength = longer.length;
if (longerLength == 0) {
return 1.0;
}
return (longerLength - editDistance(longer, shorter)) / parseFloat(longerLength);
}
}
<file_sep>/js/app.js
'use strict';
import { createApp } from 'https://unpkg.com/vue@3/dist/vue.esm-browser.js'
import {NameGen} from "./namegen.js";
// localStorage persistence
var STORAGE_KEY = 'name-generator'
var nameStorage = {
fetch: function () {
var nameArray = JSON.parse(localStorage.getItem(STORAGE_KEY) || '[]')
return nameArray.map(n => ({ name: n, favorite: true }))
},
save: function (names) {
var nameArray = names.filter(n => n.favorite).map(n => n.name);
localStorage.setItem(STORAGE_KEY, JSON.stringify(nameArray))
}
}
var nameGen = new NameGen('data/parts.txt');
const app = createApp({
el: '#app',
data() {
return {
templateName: "",
methodOptions: {
options: ["Similar", "Starts With", "Ends With"],
selectedIndex: 0
},
partsOptions: {
options: ["1 Syllable", "2 Syllables", "3 Syllables", "4 Syllables", "5 Syllables"],
selectedIndex: 2
},
names: nameStorage.fetch()
}
},
methods: {
generateName() {
var numParts = this.partsOptions.selectedIndex + 1;
var name = '';
var method = this.methodOptions.selectedIndex;
const SIMILAR = 0;
const STARTS_WITH = 1;
const ENDS_WITH = 2;
switch (method) {
case SIMILAR:
name = nameGen.generateSimilarName(this.templateName, numParts);
break;
case STARTS_WITH:
name = nameGen.generateName(this.templateName, numParts);
break;
case ENDS_WITH:
name = nameGen.generateNameReverse(this.templateName, numParts);
break;
}
this.names.push({ name: name, favorite: false });
},
setTemplate(entry) {
this.templateName = entry.name;
}
},
watch: {
names: {
handler(names) {
nameStorage.save(names);
},
deep: true
}
}
});
app.component('drop-down', {
props: ['options', 'selectedIndex'],
template: `<span class="plain-select">
<select @input="$emit('update:selectedIndex', $event.target.selectedIndex)">
<option v-for="(option, index) in options" :selected="index == selectedIndex ? 'selected' : ''">{{ option }}</option>
</select>
</span>`
});
app.component('name-entry', {
props: ['name', 'favorite'],
template: `<li>
<a href="#" :class="(favorite) ? 'favorite' : 'no-favorite'" @click="$emit('update:favorite', !favorite)">โ
</a>
<a href="#" @click="nameClicked">{{ name }}</a>
</li>`,
methods: {
nameClicked: function() {
this.$emit('name-clicked', this)
}
}
});
app.mount('#app');
<file_sep>/tests/namegen.test.js
import test from 'ava';
import { NameGen } from '../js/namegen.js';
test('randomInt returns a random integer within the given range', t => {
const nameGen = new NameGen();
const min = 1;
const max = 10;
const randomInt = nameGen.randomInt(min, max);
t.true(randomInt >= min && randomInt <= max);
});
|
5597079b77700b5cbaf6cda455ee2a9157084826
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
ahackel/name-generator
|
7e11822eda4feedd378ed20c7237f754c36e3f7d
|
95d58f4ae9f6a3d30950d65c6ee0c77a71b79dd3
|
refs/heads/master
|
<file_sep>import pandas as pd
SingleBracket1 = 15000
SingleBracket2 = 30000
MarriedJointlyBracket1 = 30000
MarriedJointlyBracket2 = 60000
MarriedSeparatelyBracket1 = 15000
MarriedSeparatelyBracket2 = 30000
HeadofHouseholdBracket1 = 15000
HeadofHouseholdBracket2 = 30000
def GeneralTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
TaxPercentage=0
if gSalary <= SingleBracket1:
Tax = (gSalary * 3.1) / 100
TaxPercentage = 3.1
elif (gSalary > SingleBracket1) & (gSalary <= SingleBracket2):
gSalary = gSalary - SingleBracket1
Tax = (SingleBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
TaxPercentage = 5.25
else:
gSalary = gSalary - SingleBracket1 - SingleBracket2
Tax = (SingleBracket1 * 3.1) / 100
Tax = Tax + (SingleBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
TaxPercentage = 5.7
return Tax, OriginalSalary - Tax, TaxPercentage
def MarriedJointlyTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= MarriedJointlyBracket1:
Tax = (gSalary * 3.1) / 100
TaxPercentage = 3.1
elif (gSalary > MarriedJointlyBracket1) & (gSalary <= MarriedJointlyBracket2):
gSalary = gSalary - MarriedJointlyBracket1
Tax = (MarriedJointlyBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
TaxPercentage = 5.25
else:
gSalary = gSalary - MarriedJointlyBracket1 - MarriedJointlyBracket2
Tax = (MarriedJointlyBracket1 * 3.1) / 100
Tax = Tax + (MarriedJointlyBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
TaxPercentage = 5.7
return Tax, OriginalSalary - Tax, TaxPercentage
def CalculateTax(gFile):
people_df = pd.DataFrame(pd.read_csv(gFile))
GeneralTax_df = people_df[(people_df.FilingStatus == "Single") | (people_df.FilingStatus == "Married Separately") | (people_df.FilingStatus == "Head of Household")]
MJTax_df = people_df[(people_df.FilingStatus == "Married Jointly")]
# Calculating Single tax
for index, row in GeneralTax_df.iterrows():
Name = row['Name']
FilingStatus = row['FilingStatus']
Salary = row['Salary']
Tax = GeneralTaxCalculator(Salary)
print(Name, ",", FilingStatus, ",", Salary, ",", Tax[0], ",", Tax[1], ",", Tax[2],"%")
# Calculating Married Jointly tax
for index, row in MJTax_df.iterrows():
Name = row['Name']
FilingStatus = row['FilingStatus']
Salary = row['Salary']
Tax = MarriedJointlyTaxCalculator(Salary)
print(Name, ",", FilingStatus, ",", Salary, ",", Tax[0], ",", Tax[1], ",", Tax[2],"%")
if __name__ == '__main__':
CalculateTax("data/people.csv")
<file_sep>#from TaxRate import TaxRate
#import numpy as np
import pandas as pd
# import datatable as dt
SingleBracket1 = 15000
SingleBracket2 = 30000
MarriedJointlyBracket1 = 30000
MarriedJointlyBracket2 = 60000
MarriedSeparatelyBracket1 = 15000
MarriedSeparatelyBracket2 = 30000
HeadofHouseholdBracket1 = 15000
HeadofHouseholdBracket2 = 30000
def SingleTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= SingleBracket1:
Tax = (gSalary * 3.1) / 100
elif (gSalary > SingleBracket1) & (gSalary <= SingleBracket2):
gSalary = gSalary - SingleBracket1
Tax = (SingleBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
else:
gSalary = gSalary - SingleBracket1 - SingleBracket2
Tax = (SingleBracket1 * 3.1) / 100
Tax = Tax + (SingleBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
return Tax, OriginalSalary - Tax
return Tax, OriginalSalary - Tax
def MarriedJointlyTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= MarriedJointlyBracket1:
Tax = (gSalary * 3.1) / 100
elif (gSalary > MarriedJointlyBracket1) & (gSalary <= MarriedJointlyBracket2):
gSalary = gSalary - MarriedJointlyBracket1
Tax = (MarriedJointlyBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
else:
gSalary = gSalary - MarriedJointlyBracket1 - MarriedJointlyBracket2
Tax = (MarriedJointlyBracket1 * 3.1) / 100
Tax = Tax + (MarriedJointlyBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
return Tax, OriginalSalary - Tax
def MarriedSeparatelyTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= MarriedSeparatelyBracket1:
Tax = (gSalary * 3.1) / 100
elif (gSalary > MarriedSeparatelyBracket1) & (gSalary <= MarriedSeparatelyBracket2):
gSalary = gSalary - MarriedSeparatelyBracket1
Tax = (MarriedSeparatelyBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
else:
# TODO 3
gSalary = gSalary - MarriedSeparatelyBracket1 - MarriedSeparatelyBracket2
Tax = (MarriedSeparatelyBracket1 * 3.1) / 100
Tax = Tax + (MarriedSeparatelyBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
return Tax, OriginalSalary - Tax
def HeadOfHouseholdTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= HeadofHouseholdBracket1:
Tax = (gSalary * 3.1) / 100
elif (gSalary > HeadofHouseholdBracket1) & (gSalary <= HeadofHouseholdBracket2):
gSalary = gSalary - HeadofHouseholdBracket1
Tax = (HeadofHouseholdBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
else:
gSalary = gSalary - HeadofHouseholdBracket1 - HeadofHouseholdBracket2
Tax = (HeadofHouseholdBracket1 * 3.1) / 100
Tax = Tax + (HeadofHouseholdBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
return Tax, OriginalSalary - Tax
def CalculateTax(gFile):
people_df = pd.DataFrame(pd.read_csv(gFile))
# taxRate_df = taxRate_df[taxRate_df.FilingStatus == gFilingStatus]
# taxRate_df = taxRate_df.sort_values(by=['FilingStatus', 'Low'])
# breaking people file into 4 groups based on the filing status
singleTax_df = people_df[(people_df.FilingStatus == "Single")]
MJTax_df = people_df[(people_df.FilingStatus == "Married Jointly")]
MSTax_df = people_df[(people_df.FilingStatus == "Married Separately")]
HeadTax_df = people_df[(people_df.FilingStatus == "Head of Household")]
# Calculating Single tax
for index, row in singleTax_df.iterrows():
Name = row['Name']
FilingStatus = row['FilingStatus']
Salary = row['Salary']
Tax = SingleTaxCalculator(Salary)
print(Name, ",", FilingStatus, ",", Salary, ",", Tax[0], ",", Tax[1])
# Calculating Married Jointly tax
for index, row in MJTax_df.iterrows():
Name = row['Name']
FilingStatus = row['FilingStatus']
Salary = row['Salary']
Tax = MarriedJointlyTaxCalculator(Salary)
print(Name, ",", FilingStatus, ",", Salary, ",", Tax[0], ",", Tax[1])
# Calculating Married Separately tax
for index, row in MSTax_df.iterrows():
Name = row['Name']
FilingStatus = row['FilingStatus']
Salary = row['Salary']
Tax = MarriedSeparatelyTaxCalculator(Salary)
print(Name, ",", FilingStatus, ",", Salary, ",", Tax[0], ",", Tax[1])
# Calculating Head of Household tax
for index, row in HeadTax_df.iterrows():
Name = row['Name']
FilingStatus = row['FilingStatus']
Salary = row['Salary']
Tax = HeadOfHouseholdTaxCalculator(Salary)
print(Name, ",", FilingStatus, ",", Salary, ",", Tax[0], ",", Tax[1])
if __name__ == '__main__':
CalculateTax("data/people.csv")
<file_sep>class TaxCalculatorManager(object):
def __init__(self):
pass
def CalculateTax(self, Salary, TaxRate):
return (Salary * TaxRate) / 100
<file_sep>#from TaxRate import TaxRate
#import numpy as np
#import pandas as pd
# import datatable as dt
SingleBracket1 = 15000
SingleBracket2 = 30000
MarriedJointlyBracket1 = 30000
MarriedJointlyBracket2 = 60000
MarriedSeparatelyBracket1 = 15000
MarriedSeparatelyBracket2 = 30000
HeadofHouseholdBracket1 = 15000
HeadofHouseholdBracket2 = 30000
def SingleTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= SingleBracket1:
Tax = (gSalary * 3.1) / 100
elif (gSalary > SingleBracket1) & (gSalary <= SingleBracket2):
gSalary = gSalary - SingleBracket1
Tax = (SingleBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
else:
gSalary = gSalary - SingleBracket1 - SingleBracket2
Tax = (SingleBracket1 * 3.1) / 100
Tax = Tax + (SingleBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
return Tax, OriginalSalary - Tax
def MarriedJointlyTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= MarriedJointlyBracket1:
Tax = (gSalary * 3.1) / 100
elif (gSalary > MarriedJointlyBracket1) & (gSalary <= MarriedJointlyBracket2):
gSalary = gSalary - MarriedJointlyBracket1
Tax = (MarriedJointlyBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
else:
# TODO 2
gSalary = gSalary - MarriedJointlyBracket1 - MarriedJointlyBracket2
Tax = (MarriedJointlyBracket1 * 3.1) / 100
Tax = Tax + (MarriedJointlyBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
return Tax, OriginalSalary - Tax
def MarriedSeparatelyTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= MarriedSeparatelyBracket1:
Tax = (gSalary * 3.1) / 100
elif (gSalary > MarriedSeparatelyBracket1) & (gSalary <= MarriedSeparatelyBracket2):
gSalary = gSalary - MarriedSeparatelyBracket1
Tax = (MarriedSeparatelyBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
else:
# TODO 3
gSalary = gSalary - MarriedSeparatelyBracket1 - MarriedSeparatelyBracket2
Tax = (MarriedSeparatelyBracket1 * 3.1) / 100
Tax = Tax + (MarriedSeparatelyBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
return Tax, OriginalSalary - Tax
def HeadOfHouseholdTaxCalculator(gSalary):
Tax = 0
OriginalSalary = gSalary
if gSalary <= HeadofHouseholdBracket1:
Tax = (gSalary * 3.1) / 100
elif (gSalary > HeadofHouseholdBracket1) & (gSalary <= HeadofHouseholdBracket2):
gSalary = gSalary - HeadofHouseholdBracket1
Tax = (HeadofHouseholdBracket1 * 3.1) / 100
Tax = Tax + (gSalary * 5.25) / 100
else:
gSalary = gSalary - HeadofHouseholdBracket1 - HeadofHouseholdBracket2
Tax = (HeadofHouseholdBracket1 * 3.1) / 100
Tax = Tax + (HeadofHouseholdBracket2 * 5.25) / 100
Tax = Tax + (gSalary * 5.7) / 100
return Tax, OriginalSalary - Tax
if __name__ == '__main__':
vName = "<NAME>"
vSalary = 50000
Tax = SingleTaxCalculator(vSalary)
# Tax[0] is the tax to be paid
# Tax[1] is the take home
print(vName, ", Single ,", vSalary, ",", Tax[0], ",", Tax[1])
Tax = MarriedJointlyTaxCalculator(vSalary)
print(vName, ", Married Jointly ,", vSalary, ",", Tax[0], ",", Tax[1])
# Assignment is to complete the TODO's
# 1. Complete the code for Single and Married Jointly for the 3rd tax braket
# 2. Update code for these two functions
Tax = MarriedSeparatelyTaxCalculator(vSalary)
print(vName, ", Married Separately ,", vSalary, ",", Tax[0], ",", Tax[1])
Tax = HeadOfHouseholdTaxCalculator(vSalary)
print(vName, ", Head Of Household ,", vSalary, ",", Tax[0], ",", Tax[1])
|
95539df45e8fd196e2647ef003b4e3d80cb8c093
|
[
"Python"
] | 4 |
Python
|
mmusleh75/taxcalc
|
655c5a24db0b2178484311cdc60a59821a22e7a7
|
b1916b9ccf298d948ad2353d1584f861e7e74e05
|
refs/heads/master
|
<file_sep>package dev.jasonhk.minecraft.time;
import java.time.Clock;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import java.time.temporal.ChronoUnit;
import java.time.temporal.Temporal;
import java.time.temporal.TemporalAdjuster;
import java.time.temporal.TemporalAmount;
import java.time.temporal.TemporalField;
import java.time.temporal.TemporalUnit;
import java.time.temporal.UnsupportedTemporalTypeException;
import java.util.HashMap;
import static java.time.temporal.ChronoField.HOUR_OF_DAY;
import static java.time.temporal.ChronoField.MINUTE_OF_HOUR;
import static java.time.temporal.ChronoField.NANO_OF_DAY;
import static java.time.temporal.ChronoField.NANO_OF_SECOND;
import static java.time.temporal.ChronoField.SECOND_OF_DAY;
import static java.time.temporal.ChronoField.SECOND_OF_MINUTE;
import org.apiguardian.api.API;
import lombok.NonNull;
import lombok.val;
import lombok.var;
import dev.jasonhk.minecraft.time.internal.GameTime;
import dev.jasonhk.minecraft.time.internal.RealTime;
import dev.jasonhk.minecraft.time.temporal.MinecraftField;
import dev.jasonhk.minecraft.time.temporal.MinecraftUnit;
import static dev.jasonhk.minecraft.time.internal.RealTime.HOURS_PER_DAY;
import static dev.jasonhk.minecraft.time.internal.RealTime.MINUTES_PER_DAY;
import static dev.jasonhk.minecraft.time.internal.RealTime.MINUTES_PER_HOUR;
import static dev.jasonhk.minecraft.time.internal.RealTime.NANOS_PER_DAY;
import static dev.jasonhk.minecraft.time.internal.RealTime.NANOS_PER_HOUR;
import static dev.jasonhk.minecraft.time.internal.RealTime.NANOS_PER_MICRO;
import static dev.jasonhk.minecraft.time.internal.RealTime.NANOS_PER_MILLI;
import static dev.jasonhk.minecraft.time.internal.RealTime.NANOS_PER_MINUTE;
import static dev.jasonhk.minecraft.time.internal.RealTime.NANOS_PER_SECOND;
import static dev.jasonhk.minecraft.time.internal.RealTime.SECONDS_PER_DAY;
import static dev.jasonhk.minecraft.time.internal.RealTime.SECONDS_PER_HOUR;
import static dev.jasonhk.minecraft.time.internal.RealTime.SECONDS_PER_MINUTE;
import static dev.jasonhk.minecraft.time.temporal.MinecraftField.TICK_OF_DAY;
@SuppressWarnings("unused")
@API(status = API.Status.STABLE, since = "0.0.1")
public final class MinecraftTime implements Temporal, TemporalAdjuster
{
//<editor-fold desc="Static Fields">
//<editor-fold desc="Time Constants">
/**
* The minimum supported {@code MinecraftTime}, {@code 0} tick. This equals to 06:00, the start
* of a Minecraft day.
*/
@API(status = API.Status.STABLE, since = "0.0.1")
public static final MinecraftTime MIN;
/**
* The time set when using the {@code /time set day} command in-game, {@code 1000} tick. This
* equals to 07:00 of a Minecraft day.
*/
@API(status = API.Status.STABLE, since = "0.0.1")
public static final MinecraftTime DAY;
/**
* The time set when using the {@code /time set noon} command in-game, {@code 6000} tick. This
* equals to 12:00 of a Minecraft day.
*/
@API(status = API.Status.STABLE, since = "0.0.1")
public static final MinecraftTime NOON;
/**
* The time set when using the {@code /time set sunset} command in-game, {@code 12000} tick.
* This equals to 18:00 of a Minecraft day.
*/
@API(status = API.Status.STABLE, since = "0.0.1")
public static final MinecraftTime SUNSET;
/**
* The time set when using the {@code /time set night} command in-game, {@code 13000} tick. This
* equals to 19:00 of a Minecraft day.
*/
@API(status = API.Status.STABLE, since = "0.0.1")
public static final MinecraftTime NIGHT;
/**
* The time set when using the {@code /time set midnight} command in-game, {@code 18000} tick.
* This equals to 00:00 of a Minecraft day.
*/
@API(status = API.Status.STABLE, since = "0.0.1")
public static final MinecraftTime MIDNIGHT;
/**
* The time set when using the {@code /time set sunrise} command in-game, {@code 23000} tick.
* This equals to 05:00 of a Minecraft day.
*/
@API(status = API.Status.STABLE, since = "0.0.1")
public static final MinecraftTime SUNRISE;
/**
* The maximum supported {@code MinecraftTime}, {@code 23999} tick. This equals to 05:59:56.4,
* the end of a Minecraft day.
*/
@API(status = API.Status.STABLE, since = "0.0.1")
public static final MinecraftTime MAX;
private static final HashMap<Integer, MinecraftTime> HOURS = new HashMap<>(HOURS_PER_DAY);
//</editor-fold>
/**
* The hour offset value of Minecraft's time system.
*/
static final int HOUR_OFFSET = 6;
/**
* Seconds per tick.
*/
static final double SECONDS_PER_TICK
= (double) RealTime.MINUTES_PER_DAY / GameTime.MINUTES_PER_GAME_DAY /
GameTime.TICKS_PER_SECOND;
/**
* Nanoseconds per tick.
*/
static final long NANOS_PER_TICK = (long) (SECONDS_PER_TICK * NANOS_PER_SECOND);
static final double TICKS_PER_NANO = SECONDS_PER_TICK / NANOS_PER_SECOND;
/**
* Ticks per second.
*/
static final double TICKS_PER_SECOND = 1 / SECONDS_PER_TICK;
/**
* Ticks per minute.
*/
static final double TICKS_PER_MINUTE = TICKS_PER_SECOND * SECONDS_PER_MINUTE;
/**
* Ticks per hour.
*/
static final int TICKS_PER_HOUR = (int) (TICKS_PER_MINUTE * MINUTES_PER_HOUR);
/**
* Ticks per day.
*/
static final int TICKS_PER_DAY = TICKS_PER_HOUR * HOURS_PER_DAY;
private static final long NANOS_OF_HOUR_OFFSET = HOUR_OFFSET * NANOS_PER_HOUR;
//</editor-fold>
static
{
for (int i = 0; i < HOURS_PER_DAY; i++)
{
val tickOfDay = TICKS_PER_HOUR * i;
HOURS.put(tickOfDay, new MinecraftTime(tickOfDay));
}
MIN = HOURS.get(0);
MAX = new MinecraftTime(23999);
DAY = HOURS.get(1000);
NOON = HOURS.get(6000);
SUNSET = HOURS.get(12000);
NIGHT = HOURS.get(13000);
MIDNIGHT = HOURS.get(18000);
SUNRISE = HOURS.get(23000);
}
//<editor-fold desc="Instance Fields">
/**
* The tick-of-day, from {@code 0} to {@code 23999}.
*/
private final short tickOfDay;
//</editor-fold>
private MinecraftTime(final int tickOfDay)
{
this.tickOfDay = (short) tickOfDay;
}
//<editor-fold desc="Static Methods">
//<editor-fold desc="Time Creators">
/**
* Obtains an instance of {@code MinecraftTime} from the current time of the system clock in the
* default time-zone.
* <p>
* This will query the {@linkplain Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current time.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing because the
* clock is hard-coded.
*
* @return The current Minecraft time using the system clock and default time-zone, not {@code null}.
*/
@NonNull
public static MinecraftTime now()
{
return now(Clock.systemDefaultZone());
}
/**
* Obtains an instance of {@code MinecraftTime} from the current time of the system clock in the
* specified time-zone.
* <p>
* This will query the {@linkplain Clock#system(ZoneId) system clock} to obtain the current
* time. Specifying the time-zone avoids dependence on the default time-zone.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing because the
* clock is hard-coded.
*
* @param zone The zone ID to use, not {@code null}.
* @return The current Minecraft time using the system clock, not {@code null}.
*/
@NonNull
public static MinecraftTime now(@NonNull final ZoneId zone)
{
return now(Clock.system(zone));
}
/**
* Obtains an instance of {@code MinecraftTime} from the current time of the specified clock.
* <p>
* This will query the specified clock to obtain the current time. Using this method allows the
* use of an alternate clock for testing. The alternate clock may be introduced using
* {@linkplain Clock dependency injection}.
*
* @param clock The clock to use, not {@code null}.
* @return The current Minecraft time, not {@code null}.
*/
@NonNull
public static MinecraftTime now(@NonNull final Clock clock)
{
val instant = clock.instant();
val zoneOffset = clock.getZone().getRules().getOffset(instant);
val localSecond = instant.getEpochSecond() + zoneOffset.getTotalSeconds();
val secondOfDay = Math.floorMod(localSecond, SECONDS_PER_DAY);
return ofSecondOfDay(secondOfDay);
}
/**
* Obtains an instance of {@code MinecraftTime} from an hour and minute.
* <p>
* This returns a {@code MinecraftTime} with the tick-of-day converted from the specified hour
* and minute.
*
* @param hour The hour-of-day to represent, from {@code 0} to {@code 23}.
* @param minute The minute-of-day to represent, from {@code 0} to {@code 59}.
* @return The Minecraft time, not {@code null}.
*/
@NonNull
public static MinecraftTime of(final int hour, final int minute)
{
return of(hour, minute, 0, 0);
}
/**
* Obtains an instance of {@code MinecraftTime} from an hour, minute and second.
* <p>
* This returns a {@code MinecraftTime} with the tick-of-day converted from the specified hour,
* minute and second.
*
* @param hour The hour-of-day to represent, from {@code 0} to {@code 23}.
* @param minute The minute-of-day to represent, from {@code 0} to {@code 59}.
* @param second The second-of-day to represent, from {@code 0} to {@code 59}.
* @return The Minecraft time, not {@code null}.
*/
@NonNull
public static MinecraftTime of(final int hour, final int minute, final int second)
{
return of(hour, minute, second, 0);
}
@NonNull
public static MinecraftTime of(
final int hour,
final int minute,
final int second,
final int nano)
{
HOUR_OF_DAY.checkValidValue(hour);
MINUTE_OF_HOUR.checkValidValue(minute);
SECOND_OF_MINUTE.checkValidValue(second);
NANO_OF_SECOND.checkValidValue(nano);
return create(hour, minute, second, nano);
}
/**
* Obtains an instance of {@code MinecraftTime} from a tick-of-day value.
* <p>
* This returns a {@code MinecraftTime} with the specified tick-of-day.
*
* @param tickOfDay The tick-of-day, from {@code 0} to {@code 23999}.
* @return The Minecraft time, not {@code null}.
*/
@NonNull
public static MinecraftTime ofTickOfDay(final long tickOfDay)
{
TICK_OF_DAY.checkValidValue(tickOfDay);
return create((int) tickOfDay);
}
/**
* Obtains an instance of {@code MinecraftTime} from a second-of-day value.
* <p>
* This returns a {@code MinecraftTime} with the tick-of-day converted from the specified
* second-of-day.
*
* @param secondOfDay The second-of-day, from {@code 0} to {@code 24 * 60 * 60 - 1}.
* @return The Minecraft time, not {@code null}.
*/
@NonNull
public static MinecraftTime ofSecondOfDay(final long secondOfDay)
{
SECOND_OF_DAY.checkValidValue(secondOfDay);
return ofNanoOfDay(secondOfDay * NANOS_PER_SECOND);
}
@NonNull
public static MinecraftTime ofNanoOfDay(final long nanoOfDay)
{
NANO_OF_DAY.checkValidValue(nanoOfDay);
return create((int) (Math.floorMod(nanoOfDay - NANOS_OF_HOUR_OFFSET, NANOS_PER_DAY) /
NANOS_PER_TICK));
}
@NonNull
private static MinecraftTime create(final int tickOfDay)
{
return HOURS.containsKey(tickOfDay)
? HOURS.get(tickOfDay)
: new MinecraftTime(tickOfDay);
}
@NonNull
private static MinecraftTime create(
final int hour,
final int minute,
final int second,
final int nano)
{
var nanoOfDay = hour * NANOS_PER_HOUR;
nanoOfDay += minute * NANOS_PER_MINUTE;
nanoOfDay += second * NANOS_PER_SECOND;
nanoOfDay += nano;
return ofNanoOfDay(nanoOfDay);
}
//</editor-fold>
//</editor-fold>
//<editor-fold desc="Instance Methods">
@Override
public long until(final Temporal endExclusive, final TemporalUnit unit)
{
return 0;
}
//<editor-fold desc="Time Adjuster">
@Override
public Temporal adjustInto(final Temporal temporal)
{
return temporal.isSupported(TICK_OF_DAY)
? temporal.with(TICK_OF_DAY, toTickOfDay())
: temporal.with(SECOND_OF_DAY, toSecondOfDay());
}
//</editor-fold>
//<editor-fold desc="Time Accessors">
@Override
public boolean isSupported(final TemporalField field)
{
return ((field instanceof ChronoField) || (field instanceof MinecraftField))
? field.isTimeBased()
: ((field != null) && field.isSupportedBy(this));
}
/**
* Gets the value of the specified field from this time as an {@code int}.
*
* @param field The field to get, not {@code null}.
* @return The value for the field.
*/
@Override
public int get(@NonNull final TemporalField field)
{
if ((field instanceof ChronoField) || (field instanceof MinecraftField))
{
return getInt(field);
}
return Temporal.super.get(field);
}
/**
* Gets the value of the specified field from this time as an {@code long}.
*
* @param field The field to get, not {@code null}.
* @return The value for the field.
*/
@Override
public long getLong(@NonNull final TemporalField field)
{
if (field instanceof ChronoField)
{
switch ((ChronoField) field)
{
case NANO_OF_DAY:
return toNanoOfDay();
case MICRO_OF_DAY:
return (toNanoOfDay() / NANOS_PER_MICRO);
default:
return getInt(field);
}
}
else if (field instanceof MinecraftField)
{
return getInt(field);
}
return field.getFrom(this);
}
private int getInt(final TemporalField field)
{
if (field instanceof ChronoField)
{
switch ((ChronoField) field)
{
case NANO_OF_SECOND:
return getNano();
case NANO_OF_DAY:
throw new UnsupportedTemporalTypeException(
"Invalid field `NanoOfDay` for get() method, use getLong() instead.");
case MICRO_OF_SECOND:
return (getNano() / NANOS_PER_MICRO);
case MICRO_OF_DAY:
throw new UnsupportedTemporalTypeException(
"Invalid field `MICRO_OF_DAY` for get() method, use getLong() instead.");
case MILLI_OF_SECOND:
return (getNano() / NANOS_PER_MILLI);
case MILLI_OF_DAY:
return (int) (toNanoOfDay() / NANOS_PER_MILLI);
case SECOND_OF_MINUTE:
return getSecond();
case SECOND_OF_DAY:
return toSecondOfDay();
case MINUTE_OF_HOUR:
return getMinute();
case MINUTE_OF_DAY:
return ((getHour() * MINUTES_PER_HOUR) + getMinute());
case HOUR_OF_AMPM:
return (getHour() % 12);
case HOUR_OF_DAY:
return getHour();
case CLOCK_HOUR_OF_AMPM:
{
val hour = getHour() % 12;
return (hour == 0) ? 12 : hour;
}
case CLOCK_HOUR_OF_DAY:
{
val hour = getHour();
return (hour == 0) ? 24 : hour;
}
case AMPM_OF_DAY:
return (getHour() / 12);
}
}
else if (field instanceof MinecraftField)
{
if (field == TICK_OF_DAY) { return toTickOfDay(); }
}
throw new UnsupportedTemporalTypeException("Unsupported field: " + field);
}
/**
* Gets the hour-of-day field.
*
* @return The hour-of-day, from {@code 0} to {@code 23}.
*/
public int getHour()
{
return (int) (toNanoOfDay() / NANOS_PER_HOUR);
}
/**
* Gets the minute-of-hour field.
*
* @return The minute-of-hour, from {@code 0} to {@code 59}.
*/
public int getMinute()
{
return (int) ((toNanoOfDay() % NANOS_PER_HOUR) / NANOS_PER_MINUTE);
}
/**
* Gets the second-of-minute field.
*
* @return The second-of-minute, from {@code 0} to {@code 59}.
*/
public int getSecond()
{
return (int) ((toNanoOfDay() % NANOS_PER_MINUTE) / NANOS_PER_SECOND);
}
public int getNano()
{
return (int) (toNanoOfDay() % NANOS_PER_SECOND);
}
/**
* Extracts the time as ticks of day, from {@code 0} to {@code 23999}.
*
* @return The tick-of-day equivalent to this time.
*/
public int toTickOfDay()
{
return tickOfDay;
}
/**
* Extracts the time as seconds of day, from {@code 0} to {@code 24 * 60 * 60 - 1}.
*
* @return The second-of-day equivalent to this time.
*/
public int toSecondOfDay()
{
return (int) (toNanoOfDay() / NANOS_PER_SECOND);
}
public long toNanoOfDay()
{
return Math.floorMod((tickOfDay * NANOS_PER_TICK) + NANOS_OF_HOUR_OFFSET, NANOS_PER_DAY);
}
//</editor-fold>
//<editor-fold desc="Time Manipulators">
@Override
public boolean isSupported(final TemporalUnit unit)
{
return ((unit instanceof ChronoUnit) || (unit instanceof MinecraftUnit))
? unit.isTimeBased()
: ((unit != null) && unit.isSupportedBy(this));
}
/**
* Returns an adjusted copy of this time.
* <p>
* This returns a {@code MinecraftTime}, based on this one, with the time adjusted. The
* adjustment takes place using the specified adjuster strategy object. Read the documentation
* of the adjuster to understand what adjustment will be made.
*
* @param adjuster The adjuster to use, not {@code null}.
* @return A {@code MinecraftTime} based on {@code this} with the adjustment made, not {@code null}.
*/
@Override
public MinecraftTime with(@NonNull final TemporalAdjuster adjuster)
{
return (adjuster instanceof MinecraftTime)
? (MinecraftTime) adjuster
: (MinecraftTime) adjuster.adjustInto(this);
}
@Override
public MinecraftTime with(final TemporalField field, final long newValue)
{
if (field instanceof ChronoField)
{
val _field = (ChronoField) field;
_field.checkValidValue(newValue);
switch (_field)
{
case SECOND_OF_MINUTE:
return withSecond((int) newValue);
case SECOND_OF_DAY:
}
}
return null;
}
public MinecraftTime withHour(final int hour)
{
if (hour == getHour()) { return this; }
HOUR_OF_DAY.checkValidValue(hour);
return create(hour, getMinute(), getSecond(), 0);
}
public MinecraftTime withMinute(final int minute)
{
if (minute == getMinute()) { return this; }
MINUTE_OF_HOUR.checkValidValue(minute);
return create(getHour(), minute, getSecond(), 0);
}
public MinecraftTime withSecond(final int second)
{
if (second == getSecond()) { return this; }
SECOND_OF_MINUTE.checkValidValue(second);
return create(getHour(), getMinute(), second, 0);
}
@Override
public MinecraftTime plus(final TemporalAmount amount)
{
return (MinecraftTime) amount.addTo(this);
}
@Override
public MinecraftTime plus(final long amountToAdd, final TemporalUnit unit)
{
if (unit instanceof ChronoUnit)
{
switch ((ChronoUnit) unit)
{
case SECONDS:
return plusSeconds(amountToAdd);
case MINUTES:
return plusMinutes(amountToAdd);
case HOURS:
return plusHours(amountToAdd);
case HALF_DAYS:
return plusHours(amountToAdd * 12);
}
}
else if (unit instanceof MinecraftUnit)
{
if (unit == MinecraftUnit.TICKS)
{
return plusTicks(amountToAdd);
}
throw new UnsupportedTemporalTypeException("Unsupported unit: " + unit);
}
return unit.addTo(this, amountToAdd);
}
public MinecraftTime plusHours(final long hoursToAdd)
{
if (hoursToAdd == 0) { return this; }
val oldHour = getHour();
val newHour = (int) Math.floorMod(oldHour + hoursToAdd, HOURS_PER_DAY);
return (newHour == oldHour)
? this
: create(newHour, getMinute(), getSecond(), 0);
}
public MinecraftTime plusMinutes(final long minutesToAdd)
{
if (minutesToAdd == 0) { return this; }
val oldMinuteOfDay = (getHour() * MINUTES_PER_HOUR) + getMinute();
val newMinuteOfDay = Math.floorMod(oldMinuteOfDay + minutesToAdd, MINUTES_PER_DAY);
if (newMinuteOfDay == oldMinuteOfDay) { return this; }
val newHour = (int) (newMinuteOfDay / MINUTES_PER_HOUR);
val newMinute = (int) (newMinuteOfDay % MINUTES_PER_HOUR);
return create(newHour, newMinute, getSecond(), 0);
}
public MinecraftTime plusTicks(final long ticksToAdd)
{
if (ticksToAdd == 0) { return this; }
val newTickOfDay = Math.floorMod(tickOfDay + ticksToAdd, TICKS_PER_DAY);
return (newTickOfDay == tickOfDay)
? this
: create((int) newTickOfDay);
}
public MinecraftTime plusSeconds(final long secondsToAdd)
{
if (secondsToAdd == 0) { return this; }
val oldSecondOfDay = toSecondOfDay();
val newSecondOfDay = Math.floorMod(oldSecondOfDay + secondsToAdd, SECONDS_PER_DAY);
if (newSecondOfDay == oldSecondOfDay) { return this; }
val newHour = (int) (newSecondOfDay / SECONDS_PER_HOUR);
val newMinute = (int) ((newSecondOfDay % SECONDS_PER_HOUR) / SECONDS_PER_MINUTE);
val newSecond = (int) (newSecondOfDay % SECONDS_PER_MINUTE);
return create(newHour, newMinute, newSecond, 0);
}
@Override
public MinecraftTime minus(final TemporalAmount amount)
{
return (MinecraftTime) amount.subtractFrom(this);
}
@Override
public MinecraftTime minus(final long amountToSubtract, final TemporalUnit unit)
{
return (amountToSubtract == Long.MIN_VALUE)
? plus(Long.MAX_VALUE, unit).plus(1, unit)
: plus(-amountToSubtract, unit);
}
//</editor-fold>
@Override
public boolean equals(final Object that)
{
if (that == this) { return true; }
if (that instanceof MinecraftTime)
{
val other = (MinecraftTime) that;
return (other.tickOfDay == tickOfDay);
}
return false;
}
@Override
public int hashCode()
{
return tickOfDay;
}
//</editor-fold>
}
<file_sep>import org.gradle.api.tasks.testing.logging.TestLogEvent;
group = "dev.jasonhk.minecraft.time"
version = "0.0.1"
allprojects {
repositories {
mavenCentral()
maven {
url = uri("https://plugins.gradle.org/m2/")
}
}
}
plugins {
java
jacoco
id("io.freefair.lombok") version "5.1.0"
}
dependencies {
implementation("org.apiguardian", "apiguardian-api", "1.1.0")
testImplementation("org.assertj", "assertj-core", "3.16.1")
testImplementation("org.junit.jupiter", "junit-jupiter", "5.6.2")
}
configure<JavaPluginConvention> {
sourceCompatibility = JavaVersion.VERSION_1_8
targetCompatibility = JavaVersion.VERSION_1_8
}
tasks.test {
useJUnitPlatform()
testLogging {
events(TestLogEvent.PASSED, TestLogEvent.SKIPPED, TestLogEvent.FAILED)
}
}
tasks.register("testCoverage") {
dependsOn(tasks.test)
finalizedBy(tasks.jacocoTestReport)
}
<file_sep>McTime4j
========
A Minecraft time construct and manipulate library for Java.
<file_sep>package dev.jasonhk.minecraft.time.internal;
import org.apiguardian.api.API;
/**
* A utility class containing constants of time in real life.
*
* @apiNote This class is for <strong>internal use only</strong>.
* @since 0.0.1
*/
@API(status = API.Status.INTERNAL,
since = "0.0.1",
consumers = { "dev.jasonhk.minecraft.time.*" })
public final class RealTime
{
/**
* Hours per day.
*/
public static final int HOURS_PER_DAY = 24;
/**
* Minutes per hour.
*/
public static final int MINUTES_PER_HOUR = 60;
/**
* Seconds per minute.
*/
public static final int SECONDS_PER_MINUTE = 60;
/**
* Milliseconds per second.
*/
public static final int MILLIS_PER_SECOND = 1_000;
/**
* Microseconds per second.
*/
public static final int MICROS_PER_SECOND = 1_000_000;
/**
* Nanoseconds per second.
*/
public static final long NANOS_PER_SECOND = 1_000_000_000;
/**
* Minutes per day.
*/
public static final int MINUTES_PER_DAY = MINUTES_PER_HOUR * HOURS_PER_DAY;
/**
* Seconds per hour.
*/
public static final int SECONDS_PER_HOUR = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
/**
* Seconds per day.
*/
public static final int SECONDS_PER_DAY = SECONDS_PER_HOUR * HOURS_PER_DAY;
/**
* Nanoseconds per microsecond.
*/
public static final int NANOS_PER_MICRO = (int) (NANOS_PER_SECOND / MICROS_PER_SECOND);
/**
* Nanoseconds per millisecond.
*/
public static final int NANOS_PER_MILLI = (int) (NANOS_PER_SECOND / MILLIS_PER_SECOND);
/**
* Nanoseconds per minute.
*/
public static final long NANOS_PER_MINUTE = NANOS_PER_SECOND * SECONDS_PER_MINUTE;
/**
* Nanoseconds per hour.
*/
public static final long NANOS_PER_HOUR = NANOS_PER_MINUTE * MINUTES_PER_HOUR;
/**
* Nanoseconds per day.
*/
public static final long NANOS_PER_DAY = NANOS_PER_HOUR * HOURS_PER_DAY;
private RealTime()
{
throw new UnsupportedOperationException(
"This is a utility class and cannot be instantiated.");
}
}
<file_sep>rootProject.name = "JMinecraftTime"
|
2181482fd89bb44b45fdeeac053af1ee9f92ed67
|
[
"Markdown",
"Java",
"Kotlin"
] | 5 |
Java
|
JasonHK-Minecraft/JMinecraftTime
|
8f8bf59d3aefe84a949ddf05a141ea21a1c950de
|
7f0a92a6bcf2a4f4741edaa8085c45d46493656a
|
refs/heads/master
|
<file_sep>## ๆฆ่ฟฐ
wxpaysandbox ๆฏไธๅฅๅผๆบ็่พ
ๅฉ่ฟ่กๅพฎไฟกๆฏไปๆฒ็ฎฑ้ชๆถ็็จๅบใ
## ๅธฎๅฉไธญๅฟ
- [ไฝ้ชไธญๅฟ](http://sd.henan28.com/)
- [ๆฅ่ฏข้ชๆถ่ฟๅบฆ](https://pay.weixin.qq.com/wiki/doc/api/tools/sp_coupon.php?chapter=15_6&index=4)
<file_sep><?php
date_default_timezone_set('PRC');
define('WEB_PATH', str_replace('\\', '/', dirname(__FILE__)) .'/');
require_once 'WxPay.Api.php';
$mch_id = isset($_POST['mchid']) ? $_POST['mchid'] : '';
$key = isset($_POST['key']) ? $_POST['key'] : '';
$api = new WxPayApi($mch_id,$key);
$api->run();<file_sep><?php
require_once 'WxPay.Data.php';
/**
*
*/
class WxPayApi
{
private $mchid = '';
private $key = '';
private $orderid = '';
private $msg = array();
function __construct($mchid,$key)
{
$this->mchid = $mchid;
$this->key = $key;
}
public function run() {
if(empty($this->mchid) || empty($this->key)) {
$this->msg[] = 'ๅๆทๅท ๅ API ็ง้ฅไธ่ฝไธบ็ฉบ!';
$this->response();
}
//่ทๅๆฒ็ฎฑ็ง้ฅ
$flag = $this->getKey();
if(!$flag) $this->response();
//ๆฏไป
$orderid = $this->order();
if(!$orderid) $this->response();
//่ฎขๅๆฅ่ฏข
$flag = $this->orderquery($orderid);
if(!$flag) $this->response();
//้ๆฌพ
$flag = $this->refund($orderid);
if(!$flag) $this->response();
//้ๆฌพๆฅ่ฏข
$flag = $this->refundquery($orderid);
if(!$flag) $this->response();
//ไธ่ฝฝๅฏน่ดฆๅ
$flag = $this->downbill();
$this->response();
}
//่ทๅๆฒ็ฎฑ็ง้ฅ
private function getKey() {
$input = new \WxPayDataBase();
$input = $this->common($input);
$xml = $input->ToXml();
$url = "https://api.mch.weixin.qq.com/sandboxnew/pay/getsignkey";
$response = $this->postXmlCurl($xml, $url, false);
$result = $input->FromXml($response);
if(!is_array($result) || !isset($result['sandbox_signkey'])) {
$this->msg[] = $result;
return false;
}
$this->key = $result['sandbox_signkey'];
$this->msg[] = 'ๆฒ็ฎฑ็ง้ฅๆๅ';
return true;
}
//ๆซ็ ๆฏไป
private function order() {
$input = new \WxPayDataBase();
$order_id = $mchid.date("YmdHis").rand(1000,9999);
$input->setValues('body',$order_id);
$input->setValues('attach',$order_id);
$input->setValues('goods_tag',$order_id);
$input->setValues('out_trade_no',$order_id);
$input->setValues('total_fee',552);
$input->setValues('time_start',date("YmdHis"));
$input->setValues('time_expire',date("YmdHis", time() + 600));
$input->setValues('notify_url','http://paysdk.weixin.qq.com/example/notify.php');
$input->setValues('trade_type','NATIVE');
$input->setValues('product_id',$order_id);
$input->setValues('spbill_create_ip',$_SERVER['REMOTE_ADDR']);
$input = $this->common($input);
$xml = $input->ToXml();
$url = "https://api.mch.weixin.qq.com/sandboxnew/pay/unifiedorder";
$response = $this->postXmlCurl($xml, $url, false);
$result = $input->FromXml($response);
if(!is_array($result) || !isset($result['code_url'])) {
$this->msg[] = $result;
return false;
}
@file_get_contents("http://paysdk.weixin.qq.com/example/qrcode.php?data=".urlencode($result['code_url']));
$this->msg[] = '็ๆ่ฎขๅๆๅ';
return $order_id;
}
//่ฎขๅๆฅ่ฏข
private function orderquery($orderid) {
$input = new \WxPayDataBase();
$input->setValues('out_trade_no',$orderid);
$input = $this->common($input);
$xml = $input->ToXml();
$url = "https://api.mch.weixin.qq.com/sandboxnew/pay/orderquery";
$response = $this->postXmlCurl($xml, $url, false);
$result = $input->FromXml($response);
if(!is_array($result) || !(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS")) {
$this->msg[] = $result;
return false;
}
$this->msg[] = '่ฎขๅๆฅ่ฏขๆๅ';
return true;
}
private function refund($orderid) {
$input = new \WxPayDataBase();
$input->setValues('out_trade_no',$orderid);
$input->setValues('out_refund_no',$orderid);
$input->setValues('total_fee',552);
$input->setValues('refund_fee',552);
$input->setValues('op_user_id',$this->mchid);
$input = $this->common($input);
$xml = $input->ToXml();
$url = "https://api.mch.weixin.qq.com/sandboxnew/pay/refund";
$response = $this->postXmlCurl($xml, $url, false);
$result = $input->FromXml($response);
if(!is_array($result) || !(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS")) {
$this->msg[] = $result;
return false;
}
$this->msg[] = '้ๆฌพๆๅ';
return true;
}
private function refundquery($orderid) {
$input = new \WxPayDataBase();
$input->setValues('out_trade_no',$orderid);
$input->setValues('out_refund_no',$orderid);
$input->setValues('total_fee',552);
$input->setValues('refund_fee',552);
$input->setValues('op_user_id',$this->mchid);
$input = $this->common($input);
$xml = $input->ToXml();
$url = "https://api.mch.weixin.qq.com/sandboxnew/pay/refundquery";
$response = $this->postXmlCurl($xml, $url, false);
$result = $input->FromXml($response);
if(!is_array($result) || !(array_key_exists("return_code", $result) && array_key_exists("result_code", $result) && $result["return_code"] == "SUCCESS" && $result["result_code"] == "SUCCESS")) {
$this->msg[] = $result;
return false;
}
$this->msg[] = '้ๆฌพๆฅ่ฏขๆๅ';
return true;
}
private function downbill() {
$input = new \WxPayDataBase();
$input->setValues('bill_date',date('Ymd'));
$input->setValues('bill_type','ALL');
$input = $this->common($input);
$xml = $input->ToXml();
$url = "https://api.mch.weixin.qq.com/sandboxnew/pay/downloadbill";
$response = $this->postXmlCurl($xml, $url, false);
if(substr($response, 0 , 5) == "<xml>"){
$this->msg[] = $response;
return false;
}
$this->msg[] = 'ไธ่ฝฝๅฏน่ดฆๅๆๅ';
return true;
}
private function common($input) {
$input->setValues('mch_id',$this->mchid);
$input->setValues('nonce_str',$this->getNonceStr());
$input->SetSign($this->key);
return $input;
}
public function response() {
$data = array(
'msg' => implode("<br>", $this->msg),
);
exit(json_encode($data));
}
private function getNonceStr($length = 32)
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str ="";
for ( $i = 0; $i < $length; $i++ ) {
$str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
}
return $str;
}
private function postXmlCurl($xml, $url, $useCert = false, $second = 30)
{
$ch = curl_init();
//่ฎพ็ฝฎ่ถ
ๆถ
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
//ๅฆๆๆ้
็ฝฎไปฃ็่ฟ้ๅฐฑ่ฎพ็ฝฎไปฃ็
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,TRUE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);//ไธฅๆ ผๆ ก้ช
//่ฎพ็ฝฎheader
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//่ฆๆฑ็ปๆไธบๅญ็ฌฆไธฒไธ่พๅบๅฐๅฑๅนไธ
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//postๆไบคๆนๅผ
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//่ฟ่กcurl
$data = curl_exec($ch);
//่ฟๅ็ปๆ
if($data){
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
$string = curl_error($ch);
curl_close($ch);
return "curlๅบ้๏ผ้่ฏฏ็ :$error".$string;
}
}
}
|
94f15804f3f9d962e923a129af39f4adfc5363a9
|
[
"Markdown",
"PHP"
] | 3 |
Markdown
|
xiyuanwanngzi/wxpaysandbox
|
38358cfff009d846a71d369bf1a74ea25926ad99
|
5958fc2f719b8217980190f677613989051aefd9
|
refs/heads/master
|
<file_sep>//
// GameViewController.swift
// WordBuzzer
//
// Created by <NAME> on 10/21/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
struct WordToShow {
var wordInLanguageOne: String
var wordInLanguageTwo: String
var wordToDisplay: String
}
class GameViewController: UIViewController {
@IBOutlet weak var playerFourButton: UIButton!
@IBOutlet weak var playerThreeButton: UIButton!
@IBOutlet weak var playerTwoButton: UIButton!
@IBOutlet weak var playerOneButton: UIButton!
@IBOutlet weak var labelOne: UILabel!
@IBAction func unwindToGameScreen(segue:UIStoryboardSegue) {
}
@IBAction func tapPlayerOneButton(_ sender: Any) {
handleButtonTap(buttonTag: playerOneButton.tag)
}
@IBAction func tapPlayerTwoButton(_ sender: Any) {
handleButtonTap(buttonTag: playerTwoButton.tag)
}
@IBAction func tapPlayerThreeButton(_ sender: Any) {
handleButtonTap(buttonTag: playerThreeButton.tag)
}
@IBAction func tapPlayerFourButton(_ sender: Any) {
handleButtonTap(buttonTag: playerFourButton.tag)
}
var labelTwo: UILabel?
let labelWidth = 250
let labelHeight = 32
var wordsArrayFromJSON = [Word]()
let amountOfWords: Int = 5
var amountOfShownWords: Int = 0
var wordToShow: WordToShow?
var wordsToShowArray = [WordToShow]()
var correctAnswers = [Int]()
var showNextWord: Bool = false
override func viewDidLoad() {
super.viewDidLoad()
if let w = Word.fetchJson() {
wordsArrayFromJSON = w
}
}
override func viewWillAppear(_ animated: Bool) {
amountOfShownWords = 0
correctAnswers = []
for _ in 0 ... 3 {
correctAnswers.append(0)
}
labelTwo = UILabel(frame: CGRect(x: -labelWidth, y: Int(self.view.frame.height / 2 + 25), width: labelWidth, height: labelHeight))
labelTwo?.textAlignment = .right
labelTwo?.text = "LabelTwo"
labelTwo?.backgroundColor = .clear
labelTwo?.font = UIFont.systemFont(ofSize: 28)
labelTwo?.numberOfLines = 0
// labelTwo?.sizeToFit()
self.view.addSubview(labelTwo!)
getWordsToShow()
}
override func viewWillDisappear(_ animated: Bool) {
self.labelTwo?.removeFromSuperview()
}
func handleButtonTap(buttonTag: Int) {
showNextWord = true
if let w = self.wordToShow {
let correctAnswer = self.isCorrectAnswer(word: w)
updateUIView(correctAnswer: correctAnswer, buttonTag: buttonTag)
}
}
func updateUIView(correctAnswer: Bool, buttonTag: Int) {
playerOneButton.isEnabled = false
playerTwoButton.isEnabled = false
playerThreeButton.isEnabled = false
playerFourButton.isEnabled = false
playerOneButton.backgroundColor = .gray
playerTwoButton.backgroundColor = .gray
playerThreeButton.backgroundColor = .gray
playerFourButton.backgroundColor = .gray
if correctAnswer {
labelOne.textColor = .green
labelTwo?.textColor = .green
self.correctAnswers[buttonTag] += 1
} else {
labelOne.textColor = .red
labelTwo?.textColor = .red
self.correctAnswers[buttonTag] -= 1
}
}
func getWordsToShow() {
if amountOfShownWords < amountOfWords {
amountOfShownWords += 1
getWordToShow()
} else {
performSegue(withIdentifier: "segueToFinalScreen", sender: self)
}
}
func getWordToShow() {
var wordsArray = [Word]()
var randomNumber = 0
for _ in 0 ... 2 {
randomNumber = Int.random(in: 0 ..< wordsArrayFromJSON.count)
wordsArray.append(wordsArrayFromJSON[randomNumber])
}
wordsToShowArray = []
for _ in 0 ... 2 {
randomNumber = Int.random(in: 0 ... 2)
wordToShow = WordToShow(wordInLanguageOne: wordsArray[0].text_eng ?? "", wordInLanguageTwo: wordsArray[0].text_spa ?? "", wordToDisplay: wordsArray[randomNumber].text_spa ?? "")
wordsToShowArray.append(wordToShow!)
print(wordToShow?.wordInLanguageOne as Any, " ", wordToShow?.wordInLanguageTwo as Any, " ", wordToShow?.wordToDisplay as Any)
}
showWord()
}
func showWord() {
labelOne.textColor = .gray
labelTwo?.textColor = .gray
playerOneButton.isEnabled = true
playerTwoButton.isEnabled = true
playerThreeButton.isEnabled = true
playerFourButton.isEnabled = true
playerOneButton.backgroundColor = .cyan
playerTwoButton.backgroundColor = .magenta
playerThreeButton.backgroundColor = .yellow
playerFourButton.backgroundColor = .blue
if wordsToShowArray.count > 0 {
wordToShow = wordsToShowArray[0]
wordsToShowArray.remove(at: 0)
labelOne.text = wordToShow?.wordInLanguageOne
labelTwo?.text = wordToShow?.wordToDisplay
labelTwo?.frame = CGRect(x: -labelWidth, y: Int(self.view.frame.height / 2 + 25), width: labelWidth, height: labelHeight)
self.addAnimation()
} else {
getWordsToShow()
}
}
func addAnimation() {
DispatchQueue.main.async {
UIView.animate(withDuration: 5.0, delay: 0.0, options: .curveEaseInOut, animations: {
self.labelTwo?.center.x = self.view.frame.width + CGFloat(self.labelWidth)
}, completion: { (finished: Bool) in
if self.showNextWord {
self.showNextWord = false
self.getWordsToShow()
} else {
self.showWord()
}
})
}
}
func isCorrectAnswer(word: WordToShow) -> Bool {
return word.wordInLanguageTwo == word.wordToDisplay
}
// MARK: - Navigation
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "segueToFinalScreen" {
if let destinationVC = segue.destination as? FinalViewController {
destinationVC.correctAnswers = correctAnswers
}
}
}
}
<file_sep>//
// WelcomeViewController.swift
// WordBuzzer
//
// Created by <NAME> on 10/21/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
class WelcomeViewController: UIViewController {
@IBOutlet weak var welcomeLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
welcomeLabel.text = "Welcome" + "\n" + "to" + "\n" + "WordBuzzer"
}
}
<file_sep># Word Buzzer
<file_sep>//
// FinalViewController.swift
// WordBuzzer
//
// Created by <NAME> on 10/21/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import UIKit
class FinalViewController: UIViewController {
var correctAnswers: [Int]?
@IBOutlet weak var playerOneResult: UILabel!
@IBOutlet weak var playerFourResult: UILabel!
@IBOutlet weak var playerThreeResult: UILabel!
@IBOutlet weak var playerTwoResult: UILabel!
@IBAction func playAgain(_ sender: Any) {
performSegue(withIdentifier: "unwindSegueToGameScreen", sender: self)
}
override func viewDidLoad() {
super.viewDidLoad()
if let answers = correctAnswers {
playerOneResult.text = "Player 1:\t\(answers[0])"
playerTwoResult.text = "Player 2:\t\(answers[1])"
playerThreeResult.text = "Player 3:\t\(answers[2])"
playerFourResult.text = "Player 4:\t\(answers[3])"
}
}
}
<file_sep>//
// Word.swift
// WordBuzzer
//
// Created by <NAME> on 10/21/18.
// Copyright ยฉ 2018 <NAME>. All rights reserved.
//
import Foundation
import UIKit
private let vocabularyURL = "https://gist.githubusercontent.com/DroidCoder/7ac6cdb4bf5e032f4c737aaafe659b33/raw/baa9fe0d586082d85db71f346e2b039c580c5804/words.json"
struct Word: Codable {
var text_eng: String?
var text_spa: String?
static func fetchJson() -> [Word]? {
if let url = URL(string: vocabularyURL) {
do {
let data = try Data(contentsOf: url)
let decoder = JSONDecoder()
let jsonData = try decoder.decode([Word].self, from: data)
return jsonData
} catch DecodingError.dataCorrupted {
print("Data corrupted")
} catch {
print("Fetching JSON Error")
}
}
return nil
}
}
|
a83cb3726b54bfa9a78ee1fc968cc0d2e34771a8
|
[
"Swift",
"Markdown"
] | 5 |
Swift
|
NatalyT/WordBuzzer
|
125761195d38c61e9fe325f597875c757659fef8
|
da71596c2863ecdbeb17f8e26cfc7be1f06534fd
|
refs/heads/main
|
<repo_name>alexanderankin/PenguinPlundgePortA2<file_sep>/build.gradle
plugins {
id 'java'
id 'application'
id 'org.beryx.jlink' version '2.26.0'
id 'com.google.osdetector' version '1.7.3'
}
tasks.register('hi') {
doLast {
println osdetector.os
}
}
java {
sourceCompatibility JavaVersion.VERSION_17
targetCompatibility JavaVersion.VERSION_17
}
def jlinkName = 'ppp'
jlink {
options.set(['--strip-debug', '--compress', '2', '--no-header-files', '--no-man-pages'])
launcher { name = jlinkName }
imageName.set jlinkName
imageZip.set(new File(project.buildDir, jlinkName + '.zip'))
// reactor needs some help to work with modules (javafx)
mergedModule {
excludeProvides servicePattern: 'io.micrometer.context.ContextAccessor'
excludeProvides servicePattern: 'reactor.blockhound.integration.BlockHoundIntegration'
}
}
tasks.register('buildRelease') { dependsOn('jlinkZip') }
application {
mainModule.set 'PenguinPlundgePortA2.main'
mainClass.set 'com.twopercent.main.Main'
}
repositories {
mavenCentral()
}
sourceSets {
main {
java {
srcDir 'src/'
}
resources.srcDir 'res/'
}
}
def fxVersion = '20.0.1'
def os = osdetector.os == 'windows' ? 'win' : 'linux'
dependencies {
implementation("org.openjfx:javafx-base:$fxVersion:$os")
implementation("org.openjfx:javafx-controls:$fxVersion:$os")
implementation("org.openjfx:javafx-fxml:$fxVersion:$os")
implementation("org.openjfx:javafx-swing:$fxVersion:$os")
implementation("org.openjfx:javafx-media:$fxVersion:$os")
implementation("org.openjfx:javafx-graphics:$fxVersion:$os")
implementation('io.projectreactor:reactor-core:3.5.5')
annotationProcessor('org.projectlombok:lombok:1.18.26')
implementation('org.projectlombok:lombok:1.18.26')
implementation('org.slf4j:slf4j-api:2.0.4')
implementation('ch.qos.logback:logback-classic:1.4.7')
}
def extraExports = [
'javafx.base/com.sun.javafx.collections',
'javafx.graphics/com.sun.glass.events',
]
def exportTo = application.mainModule.get()
tasks.withType(JavaCompile).configureEach {
extraExports.each { export ->
options.compilerArgs += ['--add-exports', "$export=$exportTo"]
}
}
tasks.withType(JavaExec).configureEach {
extraExports.each { export ->
jvmArgs(['--add-exports', "$export=$exportTo"])
}
}
<file_sep>/settings.gradle
rootProject.name = 'PenguinPlundgePortA2'
<file_sep>/src/module-info.java
module PenguinPlundgePortA2.main {
requires javafx.controls;
requires javafx.fxml;
requires lombok;
requires reactor.core;
requires org.slf4j;
requires java.sql;
requires java.desktop;
requires javafx.media;
opens com.twopercent.main to javafx.fxml;
exports com.twopercent.main;
opens com.valgriz.screen to javafx.fxml;
exports com.valgriz.screen;
}
<file_sep>/src/com/twopercent/render/SoundPlayer.java
package com.twopercent.render;
import javafx.scene.media.AudioClip;
import javafx.scene.media.Media;
import java.util.Map;
import java.util.stream.Collectors;
public class SoundPlayer {
private static Media bounce = new Media(SoundPlayer.class.getResource("/res/sounds/BounceEffect.mp3").toString());
private static Media button = new Media(SoundPlayer.class.getResource("/res/sounds/ButtonSound.mp3").toString());
private static Media fallingPlatform = new Media(SoundPlayer.class.getResource("/res/sounds/FallingPlatform.mp3")
.toString());
private static Media starSound = new Media(SoundPlayer.class.getResource("/res/sounds/StarSound.mp3").toString());
private static double volume = 1.0;
private static final Map<Media, Double> volumes = Map.ofEntries(
Map.entry(bounce, volume),
Map.entry(button, volume / 10),
Map.entry(fallingPlatform, volume / 10),
Map.entry(starSound, volume / 20)
);
private static final Map<Media, AudioClip> playerMap = volumes.entrySet().stream()
.collect(Collectors.toMap(Map.Entry::getKey, entry -> {
var m = new AudioClip(entry.getKey().getSource());
m.setVolume(entry.getValue());
return m;
}));
// private static Media
public static void playBounce() {
playerMap.get(bounce).play();
}
public static void playButton() {
playerMap.get(button).play();
}
public static void playFallingPlatform() {
playerMap.get(fallingPlatform).play();
}
public static void playStarSound() {
playerMap.get(starSound).play();
}
public static void volumeControl(int i) {
if (i == 0) {
unmute();
} else {
mute();
}
}
public static void mute() {
playerMap.values().forEach(e -> e.setVolume(0));
}
public static void unmute() {
playerMap.forEach((key, value) -> value.setVolume(volumes.get(key)));
}
}
|
afb389471bfc496f53a34eb91eb1c2085de9b046
|
[
"Java",
"Gradle"
] | 4 |
Gradle
|
alexanderankin/PenguinPlundgePortA2
|
401d01271e37a22080d4480086426cdddc0999c9
|
ef1d0f9f0b31f98de73c582228f7cd8f6b1aaf40
|
refs/heads/master
|
<file_sep># grunt-requirejs-injector
> Inject RequireJS dependencies on definition.
## Getting Started
This plugin requires Grunt `~0.4.5`
If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide, as it explains how to create a [Gruntfile](http://gruntjs.com/sample-gruntfile) as well as install and use Grunt plugins. Once you're familiar with that process, you may install this plugin with this command:
```shell
npm install grunt-requirejs-injector --save-dev
```
Once the plugin has been installed, it may be enabled inside your Gruntfile with this line of JavaScript:
```js
grunt.loadNpmTasks('grunt-requirejs-injector');
```
## requirejs_injector task
You can convert a RequireJS application to a single script, concatenate modules and inject his dependencies on definition.
### Overview
In your project's Gruntfile, add a section named `requirejs_injector` to the data object passed into `grunt.initConfig()`.
```js
grunt.initConfig({
requirejs_injector: {
your_target: {
src: src_target,
dest: dest_target
},
},
});
```
### Usage Examples
#### Simple Example
In this example, compile `test/fixtures/print/main.js` to `tmp/print.js`.
```js
grunt.initConfig({
requirejs_injector: {
print: {
src: 'test/fixtures/print/main.js',
dest: 'tmp/print.js'
}
},
});
```
## Contributing
In lieu of a formal styleguide, take care to maintain the existing coding style. Add unit tests for any new or changed functionality. Lint and test your code using [Grunt](http://gruntjs.com/).
## Release History
_(Nothing yet)_
<file_sep>/*
* grunt-requirejs-injector
* https://github.com/cuarti/grunt-requirejs-injector
*
* Copyright (c) 2015 <NAME>
* Licensed under the MIT license.
*/
'use strict';
var requirejs = require('requirejs');
var DEFINE_REGEX = /^\s*define\s*\(\s*[^\]]*]\s*,\s*/;
var END_REGEX = /}\);\s*$/;
var COMMA_REGEX = /['"]/g;
//TODO: put separator option
//TODO: put basePath option
//TODO: compile more than one file and concatenate it
//TODO: put platform option - string[] (browser | node)
module.exports = function(grunt) {
grunt.registerMultiTask('requirejs_injector', 'Inject RequireJS dependencies on definition.', function() {
var done = this.async();
var dest = this.data.dest;
//console.log(this.data.src);
var config = {
baseUrl: '.',
name: this.data.src,
optimize: 'none',
out: function(compiled) {
grunt.file.write(dest, compiled);
},
onBuildWrite: convert
};
var i = config.name.lastIndexOf('/');
if(i >= 0) {
config.baseUrl = config.name.substring(0, i);
config.name = config.name.substring(i + 1);
}
var le = config.name.length - 3;
if(config.name.substring(le) === '.js') {
config.name = config.name.substring(0, le);
}
console.log(config.baseUrl === getBasePath(this.data.src));
requirejs.optimize(config, function(response) {
grunt.verbose.writeln(response);
grunt.log.ok('File ' + dest + ' created.');
done();
}, function(err) {
done(err);
});
//// Merge task-specific and/or target-specific options with these defaults.
//var options = this.options({
// punctuation: '.',
// separator: ', '
//});
//
//// Iterate over all specified file groups.
//this.files.forEach(function(f) {
// // Concat specified files.
// var src = f.src.filter(function(filepath) {
// // Warn on and remove invalid source files (if nonull was set).
// if(!grunt.file.exists(filepath)) {
// grunt.log.warn('Source file "' + filepath + '" not found.');
// return false;
// } else {
// return true;
// }
// }).map(function(filepath) {
// // Read file source.
// return grunt.file.read(filepath);
// }).join(grunt.util.normalizelf(options.separator));
//
// // Handle options.
// src += options.punctuation;
//
// // Write the destination file.
// grunt.file.write(f.dest, src);
//
// // Print a success message.
// grunt.log.writeln('File "' + f.dest + '" created.');
//});
function convert(name, path, content) {
//TODO: relative paths for modules
var match = DEFINE_REGEX.exec(content);
if(match) {
name = name.replace('/', '_');
var define = match[0];
var args = define.substring(define.indexOf('[') + 1);
args = args.substring(0, args.indexOf(']')).replace(COMMA_REGEX, '').split(',').map(function(arg) {
//console.log(arg);
return arg;
}).join(',');
content = 'var ' + name + ' = (' + content.substring(define.length).replace(END_REGEX, '})(' + args + ');');
}
return content;
}
});
function getBasePath(path) {
var i = path.lastIndexOf('/');
return i >= 0 ? path.substring(0, i) : path;
}
function getFileName(path) {
var i = path.lastIndexOf('/');
if(i >= 0) {
path = path.substring(i + 1);
}
var length = path.length - 3;
return path.substring(length) === '.js' ? path.substring(0, length) : path;
}
};
<file_sep>
define([
'sum/target',
'sum/expected',
'deduct/target',
'deduct/expected',
'multiply/target',
'multiply/expected',
'divide/target',
'divide/expected'
], function(
sumTarget,
sumExpected,
deductTarget,
deductExpected,
multiplyTarget,
multiplyExpected,
divideTarget,
divideExpected
) {
console.log(sumTarget === sumExpected);
console.log(deductTarget === deductExpected);
console.log(multiplyTarget === multiplyExpected);
console.log(divideTarget === divideExpected);
});
<file_sep>var print = (function() {
return console.log;
})();
var first = (function() {
return 'hello';
})();
var second = (function() {
return 'world!';
})();
var main = (function(print, first, second) {
print(first + ' ' + second);
})(print, first, second);
<file_sep>
define(['./separator'], function(separator) {
return {
separator: separator
}
});
|
bf8fa06584c4dcaf8b4bf5a2034a2fae8693e4fb
|
[
"Markdown",
"JavaScript"
] | 5 |
Markdown
|
gruntjs-updater/grunt-requirejs-injector
|
d866643326931c0ef59aba3f40d5ef4d4819336f
|
f8fcca92cdf4a489730b615618773bcad6dc3f42
|
refs/heads/master
|
<file_sep>// NPM Modules
import { useState, useEffect } from "react";
import Map, { Marker } from "react-map-gl";
// Util Functions
import { listLogEntry } from "../utils/api";
// Components
import AddEntryMarker from "./AddEntryMarker";
import LogMarker from "./LogMarker";
const App = () => {
const [addEntryLocation, setAddEntryLocation] = useState(null);
const [logEntries, setLogEntries] = useState([]);
const [viewState, setViewState] = useState({
latitude: 39.8283,
longitude: -98.5795,
zoom: 3.5,
});
//
const mapSizeStyling = {
width: "100vw",
height: "100vh",
};
const getEntries = async () => {
const { data } = await listLogEntry();
setLogEntries(data);
};
const showMarkerPopup = (event) => {
const { lat, lng } = event.lngLat;
setAddEntryLocation({
latitude: lat,
longitude: lng,
});
};
useEffect(() => {
getEntries();
}, []);
return (
<Map
doubleClickZoom={false}
onDblClick={showMarkerPopup}
initialViewState={{ ...viewState }}
mapStyle={"mapbox://styles/adrianpearman12/ck6iix7kv0f2e1jpeh8lgiy7l"}
mapboxAccessToken={
"<KEY>"
}
style={mapSizeStyling}
>
{logEntries.length > 0 ? (
<>
{logEntries.map((entry) => {
return (
<LogMarker entry={entry} key={entry._id} viewState={viewState} />
);
})}
</>
) : null}
{addEntryLocation ? (
<AddEntryMarker
addEntryLocation={addEntryLocation}
getEntries={getEntries}
setAddEntryLocation={setAddEntryLocation}
viewState={viewState}
/>
) : null}
</Map>
);
};
export default App;
<file_sep>// NPM Modules
require("dotenv").config();
const cors = require("cors");
const morgan = require("morgan");
const express = require("express");
const helmet = require("helmet");
const path = require("path");
// Variables
const app = express();
const clientRoot = path.join(__dirname, "../client", "dist");
const {
generalErrorHandler,
unfoundRoute,
} = require("./middlewares/middlewares");
const monogoConnection = require("./middlewares/mongoConnection");
const PORT = process.env.PORT;
// Database Connection
app.enable("trust proxy");
monogoConnection();
// Middlewares
app.use(cors());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(helmet());
app.use(morgan("common"));
// Render client root buildfile if the application is on a production server
// if (process.env.NODE_ENV === "production") {
app.use(express.static(clientRoot));
app.get("/", (req, res) => {
res.sendFile(path.join(clientRoot, "index.html"));
});
// }
// Routes
app.use("/api/logs", require("./apiRoutes/logs"));
// Route Middleware
app.use(generalErrorHandler);
app.use(unfoundRoute);
app.listen(PORT, () => {
console.log(`Listening on PORT: ${PORT}`);
});
// curl --compressed https:://octo.win/twitch
<file_sep>// Middlware on unfound routes
const unfoundRoute = (req, res, next) => {
const err = new Error(`Not Found - ${req.originalUrl}`);
res.status(404);
next(err);
};
// General ErrorHandling Middleware
// eslint-disable-next-line-no-unused-vars
const generalErrorHandler = (error, req, res, next) => {
const statusCode = res.statusCode === 200 ? 500 : res.statusCode;
res.status(statusCode);
res.json({
message: error.message,
stack: process.env.NODE_ENV === 'production' ? ':)' : error.stack,
});
};
module.exports = {
unfoundRoute,
generalErrorHandler,
};
<file_sep># CodingGardenTravelLog_App
Code along session with 'Coding Garden with CJ'. Inspiration based on https://youtu.be/5pQsl9u_10M with adjustments to certain file structures, npm modules and deployment.
## TechStack
* Node
* Express
* Helmet
* MongoDB
* React
* React Hooks & ReactHook Form
* React Map GL
* Mapbox
* esLint
Live Link: https://codinggarding-travellog.up.railway.app/
<file_sep>import { createProxyMiddleware } from "http-proxy-middleware";
const proxyFunction = (app) => {
app.use(
createProxyMiddleware("/api", {
target: "http://localhost:4000",
changeOrigin: true,
})
);
};
export default proxyFunction;
<file_sep>import axios from "axios";
const axiosClient = axios.create({
baseURL: import.meta.env.MODE === "production" ? "" : "http://localhost:4000",
json: true,
});
export const listLogEntry = async () => {
try {
const response = await axiosClient.get("/api/logs");
return response;
} catch (error) {
return { data: "An occured!" };
}
};
export const createLogEntry = async (entry) => {
try {
const privateKey = entry.privateKey;
delete entry.privateKey;
const response = await axiosClient.post(`/api/logs`, entry, {
headers: {
"X-APIKEY": privateKey,
},
});
return response.data;
} catch (error) {
return error;
}
};
<file_sep>// NPM Modules
import React, { useState } from "react";
// Util Functions
import { createLogEntry } from "../utils/api";
const LogEntryForm = ({ latitude, longitude, onClose }) => {
// State
const [comments, setComments] = useState("");
const [description, setDescription] = useState("");
const [error, setError] = useState(false);
const [loading, setLoading] = useState(false);
const [privateKey, setPrivateKey] = useState("");
const [title, setTitle] = useState("");
const [visitDate, setVisitDate] = useState("");
// Functions
const onSubmit = async (e) => {
e.preventDefault();
const data = {
comments: comments,
description: description,
privateKey: privateKey,
title: title,
visitDate: visitDate,
};
try {
setLoading(true);
await createLogEntry({ ...data, latitude, longitude });
onClose();
} catch (err) {
setError(err.message);
setLoading(false);
}
};
return (
<form className="entryForm" onSubmit={onSubmit}>
{error ? <h3 className="error">{error}</h3> : null}
<div>
<label htmlFor="apiKey">APIKEY</label>
<input
name="apiKey"
onChange={(e) => setPrivateKey(e.target.value)}
required
type="password"
/>
</div>
<div>
<label htmlFor="title">Title</label>
<input
name="title"
onChange={(e) => setTitle(e.target.value)}
required
/>
</div>
<div>
<label htmlFor="comments">Comments</label>
<textarea
name="comments"
row={3}
onChange={(e) => setComments(e.target.value)}
></textarea>
</div>
<div>
<label htmlFor="description">Description</label>
<textarea
name="description"
row={3}
onChange={(e) => setDescription(e.target.value)}
></textarea>
</div>
<div>
<label htmlFor="visitDate">Visit Date</label>
<input
name="visitDate"
onChange={(e) => setVisitDate(e.target.value)}
required
type="date"
/>
</div>
<button disabled={loading}>
{loading ? "Loading..." : "Create Log Entry"}
</button>
</form>
);
};
export default LogEntryForm;
<file_sep>// NPM Modules
import { useState } from "react";
import { Marker, Popup } from "react-map-gl";
import SVGIcon from "./SVGIcon";
const LogMarker = ({ entry, viewState }) => {
// State
const [showPopup, setShowPopup] = useState(false);
return (
<div
onMouseEnter={() => {
setShowPopup(true);
}}
>
<Marker latitude={entry.latitude} longitude={entry.longitude}>
<SVGIcon className={"marker"} zoom={viewState.zoom} />
</Marker>
{showPopup ? (
<Popup
anchor="top"
closeButton={true}
closeOnClick={true}
dynamicPosition={true}
latitude={entry.latitude}
longitude={entry.longitude}
onClose={() => setShowPopup(false)}
>
<div className="popUp">
<h3>{entry.title}</h3>
<p>{entry.description}</p>
<small>
Visit Date:
{new Date(entry.visitDate).toLocaleDateString()}
</small>
</div>
</Popup>
) : null}
</div>
);
};
export default LogMarker;
|
fdfd6453b66add0c290fe53fa71684aeeed09a8c
|
[
"JavaScript",
"Markdown"
] | 8 |
JavaScript
|
adrianpearman/CodingGardenTravelLog_App
|
368286c212f7e2df30bc5f103792614105d2502b
|
8e328ea74b1605c7954beebddbe33092b0093297
|
refs/heads/master
|
<repo_name>cmusteata/workspace<file_sep>/introlib/yaml.h
/*******************************************************************************
* Author: <NAME> *
* <EMAIL> *
******************************************************************************/
#ifndef __YAML_H__
#define __YAML_H__
#include <iostream>
#include <fstream>
#include <vector>
// struct BRIDGE
//
// This data-structure is used
// internally by the Yaml parser
struct BRIDGE final
{
int length = 0;
std::vector<double> paces;
};
// class Yaml
//
// This class is not intended to parse any generic .yaml file
// The sole purpose of this class is to parse the intro.yaml
//
// The following assumptions are made in order to parse:
// 1) The intro.yaml file is a valid yaml formatted file
// 2) All comments start at index 0
// 3) The sequence indicator is "- "
// 4) The keyvalue indicator is ": "
// 5) All sequences in a block are aligned relative to the same column
// 6) The underlying data structure of 'Yaml' is a sequence of BRIDGES
// BRIDGE entries in the intro.yaml file start at index 0
// 7) Each BRIDGE has two key-value pairs starting at index 2
// length: scalar-value
// paces: list of scalar-values
class Yaml final
{
std::string fname;
std::ifstream ifs;
std::vector<BRIDGE> data;
void parse(const std::string& line);
public:
Yaml(const std::string& filename);
~Yaml();
void parse();
const std::vector<BRIDGE>& get() const;
};
#endif //__YAML_H__
<file_sep>/crumbs/src/show3.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
void show(char n, std::ostringstream& oss)
{
for (size_t i = 8; i > 0; --i)
{
char k = 1 << (i-1);
oss << (k & n ? '1' : '0');
}
};
int main(int argc, char* argv[])
{
assert(argc == 2);
int n = std::stoi(argv[1]);
char* p = (char*)&n;
std::cout << "show(" << n << ")" << std::endl;
std::ostringstream oss;
show(*(p + 0), oss);
std::cout << std::hex << (int*)(p + 0) << " 0b" << oss.str() << std::endl;
oss.str("");
show(*(p + 1), oss);
std::cout << std::hex << (int*)(p + 1) << " 0b" << oss.str() << std::endl;
oss.str("");
show(*(p + 2), oss);
std::cout << std::hex << (int*)(p + 2) << " 0b" << oss.str() << std::endl;
oss.str("");
show(*(p + 3), oss);
std::cout << std::hex << (int*)(p + 3) << " 0b" << oss.str() << std::endl;
return 0;
}
<file_sep>/crumbs/src/bitop.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
void show(int n, std::ostringstream& oss)
{
if (n > 0)
{
show(n >> 1, oss);
oss << (n % 2);
}
};
int main(int argc, char* argv[])
{
assert(argc == 3);
int a = std::stoi(argv[1]);
int b = std::stoi(argv[2]);
std::ostringstream oss;
show(a, oss);
std::cout << "a = " << a << " " << oss.str() << std::endl;
oss.str("");
show(b, oss);
std::cout << "b = " << b << " " << oss.str() << std::endl;
int anb = a & b; // check a bit
oss.str("");
show(anb, oss);
std::cout << "check bit: a & b = " << anb << " " << oss.str() << std::endl;
int aob = a | b; // set a bit
oss.str("");
show(aob, oss);
std::cout << " set bit: a | b = " << aob << " " << oss.str() << std::endl;
a ^= b; // toggle a bit
oss.str("");
show(a, oss);
std::cout << " flip bit: a ^= b " << a << " " << oss.str() << std::endl;
a ^= b; // toggle a bit
oss.str("");
show(a, oss);
std::cout << " flip bit: a ^= b " << a << " " << oss.str() << std::endl;
int a_b = a & ~b; // clear a bit
oss.str("");
show(a_b, oss);
std::cout << "clear bit: a &~b = " << a_b << " " << oss.str() << std::endl;
return 0;
}
<file_sep>/crumbs/src/show2.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
void show2(int n, std::ostringstream& oss)
{
for (size_t i = sizeof(n)*8; i > 0; --i)
{
size_t k = 1 << (i-1);
oss << (k & n ? 1 : 0);
}
};
int main(int argc, char* argv[])
{
assert(argc == 2);
int n = std::stoi(argv[1]);
std::ostringstream oss;
show2(n, oss);
std::cout << "show2(" << n << ") = 0b" << oss.str() << std::endl;
return 0;
}
<file_sep>/intro2/Makefile
target :=intro2
objects :=main.o algo.o yaml.o bridge.o
CC :=g++
CFLAGS :=-std=c++11 -O3 -Wall -Wextra -Werror -I ../introlib
all: $(target)
intro2: $(objects)
$(CC) $^ -o $@
main.o: main.cpp algo.h
$(CC) $(CFLAGS) -c $<
algo.o: algo.cpp algo.h ../introlib/yaml.h ../introlib/bridge.h
$(CC) $(CFLAGS) -c $<
%.o: ../introlib/%.cpp ../introlib/%.h
$(CC) $(CFLAGS) -c $<
clean:
rm -f $(objects) $(target)
<file_sep>/crumbs/src/swap2.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
void swap(int& a, int& b)
{
a = a+b;
b = a-b;
a = a-b;
};
int main(int argc, char* argv[])
{
assert(argc == 3);
int a = std::stoi(argv[1]);
int b = std::stoi(argv[2]);
std::cout << "swap [" << a << "," << b << "]" << std::endl;
swap(a, b);
std::cout << "done [" << a << "," << b << "]" << std::endl;
return 0;
}
<file_sep>/crumbs/src/show.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
void show(unsigned n, std::ostringstream& oss)
{
if (n > 0)
{
show(n >> 1, oss);
oss << (n % 2);
}
};
int main(int argc, char* argv[])
{
assert(argc == 2);
int n = std::stoi(argv[1]);
assert(n > 0);
std::ostringstream oss;
show(n, oss);
std::cout << "show(" << n << ") = 0b" << oss.str() << std::endl;
return 0;
}
<file_sep>/introlib/Makefile
objects :=yaml.o bridge.o
CC :=g++
CFLAGS :=-std=c++11 -O3 -Wall -Wextra -Werror
all: $(objects)
%.o: %.cpp %.h
$(CC) $(CFLAGS) -c $<
clean:
rm -f $(objects)
<file_sep>/crumbs/src/dec2bin.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
char* dec2bin(int n, char* p)
{
if (p == nullptr)
return p;
if (n > 0)
{
p = dec2bin(n >> 1, p);
*p = n % 2 == 0 ? '0' : '1';
p++;
}
return p;
};
int main(int argc, char* argv[])
{
assert(argc == 2);
int dec = std::stoi(argv[1]);
std::cout << "dec: " << dec << std::endl;
char bin[100] = {'\0'};
dec2bin(dec, bin);
std::cout << "bin: " << bin << std::endl;
return 0;
}
<file_sep>/crumbs/src/badvss.cpp
#include <iostream>
#include <vector>
#include <thread>
#include <cassert>
#include <functional>
#include <unistd.h>
std::vector<int> vss;
auto bad = [&](int value) {
return value > (int)vss.size() / 3;
};
// template <typename F>
// size_t find(F cmp)
// size_t find(bool (*cmp)(size_t))
// size_t find(std::function<bool(size_t)> cmp);
int find(int i, int j)
{
if (i == j)
return vss[i];
int mid = (i+j)/2;
int mid_i = std::max<int>(i, mid);
int mid_j = std::min<int>(mid+1, j);
int curr = vss[mid_i];
int next = vss[mid_j];
std::cerr << "[" << vss[i] << "," << curr << "][" << next << "," << vss[j] << "] " << (int)vss.size()/3 << std::endl;
if (!bad(curr) && bad(next))
return next;
if (bad(curr) && bad(next))
return find(i, mid_i);
if (!bad(curr) && !bad(next))
return find(mid_j, j);
return -1;
};
int main(int argc, char* argv[])
{
assert(argc == 2);
int n = std::stoi(argv[1]);
for (int i = 0; i < n; ++i)
vss.push_back(i+1);
int ver = find(0, (int)vss.size() - 1);
std::cout << "ver: " << ver << std::endl;
return 0;
}
<file_sep>/crumbs/src/invert.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
void invert(int n)
{
if (n > 0)
{
std::ostringstream oss;
for (int i = 0; i < n; ++i)
oss << '*';
std::cout << oss.str() << std::endl;
invert(--n);
}
}
int main(int argc, char* argv[])
{
assert(argc == 2);
int n = std::stoi(argv[1]);
invert(n);
return 0;
}
<file_sep>/thread/src/sum.cpp
#include <iostream>
#include <vector>
#include <thread>
int compsum(const std::vector<int>& vect, int num)
{
std::vector<int> temp(num);
std::vector<std::thread> cont;
auto singsum = [&](int id, int j, int len)
{
int sum = 0;
for (int i = 0; i < len; ++i)
sum += vect[j + i];
temp[id] = sum;
};
int m = vect.size() % num;
int n = vect.size() / num;
for (int i = 0; i < num-1; ++i)
cont.emplace_back(singsum, i, i*n, n);
cont.emplace_back(singsum, num-1, (num-1)*n, n+m);
// wait here for threads to complete and while
// they complete add the result to the whole sum
int sum = 0;
for (int i = 0; i < num-1; ++i)
{
cont[i].join();
std::cout << "thread " << i << ": " << temp[i] << std::endl;
sum += temp[i];
}
cont[num-1].join();
std::cout << "thread " << num-1 << ": " << temp[num-1] << std::endl;
sum += temp[num-1];
return sum;
};
int main()
{
std::vector<int> myarr = {3,6,9,1,5,7,2,8,4,13,17,55,47,13,21,46,99,74,71,25};
int sum = compsum(myarr, 3);
std::cout << "sum: " << sum << std::endl;
double avg = double(sum) / myarr.size();
std::cout << "avg: " << avg << std::endl;
return 0;
}
<file_sep>/intro/algo.cpp
#include "algo.h"
#include <algorithm>
// This Algo computes the crossing time and total distance
// The assumption is made that a faster hiker on the right side of the bridge
// can't help the hikers on the left side to improve the crossing time.
// Each group on the left side independently has to cross the bridge and
// then join the group of hikers on the right side.
void Algo::show() const
{
for (size_t k = 0; k < groups.size(); ++k)
{
for (double pace : groups[k])
std::cerr << pace << ',';
if (k < bridges.size())
std::cerr << bridges[k] << ' ';
}
std::cerr << std::endl;
}
Algo::Algo(const Yaml& yaml)
{
for (const auto& y : yaml.get())
{
bridges.emplace_back(y.length);
groups.emplace_back();
auto& group = groups.back();
for (double pace : y.paces)
group.push_back(pace);
}
// add [n + 1] group to help transfer
// the hikers across the [n] bridge
groups.emplace_back();
}
void Algo::run()
{
Bridge total;
for (size_t k = 0; k < bridges.size(); ++k)
{
auto& lhs = groups[k]; // left hand side of the bridge
auto& rhs = groups[k+1]; // right hand side of the bridge
std::sort(lhs.begin(), lhs.end(), std::greater<double>());
show();
// The top 2 fastest hikers on the left side cross together
// while the fastest on the left side returns back to handover
// the torch to the slowest pair of hikers on the left side.
// The slowest pair of hikers cross the bridge then the second
// fastest returns the torch back to the left side group of hikers.
//
// Note that the fastest pair of hikers always return back so
// only the timing is incremented while not necessary to phisically
// move the hikers from one container to another back and forth.
// However, for the slowest pair of hikers we both increment the time
// and phisically move the hikers to the next container.
//
// We repeat this same algorithm for each bridge by removing the
// slowest pair of hikers at each iteration until 1, 2 or 3 hikers
// are left in the group. From there, there's no particular variation
// to improve any timing therefore we consider them particular cases.
//
// The hikers are represented by their pace and we sort them before
// crossing each bridge. The choice of using a std::vector to move
// the hikers and std::sort sorting algorithm with [n*log(n)] time
// complexity potentially may be faster than other data-structures
// (have to prove) for a reasonable numbers of hikers in each group
// as long as each group fits in a line of CPU cache in order to
// avoid false sharing at sorting.
auto& bridge = bridges[k];
for (size_t n = lhs.size(); n > 0; n = lhs.size())
{
if (n == 1)
{
// one-way trip
// timing for hiker [0]
bridge.time += bridge.length / lhs[0];
// transfer for the last hikers
while (!lhs.empty())
{
rhs.push_back(lhs.back());
lhs.pop_back();
}
}
else if (n == 2)
{
// one-way trip
// timing for hikers [0] and [1]
bridge.time += bridge.length / lhs[1];
// transfer for the last hikers
while (!lhs.empty())
{
rhs.push_back(lhs.back());
lhs.pop_back();
}
}
else if (n == 3)
{
// timing for the fastest pair of hikers from the
// left side lhs[0] & lhs[1] at the pace of lhs[1]
bridge.time += bridge.length / lhs[1];
// timing for the fastest hiker from the left side
// who just returned the torch from the right side
bridge.time += bridge.length / lhs[0];
// timing for the hikers lhs[2] & lhs[0] at the pace of lhs[2]
bridge.time += bridge.length / lhs[2];
// move all hikers from the left to the right side
while (!lhs.empty())
{
rhs.push_back(lhs.back());
lhs.pop_back();
}
}
else
{
// timing for the fastest pair of hikers from the
// left side lhs[0] & lhs[1] at the pace of lhs[1]
bridge.time += bridge.length / lhs[1];
// timing for the fastest hiker from the left side
// who just returned the torch from the right side
bridge.time += bridge.length / lhs[0];
// timing for the slowest pair of hikers from the
// left side lhs[j] and lhs[j-1] at the pace of lhs[j]
size_t j = n - 1;
bridge.time += bridge.length / lhs[j];
// timing for the second fastest hiker from the left side
// who just returned the torch from the right side
bridge.time += bridge.length / lhs[1];
// move the slowest pair of hikers from left to the right side
for (int i = 0; i < 2; ++i)
{
rhs.push_back(lhs.back());
lhs.pop_back();
}
}
// display the progress as we transfer the hikers
show();
}
// total crossing all bridges
total += bridge;
}
// store the result
result = total;
}
std::ostream& operator<<(std::ostream& os, const Algo& algo)
{
for (size_t k = 0; k < algo.bridges.size(); ++k)
os << "bridge " << k << ": " << algo.bridges[k] << std::endl;
os << "overall : " << algo.result;
return os;
}
<file_sep>/cirque/build.sh
#!/bin/bash
g++ main.cpp -I . -pthread -std=c++11 -O3 -Wall -Wextra -o cirque
<file_sep>/cirque/ring_buffer.h
#ifndef __RING_BUFFER_H__
#define __RING_BUFFER_H__
#include <limits>
#include <atomic>
template <typename T>
class ring_buffer final
{
int length;
char* data[std::numeric_limits<T>::max()+1];
std::atomic<T> i, j, next_i, next_j;
public:
ring_buffer(int len);
~ring_buffer();
bool empty() const;
bool full() const;
const char* front() const;
const char* back() const;
bool pop_front(char* msg, int msgsize);
bool push_back(const char* msg, int msgsize);
};
#include "ring_buffer.hpp"
#endif // __RING_BUFFER_H__
<file_sep>/Makefile
all:
$(MAKE) -C introlib
$(MAKE) -C intro
$(MAKE) -C intro2
clean:
$(MAKE) -C intro2 clean
$(MAKE) -C intro clean
$(MAKE) -C introlib clean
<file_sep>/run.sh
#!/bin/bash
BEGIN=$(date +%s)
./intro/intro intro/intro.yaml 2> /dev/null
./intro2/intro intro2/intro.yaml 2> /dev/null
END=$(date +%s)
echo "elapsed "$((END-BEGIN))" seconds"
<file_sep>/thread/src/sum2.cpp
#include <iostream>
#include <vector>
#include <thread>
#include <cassert>
int compsum(const std::vector<int>& vect, int num)
{
auto singsum = [&](int id, int* sum)
{
for (size_t i = id; i < vect.size(); i += num)
*sum += vect[i];
};
std::vector<int> temp(num);
std::vector<std::thread> cont(num);
for (int i = 0; i < num; ++i)
cont[i] = std::thread(singsum, i, &temp[i]);
// wait here for threads to complete and while
// they complete add the result to the whole sum
int sum = 0;
for (int i = 0; i < num; ++i)
{
cont[i].join();
std::cout << "thread " << i << ": " << temp[i] << std::endl;
sum += temp[i];
}
return sum;
};
std::vector<int> myarr = {
3, 6, 9, 1, 5, 7, 2, 8, 4,13,
17,55,47,13,21,46,99,74,71,25
};
int main(int argc, char* argv[])
{
assert(argc == 2);
int n = std::stoi(argv[1]);
int sum = compsum(myarr, n);
std::cout << "sum: " << sum << std::endl;
double avg = double(sum) / myarr.size();
std::cout << "avg: " << avg << std::endl;
return 0;
}
<file_sep>/crumbs/build.sh
#!/bin/bash
BEGIN=$(date +%s)
g++ -std=c++11 -Wall -Wextra -O3 -o $1 src/$1.cpp
END=$(date +%s)
ELAPSED=$((END-BEGIN))
echo "elapsed $ELAPSED seconds"
<file_sep>/matrix/build.sh
#!/bin/bash
g++ main.cpp matrix.cpp -I . -std=c++11 -O3 -Wall -Wextra -o matrix
<file_sep>/introlib/bridge.h
/*******************************************************************************
* Author: <NAME> *
* <EMAIL> *
******************************************************************************/
#ifndef __BRIDGE_H__
#define __BRIDGE_H__
#include <ostream>
// Data structure used internally by the 'class Algo'
// to compute the crossing distance & the crosing time
struct Bridge final
{
int length;
double time;
Bridge();
Bridge(int len);
const Bridge& operator +=(const Bridge&);
friend std::ostream& operator <<(std::ostream&, const Bridge&);
};
#endif //__BRIDGE_H__
<file_sep>/matrix/matrix.cpp
#include <iostream>
#include "matrix.h"
std::vector<std::vector<int>> matrix_sum(const std::vector<std::vector<int>>& before)
{
std::vector<std::vector<int>> after(before.size());
for (size_t i = 0; i < before.size(); ++i)
{
after[i].resize(before[i].size());
for (size_t j = 0; j < before[i].size(); ++j)
{
if (i > 0 && j > 0)
after[i][j] = before[i][j] + after[i-1][j] + after[i][j-1] - after[i-1][j-1];
else if (i > 0)
after[i][j] = before[i][j] + after[i-1][j];
else if (j > 0)
after[i][j] = before[i][j] + after[i][j-1];
else
after[i][j] = before[i][j];
}
}
return after;
}
std::vector<std::vector<int>> matrix_restore(const std::vector<std::vector<int>>& after)
{
std::vector<std::vector<int>> before(after.size());
for (size_t i = 0; i < after.size(); ++i)
{
before[i].resize(after[i].size());
for (size_t j = 0; j < after[i].size(); ++j)
{
if (i > 0 && j > 0)
before[i][j] = after[i][j] - after[i-1][j] - after[i][j-1] + after[i-1][j-1];
else if (i > 0)
before[i][j] = after[i][j] - after[i-1][j];
else if (j > 0)
before[i][j] = after[i][j] - after[i][j-1];
else
before[i][j] = after[i][j];
}
}
return before;
}
<file_sep>/readme.txt
workspace/intro
This algo computes the crossing time and total distance
The assumption is made that a faster hiker on the right side of the bridge
can't help the hikers on the left side to improve the crossing time.
Each group on the left side independently has to cross the bridge and
then join the group of hikers on the right side.
[constantin.musteata@localhost intro]$ ./run.sh
open file: intro/intro.yaml
bridge 0: [100 ft, 17 min]
bridge 1: [250 ft, 132.5 min]
bridge 2: [150 ft, 95.5 min]
overall : [500 ft, 245 min]
begin time: Tue Aug 20 16:08:40 2019
end time: Tue Aug 20 16:08:40 2019
elapsed: 0.000279383 seconds
Obs: this algorithm is using std::vector as underlying data-structure for
moving the hikers accross the bridge
workspace/intro2
This algo computes the crossing time and total distance
The assumption is made that a faster hiker on the right side
may help the hikers on the left side to improve the crossing time
After each pair-crossing from the left side to the right side
the ranking of the hikers is reevaluated in order to establish
the fastest hiker to return the torch back to the left side.
[constantin.musteata@localhost intro2]$ ./run.sh
open file: intro2/intro.yaml
bridge 0: [100 ft, 17 min]
bridge 1: [250 ft, 132.5 min]
bridge 2: [150 ft, 95.5 min]
overall : [500 ft, 245 min]
begin time: Tue Aug 20 16:08:40 2019
end time: Tue Aug 20 16:08:40 2019
elapsed: 0.000471861 seconds
Obs: this algorithm is using std::deque as underlying data-structure for
moving the hikers back and forth accross the bridge
<file_sep>/crumbs/src/zero.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
void show(int n, std::ostringstream& oss)
{
if (n > 0)
{
show(n >> 1, oss);
oss << n%2;
}
};
int main(int argc, char* argv[])
{
assert(argc == 2);
int n = std::stoi(argv[1]);
std::ostringstream oss;
show(n, oss);
std::cout << "n = " << oss.str() << " (dec: " << n << ")"<< std::endl;
int count = -1, m = 0ul;
for (size_t i = 0; i < sizeof(n)*8; ++i)
{
if (n%2 == 0)
{
if (count >= 0)
count++;
}
else // == 1
{
if (count > m)
m = count;
count = 0;
}
n = n >> 1;
}
oss.str("");
show(m, oss);
std::cout << "m = " << m << " (max num of zeroes between two bits set to 1)" << std::endl;
return 0;
}
<file_sep>/intro2/generate.sh
#!/bin/bash
BEGIN=$(date +%s)
END=$(date +%s)
echo "elapsed "$((END-BEGIN))" seconds"
<file_sep>/intro/main.cpp
#include <iostream>
#include <chrono>
#include <ctime>
#include <cassert>
#include "algo.h"
int main(int argc, char* argv[])
{
assert(argc == 2);
std::string filename = argv[1];
std::cout << "open file: " << filename << std::endl;
auto begin = std::chrono::system_clock::now();
time_t begin_time = std::chrono::system_clock::to_time_t(begin);
Yaml yaml(filename);
yaml.parse();
Algo algo(yaml);
algo.run();
std::cout << algo << std::endl;
auto end = std::chrono::system_clock::now();
std::time_t end_time = std::chrono::system_clock::to_time_t(end);
std::chrono::duration<double> elapsed_seconds = end - begin;
std::cout << "begin time: " << std::ctime(&begin_time);
std::cout << " end time: " << std::ctime(&end_time);
std::cout << " elapsed: " << elapsed_seconds.count() << " seconds" << std::endl;
return 0;
}
<file_sep>/cirque/main.cpp
#include <cassert>
#include <atomic>
#include <thread>
#include <vector>
#include <unistd.h>
#include "ring_buffer.h"
constexpr char err[] = "queue is full";
constexpr int errlen = sizeof(err);
ring_buffer<uint16_t> rb(100);
ring_buffer<uint16_t> oo(100);
bool stop = false;
auto prnt= [&]()
{
char msg[100] = {0};
for (size_t i = 0; !stop; ++i)
{
if (!oo.pop_front(msg, sizeof(msg)))
continue;
std::cout << "cons: " << msg << std::endl;
}
};
auto prod = [&](const char* msg)
{
int msglen = std::strlen(msg) + 1;
for (size_t i = 0; !stop; ++i)
{
if (!rb.push_back(msg, msglen))
oo.push_back(err, errlen);
if (i % 100 == 0)
usleep(1);
}
};
auto cons = [&]()
{
char msg[100] = {0};
for (size_t i = 0; !stop; ++i)
{
if (rb.pop_front(msg, sizeof(msg)))
oo.push_back(msg, std::strlen(msg)+1);
}
};
int main(int argc, char**)
{
assert(argc == 1);
std::vector<std::thread> workers;
workers.emplace_back(prnt);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(cons);
workers.emplace_back(prod, "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
workers.emplace_back(prod, "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb");
workers.emplace_back(prod, "ccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc");
workers.emplace_back(prod, "fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff");
workers.emplace_back(prod, "ggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggggg");
workers.emplace_back(prod, "kkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
workers.emplace_back(prod, "nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn");
workers.emplace_back(prod, "ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo");
workers.emplace_back(prod, "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
workers.emplace_back(prod, "sssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss");
workers.emplace_back(prod, "vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv");
workers.emplace_back(prod, "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz");
for (auto& w : workers)
w.join();
return 0;
}
<file_sep>/crumbs/src/bin2dec.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
int bin2dec(const char* p)
{
if (p == nullptr)
return -1;
int n = 0;
if (*p != '\0')
{
n = bin2dec(++p);
n = n << 1;
n += *p == '0' ? 0 : 1;
}
return n;
};
int main(int argc, char* argv[])
{
assert(argc == 2);
const char* bin = argv[1];
std::cout << "bin: " << bin << std::endl;
int dec = bin2dec(bin);
std::cout << "dec: " << dec << std::endl;
return 0;
}
<file_sep>/matrix/readme.txt
Considering a matrix A(m,n) with m rows and n columns.
We define the sum matrix S(m,n) with the following property.
The value of each S[x][y] cell is the sum of all the elements
in the A(x+1,y+1) matrix, where x = [0, m) and y = [0, n).
for (int x = 0; x < m; ++x)
{
for (int y = 0; y < n; ++y)
{
int sum = 0;
for (int i = 0; i < x+1; ++i)
for (int j = 0; j < y+1; ++j)
sum += A[i][j];
S[x][y] = sum;
}
}
Being given the sum-matrix S(m,n) you have to calculate the initial matrix A(m,n).
Time complexity O(m*n).
<file_sep>/intro/algo.h
/*******************************************************************************
* Author: <NAME> *
* <EMAIL> *
******************************************************************************/
#ifndef __ALGO_H__
#define __ALGO_H__
#include <vector>
#include <ostream>
#include "bridge.h"
#include "yaml.h"
// This algo computes the crossing time and total distance
// The assumption is made that a faster hiker on the right side of the bridge
// can't help the hikers on the left side to improve the crossing time.
// Each group on the left side independently has to cross the bridge and
// then join the group of hikers on the right side.
class Algo final
{
Bridge result;
std::vector<Bridge> bridges;
std::vector<std::vector<double>> groups;
void show() const;
public:
Algo(const Yaml&);
void run();
friend std::ostream& operator <<(std::ostream&, const Algo&);
};
#endif //__ALGO_H__
<file_sep>/cirque/ring_buffer.hpp
#ifndef __RING_BUFFER_HPP__
#define __RING_BUFFER_HPP__
#include <iostream>
#include <cstring>
template<typename T, size_t size>
constexpr size_t SizeOf(const T (&)[size])
{
return size;
};
template <typename T>
ring_buffer<T>::ring_buffer(int len)
: length(len)
, i(std::numeric_limits<T>::max())
, j(0)
, next_i(0)
, next_j(1)
{
size_t rows = SizeOf(data);
char* buffer = static_cast<char*>(operator new(rows * length));
for (size_t k = 0; k < rows; ++k)
data[k] = &buffer[k * length];
}
template <typename T>
ring_buffer<T>::~ring_buffer()
{
char* buffer = data[0];
operator delete(buffer);
}
template <typename T>
bool ring_buffer<T>::empty() const
{
return next_i == j;
}
template <typename T>
bool ring_buffer<T>::full() const
{
return next_j == i;
}
template <typename T>
const char* ring_buffer<T>::front() const
{
return next_i == j ? nullptr : data[next_i];
}
template <typename T>
const char* ring_buffer<T>::back() const
{
return next_j == i ? nullptr : data[next_j];
}
template <typename T>
bool ring_buffer<T>::pop_front(char* msg, int msgsize)
{
if (next_i == j) // empty
return false;
char* front = data[next_i++];
std::memcpy(msg, front, std::min<int>(length, msgsize));
++i;
return true;
}
template <typename T>
bool ring_buffer<T>::push_back(const char* msg, int msgsize)
{
if (next_j == i) // full
return false;
char* back = data[next_j++];
std::memcpy(back, msg, std::min<int>(length, msgsize));
++j;
return true;
}
#endif // __RING_BUFFER_HPP__
<file_sep>/introlib/yaml.cpp
#include <cassert>
#include "yaml.h"
Yaml::Yaml(const std::string& filename)
: fname(filename)
, ifs(filename)
{
}
Yaml::~Yaml()
{
ifs.close();
}
void Yaml::parse(const std::string& line)
{
// ignore all comments
if (line.find("# ") == 0)
return;
// looking for a sequence indicator
std::size_t pos = line.find("- ");
if (pos != std::string::npos)
{
if (pos == 0)
{
// emplace an empty BRIDGE entry
data.emplace_back();
std::cerr << "[" << pos << "] " << "- " << std::endl;
}
else
{
assert(data.empty() == false);
// emplace a new hiking-pace for this BRIDGE
std::string value = line.substr(pos += 2);
data.back().paces.emplace_back(std::stod(value));
std::cerr << "[" << pos << "] " << " - " << value << std::endl;
}
}
// looking for a key-value indicator
pos = line.find(": ");
if (pos != std::string::npos)
{
const std::string key1 = "length";
const std::string key2 = "paces";
if (line.find(key1, 2) != std::string::npos)
{
assert(data.empty() == false);
// sent the length of the bridge
std::string value = line.substr(pos += 2);
data.back().length = std::stoi(value);
std::cerr << "[" << pos << "] " << key1 << ": " << value << std::endl;
}
else if (line.find(key2, 2) != std::string::npos)
{
std::cerr << "[" << pos << "] " << key2 << ": " << std::endl;
}
}
}
void Yaml::parse()
{
assert(ifs.is_open() == true);
std::string line;
getline(ifs, line);
assert(line == "---");
while (getline(ifs, line))
parse(line);
}
const std::vector<BRIDGE>& Yaml::get() const
{
return data;
}
<file_sep>/introlib/bridge.cpp
#include "bridge.h"
Bridge::Bridge()
: length(0)
, time(0.0)
{
}
Bridge::Bridge(int len)
: length(len)
, time(0.0)
{
}
const Bridge& Bridge::operator +=(const Bridge& bridge)
{
length += bridge.length;
time += bridge.time;
return *this;
}
std::ostream& operator <<(std::ostream& os, const Bridge& bridge)
{
os << "[" << bridge.length << " ft, " << bridge.time << " min]";
return os;
}
<file_sep>/matrix/main.cpp
#include <cassert>
#include <iostream>
#include "matrix.h"
const std::vector<std::vector<int>> before =
{
{ 1, 2, 3, 4},
{ 5, 6, 7, 8},
{ 9,10,11,12},
{13,14,15,16}
};
int main(int argc, char**)
{
assert(argc == 1);
for (const auto& r : before)
{
std::cout << "before:";
for (auto v : r)
std::cout << " " << v << ",";
std::cout << std::endl;
}
auto after = matrix_sum(before);
for (const auto& r : after)
{
std::cout << "after:";
for (auto v : r)
std::cout << " " << v << ",";
std::cout << std::endl;
}
auto before = matrix_restore(after);
for (const auto& r : before)
{
std::cout << "restore:";
for (auto v : r)
std::cout << " " << v << ",";
std::cout << std::endl;
}
return 0;
}
<file_sep>/intro2/readme.txt
Write a C++ program that simulates a team hiking through a forest at night. The team encounters a series of narrow bridges along the way. At each bridge they may meet additional hikers who need their help to cross the bridge.
The narrow bridge can only hold two people at a time. They have one torch and because it's night, the torch has to be used when crossing the bridge. Each hiker can cross the bridge at different speeds. When two hikers cross the bridge together, they must move at the slower person's pace.
Determine the fastest time that the hikers can cross the each bridge and the total time for all crossings. The input to the program will be a yaml file that describes the speeds of each person, the bridges encountered, their length, and the additional hikers encountered along the way. Your solution should assume any number of people and bridges can be provided as inputs.
Demonstrate the operation of your program using the following inputs: the hikers cross 3 bridges, at the first bridge (100 ft long) 4 hikers cross (hiker A can cross at 100 ft/minute, B at 50 ft/minute, C at 20 ft/minute, and D at 10 ft/minute), at the second bridge (250 ft long) an additional hiker crosses with the team (E at 2.5 ft/minute), and finally at the last bridge (150 ft long) two hikers are encountered (F at 25 ft/minute and G at 15 ft/minute).
A 100 ft/min | 100 ft | E 2.5 ft/min | 250 ft | F 25 ft/min | 150 ft |
B 50 ft/min |==========| |==========| G 15 ft/min |==========|
C 20 ft/min
D 10 ft/min
You will be judged on the following:
1. Strategy(s) - there are several ways to solve the problem, you can provide more than one. The goal is to show us how you think.
2. Architecture and design- we want to see how well you architect and design solutions to complex problems.
3. Testing - we want to see how you approach testing of the solution.
4. Standards and best practices.
5. Explanation - as a C++ thought leader in the organization you will be working with and mentoring other engineers. How well you can describe and explain your solution is very important.
Please provide a link to your github repo with your solution.
<file_sep>/matrix/matrix.h
#ifndef __MATRIX_H__
#define __MATRIX_H__
#include <vector>
std::vector<std::vector<int>> matrix_sum(const std::vector<std::vector<int>>& before);
std::vector<std::vector<int>> matrix_restore(const std::vector<std::vector<int>>& after);
#endif // __MATRIX_H__
<file_sep>/crumbs/src/compl.cpp
#include <cassert>
#include <iostream>
#include <sstream>
#include <string>
int log(unsigned n)
{
int count = 0; // number of bits to represent the number n
for (unsigned i = 1; i <= n; i = i << 1)
count++;
return count;
};
int log2(unsigned n)
{
int count = 0;
for (; n > 0; n = n >> 1)
count++;
return count;
};
void show(unsigned n, std::ostringstream& oss)
{
if (n > 0)
{
show(n >> 1, oss);
oss << n%2;
}
};
int main(int argc, char* argv[])
{
assert(argc == 2);
int n = std::stoi(argv[1]);
assert(n > 0);
std::ostringstream oss;
show(n, oss);
std::cout << "show(" << n << ") = 0b" << oss.str() << std::endl;
int logn = log2(n);
std::cout << "logn = " << logn << std::endl;
int max = sizeof(n)*8; // max number of bits to represent type int
int k = max - logn; // bits to shift to get rid of leftmost bits
// n == 5 // 0000 0101
unsigned c = ~n; // 1111 1010
c = c << k; // 0100 0000
c = c >> k; // 0000 0010
// c == 2 // ---- ----
oss.str("");
show(c, oss);
std::cout << "compl(" << c << ") = 0b" << oss.str() << std::endl;
return 0;
}
<file_sep>/intro2/algo.cpp
#include "algo.h"
#include <algorithm>
// This algo computes the crossing time and total distance
// The assumption is made that a faster hiker on the right side
// may help the hikers on the left side to improve the crossing time
// After each pair-crossing from the left side to the right side
// the ranking of the hikers is reevaluated in order to establish
// the fastest hiker to return the torch back to the left side.
void Algo::show() const
{
for (size_t k = 0; k < groups.size(); ++k)
{
for (double pace : groups[k])
std::cerr << pace << ',';
if (k < bridges.size())
std::cerr << bridges[k] << ' ';
}
std::cerr << std::endl;
}
Algo::Algo(const Yaml& yaml)
{
for (const auto& y : yaml.get())
{
bridges.emplace_back(y.length);
groups.emplace_back();
auto& group = groups.back();
for (double pace : y.paces)
group.push_back(pace);
}
// add [n + 1] group to help transfer
// the hikers across the [n] bridge
groups.emplace_back();
}
void Algo::run()
{
Bridge total;
for (size_t k = 0; k < bridges.size(); ++k)
{
auto& lhs = groups[k]; // left hand side of the bridge
auto& rhs = groups[k+1]; // right hand side of the bridge
std::sort(lhs.begin(), lhs.end(), std::greater<double>());
show();
// The top 2 fastest hikers on the left side cross together at the
// pace of the second fastest. After this first pair-crossing we
// reevaluate the fastest hikers on the right. The fastest hiker on
// the right group returns with the torch and hands it over to the
// slowest pair of hikers on the left side. The slowest pair of hikers
// finally crosses the bridge. After this second pair-crossing we
// have to reevaluate again the fastest hiker on the right side.
// The fastest hiker on the right side returns with the torch.
// At this point the fastest hikers in both left and right side
// are on the left side helping the rest of the group to cross.
//
// We repeat this same algorithm for each bridge by removing the
// bottom 2 slowest hikers at each iteration until 1, 2 or 3 hikers
// are left in the group. From there, there's no particular variation
// to improve any timing therefore I consider them particular cases.
//
// The hikers are represented by their pace and we sort them after
// each bridge crossing. I use std::deque to move the hikers back and
// forth and std::sort algorithm with [n*log(n)] time complexity.
auto &bridge = bridges[k];
for (size_t n = lhs.size(); n > 0; n = lhs.size())
{
if (n == 1)
{
// one-way trip
// timing for hiker [0]
bridge.time += bridge.length / lhs[0];
// transfer for the last hikers
while (!lhs.empty())
{
rhs.push_back(lhs.back());
lhs.pop_back();
}
}
else if (n == 2)
{
// one-way trip
// timing for hikers [0] and [1]
bridge.time += bridge.length / lhs[1];
// transfer for the last hikers
while (!lhs.empty())
{
rhs.push_back(lhs.back());
lhs.pop_back();
}
}
else if (n == 3)
{
// timing for the fastest pair of hikers from the
// left side lhs[0] & lhs[1] at the pace of lhs[1]
bridge.time += bridge.length / lhs[1];
// move the fastest hiker from left to the right side
// and reevaluate the fastest hiker on the right side
rhs.push_front(lhs.front());
lhs.pop_front();
std::sort(rhs.begin(), rhs.end(), std::greater<double>());
show();
// move the fastest hiker from right to the left side
// and reevaluate the fastest hiker on the left side
lhs.push_front(rhs.front());
rhs.pop_front();
std::sort(lhs.begin(), lhs.end(), std::greater<double>());
show();
// timing for the fastest hiker from the left side
// who just returned the torch from the right side
bridge.time += bridge.length / lhs[0];
// timing for the hikers lhs[2] & lhs[0] at the pace of lhs[2]
bridge.time += bridge.length / lhs[2];
// move all hikers from the left to the right side
while (!lhs.empty())
{
rhs.push_back(lhs.back());
lhs.pop_back();
}
}
else
{
// timing for the fastest pair of hikers from the
// left side lhs[0] & lhs[1] at the pace of lhs[1]
bridge.time += bridge.length / lhs[1];
// NOTE: in real life the fastest hikers don't return the
// torch together as in this code. They return the torch
// at different points in time. This is just a code
// optimization since after the first pair-crossing and
// ranking reevaluation the fastest pair of hikers in both
// groups is not going to change and they certainly
// return afer the first 2 pair-crossings.
// move pair of fastest hikers from left to the right side
// and reevaluate the fastest hikers on the right side.
rhs.push_front(lhs.front());
lhs.pop_front();
rhs.push_front(lhs.front());
lhs.pop_front();
std::sort(rhs.begin(), rhs.end(), std::greater<double>());
show();
// move pair of fastest hikers from right to the left side
// and reevaluate the fastest hikers on the left side
lhs.push_front(rhs.front());
rhs.pop_front();
lhs.push_front(rhs.front());
rhs.pop_front();
std::sort(lhs.begin(), lhs.end(), std::greater<double>());
show();
// timing for the fastest hiker from the right side
// who just returned the torch from the right side
bridge.time += bridge.length / lhs[0];
// timing for the slowest pair of hikers from the
// left side lhs[j] and lhs[j-1] at the pace of lhs[j]
size_t j = n - 1;
bridge.time += bridge.length / lhs[j];
bridge.time += bridge.length / lhs[1];
// move the slowest pair of hikers from left to the right side
for (int i = 0; i < 2; ++i)
{
rhs.push_back(lhs.back());
lhs.pop_back();
}
}
// display the progress as we transfer the hikers
show();
}
// total crossing all bridges
total += bridge;
}
// store the result
result = total;
}
std::ostream& operator<<(std::ostream& os, const Algo& algo)
{
for (size_t k = 0; k < algo.bridges.size(); ++k)
os << "bridge " << k << ": " << algo.bridges[k] << std::endl;
os << "overall : " << algo.result;
return os;
}
|
93e132d051352e839532e68042e5842a4827f16f
|
[
"Text",
"Makefile",
"C++",
"Shell"
] | 38 |
C++
|
cmusteata/workspace
|
e8de183131a3c481fb0c1c58c9220721eeeae8e9
|
dbbc35685cee7d5b92d94922981feebb6fd4f693
|
refs/heads/master
|
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 bits;
/**
* Sync pattern matcher.
*
* Note: works for sync patterns up to 63 bits (integer size - 1 ) long.
* If a 64 bit or larger sync pattern is applied, then the wrapping feature
* of the Long.rotate methods will wrap the MSB around to the LSB and
* corrupt the matching value.
*
*/
public class SyncPatternMatcher
{
private long mBits = 0;
private long mMask = 0;
private long mSync = 0;
private boolean mSoftMode = false;
private int mSoftModeErrorThreshold = 0;
public SyncPatternMatcher( boolean[] syncPattern )
{
//Setup a bit mask of all ones the length of the sync pattern
mMask = (long)( ( Math.pow( 2, syncPattern.length ) ) - 1 );
//Convert the sync bits into a long value for comparison
for( int x = 0; x < syncPattern.length; x++ )
{
if( syncPattern[ x ] )
{
mSync += 1l << ( syncPattern.length - 1 - x );
}
}
}
public SyncPatternMatcher( long sync )
{
mSync = sync;
mMask = getMask( sync );
}
/**
* Constructs the sync pattern matcher and defines the soft mode maximum
* number of bit errors to allow in the pattern match.
*
* @param sync pattern
* @param softModeErrorThreshold - maximum bit errors (ie pattern mismatch
* positions) when considering a sync match
*/
public SyncPatternMatcher( long sync, int softModeErrorThreshold )
{
this( sync );
mSoftModeErrorThreshold = softModeErrorThreshold;
}
/**
* Generates an all ones mask corresponding to the sync pattern
*/
private static long getMask( long sync )
{
long mask = sync;
for( int x = 1; x < 64; x *= 2 )
{
mask |= ( mask >> x );
}
return mask;
}
public void receive( boolean bit )
{
//Left shift the previous value
mBits = Long.rotateLeft( mBits, 1 );
//Apply the mask to erase the previous MSB
mBits &= mMask;
//Add in the new bit
if( bit )
{
mBits += 1;
}
}
/**
* Indicates if the most recently received bit sequence matches the
* sync pattern
*/
public boolean matches()
{
if( mSoftMode )
{
long difference = mBits ^ mSync;
return difference == 0 ||
Long.bitCount( difference ) <= mSoftModeErrorThreshold;
}
else
{
return ( mBits == mSync );
}
}
/**
* Sets the sync pattern matcher in soft mode which allows up to the soft
* mode threshold number of bit errors when considering a sync pattern match
*/
public void setSoftMode( boolean softMode )
{
mSoftMode = softMode;
}
}
<file_sep>package decode.p25.message.pdu.confirmed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.pdu.PDUMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.MDPConfigurationOption;
import decode.p25.reference.PDUType;
import decode.p25.reference.SNDCPActivationRejectReason;
import decode.p25.reference.Vendor;
import edac.CRC;
import edac.CRCP25;
public class SNDCPActivateTDSContextAccept extends PDUConfirmedMessage
{
public final static Logger mLog =
LoggerFactory.getLogger( SNDCPActivateTDSContextAccept.class );
/* SN-Activate TDS Context Accept */
public static final int[] NSAPI = { 180,181,182,183 };
public static final int[] PDUPM = { 184,185,186,187 };
public static final int[] READY = { 188,189,190,191 };
public static final int[] STANDBY = { 192,193,194,195 };
public static final int[] NAT = { 196,197,198,199 };
public static final int[] IP_1 = { 200,201,202,203,204,205,206,207 };
public static final int[] IP_2 = { 208,209,210,211,212,213,214,215 };
public static final int[] IP_3 = { 216,217,218,219,220,221,222,223 };
public static final int[] IP_4 = { 224,225,226,227,228,229,230,231 };
public static final int[] IPHC = { 232,233,234,235,236,237,238,239 };
public static final int[] TCPSS = { 240,241,242,243 };
public static final int[] UDPSS = { 244,245,246,247 };
public static final int[] MTU = { 248,249,250,251 };
public static final int[] UDPC = { 252,253,254,255 };
public static final int[] MDPCO = { 256,257,258,259,260,261,262,263 };
public static final int[] DATA_ACCESS_CONTROL = { 264,265,266,267,268,
269,270,271,272,273,274,275,276,277,278,279 };
public SNDCPActivateTDSContextAccept( PDUConfirmedMessage message )
{
super( message );
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( "NAC:" );
sb.append( getNAC() );
sb.append( " PDUC LLID:" );
sb.append( getLogicalLinkID() );
sb.append( " ACCEPT SNDCP PACKET DATA ACTIVATE " );
sb.append( getNetworkAddressType() );
sb.append( " " );
sb.append( getIPAddress() );
sb.append( " NSAPI:" );
sb.append( getNSAPI() );
sb.append( " MTU:" );
sb.append( getMaximumTransmissionUnit() );
sb.append( " CRC[" );
sb.append( getErrorStatus() );
sb.append( "]" );
sb.append( " PACKET #" );
sb.append( getPacketSequenceNumber() );
if( isFinalFragment() && getFragmentSequenceNumber() == 0 )
{
sb.append( ".C" );
}
else
{
sb.append( "." );
sb.append( getFragmentSequenceNumber() );
if( isFinalFragment() )
{
sb.append( "C" );
}
}
sb.append( " " );
return sb.toString();
}
/**
* Network Service Access Point Identifier - up to 14 NSAPI's can be
* allocated to the mobile with each NSAPI to be used for a specific
* protocol layer.
*/
public int getNSAPI()
{
return mMessage.getInt( NSAPI );
}
public int getPDUPriorityMaximum()
{
return mMessage.getInt( PDUPM );
}
public String getReadyTimer()
{
switch( mMessage.getInt( READY ) )
{
case 1:
return "1 Second";
case 2:
return "2 Seconds";
case 3:
return "4 Seconds";
case 4:
return "6 Seconds";
case 5:
return "8 Seconds";
case 6:
return "10 Seconds";
case 7:
return "15 Seconds";
case 8:
return "20 Seconds";
case 9:
return "25 Seconds";
case 10:
return "30 Seconds";
case 11:
return "60 Seconds";
case 12:
return "120 Seconds";
case 13:
return "180 Seconds";
case 14:
return "300 Seconds";
case 15:
return "Always in Ready";
}
return "UNKNOWN";
}
public String getStandbyTimer()
{
switch( mMessage.getInt( STANDBY ) )
{
case 1:
return "10 Seconds";
case 2:
return "30 Seconds";
case 3:
return "1 Minutes";
case 4:
return "5 Minutes";
case 5:
return "10 Minutes";
case 6:
return "30 Minutes";
case 7:
return "1 Hour";
case 8:
return "2 Hours";
case 9:
return "4 Hours";
case 10:
return "8 Hours";
case 11:
return "12 Hours";
case 12:
return "24 Hours";
case 13:
return "48 Hours";
case 14:
return "72 Hours";
case 15:
return "Always in Ready";
}
return "Unknown";
}
public String getNetworkAddressType()
{
return mMessage.getInt( NAT ) == 0 ? "IPV4 STATIC" : "IPV4 DYNAMIC";
}
public String getIPAddress()
{
StringBuilder sb = new StringBuilder();
sb.append( mMessage.getInt( IP_1 ) );
sb.append( "." );
sb.append( mMessage.getInt( IP_2 ) );
sb.append( "." );
sb.append( mMessage.getInt( IP_3 ) );
sb.append( "." );
sb.append( mMessage.getInt( IP_4 ) );
return sb.toString();
}
public boolean hasIPHeaderCompression()
{
return mMessage.getInt( IPHC ) == 1;
}
public boolean hasUserDataPayloadCompression()
{
return mMessage.getInt( UDPC ) == 1;
}
public int getTCPStateSlots()
{
return mMessage.getInt( TCPSS );
}
public int getUDPStateSlots()
{
return mMessage.getInt( UDPSS );
}
public String getMaximumTransmissionUnit()
{
int mtu = mMessage.getInt( MTU );
switch( mtu )
{
case 1:
return "296 BYTES";
case 2:
return "510 BYTES";
case 3:
return "1020 BYTES";
case 4:
return "1500 BYTES";
default:
return "UNK-" + mtu;
}
}
public MDPConfigurationOption getMDPConfigurationOption()
{
return MDPConfigurationOption.fromValue( mMessage.getInt( MDPCO ) );
}
public String getDataAccessControl()
{
return mMessage.getHex( DATA_ACCESS_CONTROL, 4 );
}
}
<file_sep>package dsp.gain;
public interface GainController
{
public abstract void increase();
public abstract void decrease();
public abstract void reset();
}<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 alias.mpt1327;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JButton;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import controller.ConfigurableNode;
public class MPT1327IDEditor extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private MPT1327IDNode mMPT1327IDNode;
private JTextField mTextIdent;
public MPT1327IDEditor( MPT1327IDNode fsNode )
{
mMPT1327IDNode = fsNode;
initGUI();
}
private void initGUI()
{
setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][grow]" ) );
add( new JLabel( "MPT-1327 Radio or Group ID" ), "span,align center" );
add( new JLabel( "ID:" ) );
mTextIdent = new JTextField( mMPT1327IDNode.getMPT1327ID().getIdent() );
add( mTextIdent, "growx,push" );
JButton btnSave = new JButton( "Save" );
btnSave.addActionListener( MPT1327IDEditor.this );
add( btnSave, "growx,push" );
JButton btnReset = new JButton( "Reset" );
btnReset.addActionListener( MPT1327IDEditor.this );
add( btnReset, "growx,push" );
}
@Override
public void actionPerformed( ActionEvent e )
{
String command = e.getActionCommand();
if( command.contentEquals( "Save" ) )
{
String ident = mTextIdent.getText();
if( ident != null )
{
mMPT1327IDNode.getMPT1327ID().setIdent( ident );
((ConfigurableNode)mMPT1327IDNode.getParent()).sort();
mMPT1327IDNode.save();
mMPT1327IDNode.show();
}
else
{
JOptionPane.showMessageDialog( MPT1327IDEditor.this, "Please enter a MPT1327 unit ID" );
}
}
else if( command.contentEquals( "Reset" ) )
{
mTextIdent.setText( mMPT1327IDNode.getMPT1327ID().getIdent() );
}
mMPT1327IDNode.refresh();
}
}
<file_sep>package spectrum.converter;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import spectrum.DFTProcessor;
public class ComplexDecibelConverter extends DFTResultsConverter
{
private final static Logger mLog =
LoggerFactory.getLogger( DFTResultsConverter.class );
/**
* Converts the output of the JTransforms FloatFFT_1D.complexForward()
* calculation into a normalized power spectrum in decibels, per description
* in Lyons, Understanding Digital Signal Processing, 3e, page 141.
*/
@Override
public void receive( float[] results )
{
float[] processed = new float[ results.length / 2 ];
/* Output from JTransforms 3.0 has the lower and upper halves of the
* spectrum swapped. */
int half = processed.length / 2;
for( int x = 0; x < results.length; x += 2 )
{
float magnitude = (float)Math.sqrt( results[ x ] *
results[ x ] + results[ x + 1 ] * results[ x + 1 ] );
/* Place upper half of magnitudes in lower half of results, vice-versa */
if( x / 2 >= half )
{
processed[ x / 2 - half ] = magnitude;
}
else
{
processed[ x / 2 + half ] = magnitude;
}
}
/* Use the DC component as the largest magnitude value to keep the
* display from jumping when a strong bursting signal exists */
float largestMagnitude = processed[ half ];
if( largestMagnitude > 0 )
{
/* Convert magnitudes to normized power spectrum dBm */
for( int i = 0; i < processed.length; i++ )
{
processed[ i ] = 20.0f *
(float)Math.log10( processed[ i ] / largestMagnitude );
}
dispatch( processed );
}
}
}
<file_sep>package decode.p25.message.tsbk;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.reference.DataUnitID;
public abstract class GroupMultiChannelGrant extends ChannelGrant
implements IdentifierReceiver
{
public static final int[] CHANNEL_IDENTIFIER_1 = { 80,81,82,83 };
public static final int[] CHANNEL_NUMBER_1 = { 84,85,86,87,
88,89,90,91,92,93,94,95 };
public static final int[] GROUP_ADDRESS_1 = { 96,97,98,99,100,101,102,103,
104,105,106,107,108,109,110,111 };
public static final int[] CHANNEL_IDENTIFIER_2 = { 112,113,114,115 };
public static final int[] CHANNEL_NUMBER_2 = { 116,117,118,119,120,121,122,
123,124,125,126,127 };
public static final int[] GROUP_ADDRESS_2 = { 128,129,130,131,132,133,134,
135,136,137,138,139,140,141,142,143 };
private IBandIdentifier mIdentifierUpdate1;
private IBandIdentifier mIdentifierUpdate2;
public GroupMultiChannelGrant( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " CHAN1:" );
sb.append( getChannelIdentifier1() + "/" + getChannelNumber1() );
sb.append( " GRP1:" );
sb.append( getGroupAddress1() );
if( hasChannelNumber2() )
{
sb.append( " CHAN2:" );
sb.append( getChannelIdentifier2() + "/" + getChannelNumber2() );
sb.append( " GRP2:" );
sb.append( getGroupAddress2() );
}
return sb.toString();
}
public int getChannelIdentifier1()
{
return mMessage.getInt( CHANNEL_IDENTIFIER_1 );
}
public int getChannelNumber1()
{
return mMessage.getInt( CHANNEL_NUMBER_1 );
}
public String getChannel1()
{
return getChannelIdentifier1() + "-" + getChannelNumber1();
}
public String getGroupAddress1()
{
return mMessage.getHex( GROUP_ADDRESS_1, 4 );
}
public int getChannelIdentifier2()
{
return mMessage.getInt( CHANNEL_IDENTIFIER_2 );
}
public int getChannelNumber2()
{
return mMessage.getInt( CHANNEL_NUMBER_2 );
}
public String getChannel2()
{
return getChannelIdentifier2() + "-" + getChannelNumber2();
}
public String getGroupAddress2()
{
return mMessage.getHex( GROUP_ADDRESS_2, 4 );
}
public boolean hasChannelNumber2()
{
return mMessage.getInt( CHANNEL_NUMBER_2 ) !=
mMessage.getInt( CHANNEL_NUMBER_1 );
}
@Override
public String getFromID()
{
return getGroupAddress1();
}
@Override
public String getToID()
{
return getGroupAddress2();
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
if( identifier == getChannelIdentifier1() )
{
mIdentifierUpdate1 = message;
}
if( hasChannelNumber2() && identifier == getChannelIdentifier2() )
{
mIdentifierUpdate2 = message;
}
}
@Override
public int[] getIdentifiers()
{
int[] identifiers;
if( hasChannelNumber2() )
{
identifiers = new int[ 2 ];
identifiers[ 0 ] = getChannelIdentifier1();
identifiers[ 1 ] = getChannelIdentifier2();
}
else
{
identifiers = new int[ 1 ];
identifiers[ 0 ] = getChannelIdentifier1();
}
return identifiers;
}
public long getDownlinkFrequency1()
{
return calculateDownlink( mIdentifierUpdate1, getChannelNumber() );
}
public long getUplinkFrequency1()
{
return calculateUplink( mIdentifierUpdate1, getChannelNumber() );
}
public long getDownlinkFrequency2()
{
return calculateDownlink( mIdentifierUpdate2, getChannelNumber() );
}
public long getUplinkFrequency2()
{
return calculateUplink( mIdentifierUpdate2, getChannelNumber() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode;
import controller.channel.ChannelNode;
import decode.config.DecodeConfiguration;
import decode.ltrnet.LTRNetEditor;
import decode.ltrstandard.LTRStandardEditor;
import decode.mpt1327.MPT1327Editor;
import decode.nbfm.NBFMEditor;
import decode.p25.P25Editor;
import decode.passport.PassportEditor;
public class DecodeEditorFactory
{
public static DecodeEditor getPanel( DecodeConfiguration config,
ChannelNode channelNode )
{
DecodeEditor configuredPanel;
switch( config.getDecoderType() )
{
case NBFM:
configuredPanel = new NBFMEditor( config );
break;
case LTR_STANDARD:
configuredPanel = new LTRStandardEditor( config );
break;
case LTR_NET:
configuredPanel = new LTRNetEditor( config );
break;
case MPT1327:
configuredPanel = new MPT1327Editor( config, channelNode );
break;
case PASSPORT:
configuredPanel = new PassportEditor( config );
break;
case P25_PHASE1:
configuredPanel = new P25Editor( config );
break;
default:
configuredPanel = new DecodeEditor( config );
break;
}
return configuredPanel;
}
}
<file_sep>package decode.p25.message.tsbk.motorola;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.reference.DataUnitID;
public class ControlChannelBaseStationIdentification extends MotorolaTSBKMessage
implements IdentifierReceiver
{
public static final int[] CHARACTER_1 = { 80,81,82,83,84,85 };
public static final int[] CHARACTER_2 = { 86,87,88,89,90,91 };
public static final int[] CHARACTER_3 = { 92,93,94,95,96,97 };
public static final int[] CHARACTER_4 = { 98,99,100,101,102,103 };
public static final int[] CHARACTER_5 = { 104,105,106,107,108,109 };
public static final int[] CHARACTER_6 = { 110,111,112,113,114,115 };
public static final int[] CHARACTER_7 = { 116,117,118,119,120,121 };
public static final int[] CHARACTER_8 = { 122,123,124,125,126,127 };
public static final int[] IDENTIFIER = { 128,129,130,131 };
public static final int[] CHANNEL = { 132,133,134,135,136,137,138,139,140,
141,142,143 };
private IBandIdentifier mIdentifierUpdate;
public ControlChannelBaseStationIdentification( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return MotorolaOpcode.CONTROL_CHANNEL_ID.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " CHAN:" + getIdentifier() + "-" + getChannel() );
sb.append( " CWID:" + getCWID() );
sb.append( " DN:" + getDownlinkFrequency() );
sb.append( " UP:" + getUplinkFrequency() );
return sb.toString();
}
public String getCWID()
{
StringBuilder sb = new StringBuilder();
sb.append( getCharacter( CHARACTER_1 ) );
sb.append( getCharacter( CHARACTER_2 ) );
sb.append( getCharacter( CHARACTER_3 ) );
sb.append( getCharacter( CHARACTER_4 ) );
sb.append( getCharacter( CHARACTER_5 ) );
sb.append( getCharacter( CHARACTER_6 ) );
sb.append( getCharacter( CHARACTER_7 ) );
sb.append( getCharacter( CHARACTER_8 ) );
return sb.toString();
}
private String getCharacter( int[] field )
{
int value = mMessage.getInt( field );
if( value != 0 )
{
return String.valueOf( (char)( value + 43 ) );
}
return null;
}
public int getIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
public int getChannel()
{
return mMessage.getInt( CHANNEL );
}
public long getUplinkFrequency()
{
return calculateUplink( mIdentifierUpdate, getChannel() );
}
public long getDownlinkFrequency()
{
return calculateDownlink( mIdentifierUpdate, getChannel() );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
mIdentifierUpdate = message;
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 1 ];
identifiers[ 0 ] = getIdentifier();
return identifiers;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.mdc1200;
import message.Message;
import alias.Alias;
import controller.state.AuxChannelState;
import controller.state.ChannelState;
import controller.state.ChannelState.ChangedAttribute;
import controller.state.ChannelState.State;
public class MDCChannelState extends AuxChannelState
{
private String mFrom;
private Alias mFromAlias;
private String mTo;
private Alias mToAlias;
private String mMessage;
private String mMessageType;
private MDCActivitySummary mActivitySummary;
public MDCChannelState( ChannelState parentState )
{
super( parentState );
mActivitySummary = new MDCActivitySummary( parentState.getAliasList() );
}
@Override
public void reset()
{
setFrom( null );
setFromAlias( null );
setTo( null);
setToAlias( null );
setMessage( null );
setMessageType( null );
}
@Override
public void fade() {}
@Override
public void receive( Message message )
{
if( message instanceof MDCMessage )
{
mActivitySummary.receive( message );
MDCMessage mdc = (MDCMessage)message;
setFrom( mdc.getFromID() );
setFromAlias( mdc.getFromIDAlias() );
MDCMessageType type = mdc.getMessageType();
setMessageType( type.getLabel() );
StringBuilder sb = new StringBuilder();
switch( type )
{
case ACKNOWLEDGE:
case ANI:
case EMERGENCY:
case PAGING:
case STATUS:
default:
sb.append( "OPCODE " );
sb.append( String.valueOf( mdc.getOpcode() ) );
if( mdc.isBOT() )
{
sb.append( " TYPE:BOT" );
}
if( mdc.isEOT() )
{
sb.append( " TYPE:EOT" );
}
break;
}
setMessage( sb.toString() );
//Set the state to CALL on the parent channel state, so that the
//timer can track turning off any updates we apply
mParentChannelState.setState( State.CALL );
MDCCallEvent event = MDCCallEvent.getMDCCallEvent( mdc );
event.setAliasList( mParentChannelState.getAliasList() );
mParentChannelState.receiveCallEvent( event );
}
}
public String getFrom()
{
return mFrom;
}
public void setFrom( String from )
{
mFrom = from;
broadcastChange( ChangedAttribute.FROM_TALKGROUP );
}
public Alias getFromAlias()
{
return mFromAlias;
}
public void setFromAlias( Alias alias )
{
mFromAlias = alias;
broadcastChange( ChangedAttribute.FROM_TALKGROUP_ALIAS );
}
public String getTo()
{
return mTo;
}
public void setTo( String to )
{
mTo = to;
broadcastChange( ChangedAttribute.TO_TALKGROUP );
}
public Alias getToAlias()
{
return mToAlias;
}
public void setToAlias( Alias alias )
{
mToAlias = alias;
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
}
public String getMessage()
{
return mMessage;
}
public void setMessage( String message )
{
mMessage = message;
broadcastChange( ChangedAttribute.MESSAGE );
}
public String getMessageType()
{
return mMessageType;
}
public void setMessageType( String type )
{
mMessageType = type;
broadcastChange( ChangedAttribute.MESSAGE_TYPE );
}
@Override
public String getActivitySummary()
{
return mActivitySummary.getSummary();
}
}
<file_sep>package spectrum;
import java.awt.Component;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.util.Arrays;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JLayeredPane;
import javax.swing.JMenu;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.SwingUtilities;
import net.miginfocom.swing.MigLayout;
import sample.Listener;
import sample.complex.ComplexBuffer;
import sample.real.RealSampleListener;
import settings.ColorSetting.ColorSettingName;
import settings.ColorSettingMenuItem;
import settings.Setting;
import settings.SettingChangeListener;
import settings.SettingsManager;
import source.Source.SampleType;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.FrequencyChangeEvent.Attribute;
import spectrum.converter.DFTResultsConverter;
import spectrum.converter.RealDecibelConverter;
import spectrum.menu.AveragingItem;
import spectrum.menu.DBScaleItem;
import spectrum.menu.FFTWidthItem;
import spectrum.menu.FFTWindowTypeItem;
import spectrum.menu.FrameRateItem;
import controller.ResourceManager;
import controller.channel.Channel;
import controller.channel.ChannelEvent;
import controller.channel.ChannelEventListener;
import dsp.filter.Filters;
import dsp.filter.FloatHalfBandFilter;
import dsp.filter.Window.WindowType;
public class ChannelSpectrumPanel extends JPanel
implements ChannelEventListener,
RealSampleListener,
SettingChangeListener,
SpectralDisplayAdjuster
{
private static final long serialVersionUID = 1L;
private static final String CHANNEL_SPECTRUM_AVERAGING_SIZE =
"channel_spectrum_averaging_size";
private ResourceManager mResourceManager;
private DFTProcessor mDFTProcessor = new DFTProcessor( SampleType.REAL );
private DFTResultsConverter mDFTConverter = new RealDecibelConverter();
private JLayeredPane mLayeredPane;
private SpectrumPanel mSpectrumPanel;
private ChannelOverlayPanel mOverlayPanel;
private Channel mCurrentChannel;
private int mSpectrumAveragingSize;
private int mSampleBufferSize = 2400;
private float[] mSamples = new float[ mSampleBufferSize ];
private int mSamplePointer = 0;
private DecimatingSampleAssembler mDecimatingSampleAssembler;
private AtomicBoolean mEnabled = new AtomicBoolean();
public ChannelSpectrumPanel( ResourceManager resourceManager )
{
mResourceManager = resourceManager;
mResourceManager.getSettingsManager().addListener( this );
mSpectrumPanel = new SpectrumPanel( mResourceManager );
mOverlayPanel = new ChannelOverlayPanel( mResourceManager );
mSpectrumAveragingSize = 10;
// mSpectrumAveragingSize = mResourceManager.getSettingsManager()
// .getIntegerSetting( CHANNEL_SPECTRUM_AVERAGING_SIZE, 10 ).getValue();
mSpectrumPanel.setAveraging( mSpectrumAveragingSize );
mDFTProcessor.addConverter( mDFTConverter );
mDFTConverter.addListener( mSpectrumPanel );
mDecimatingSampleAssembler = new DecimatingSampleAssembler( mDFTProcessor );
/* Set the DFTProcessor to the decimated 24kHz sample rate */
mDFTProcessor.frequencyChanged(
new FrequencyChangeEvent( Attribute.SAMPLE_RATE, 24000 ) );
initGui();
}
public void dispose()
{
setEnabled( false );
mDFTProcessor.dispose();
mResourceManager = null;
mCurrentChannel = null;
mDFTProcessor = null;
mSpectrumPanel = null;
}
public void setFrameRate( int framesPerSecond )
{
mSampleBufferSize = (int)( 48000 / framesPerSecond );
mDFTProcessor.setFrameRate( framesPerSecond );
}
private void initGui()
{
setLayout( new MigLayout( "insets 0 0 0 0 ",
"[grow,fill]",
"[grow,fill]") );
mLayeredPane = new JLayeredPane();
mLayeredPane.addComponentListener( new ResizeListener() );
MouseEventProcessor mouser = new MouseEventProcessor();
mOverlayPanel.addMouseListener( mouser );
mOverlayPanel.addMouseMotionListener( mouser );
mLayeredPane.add( mSpectrumPanel, new Integer( 0 ), 0 );
mLayeredPane.add( mOverlayPanel, new Integer( 1 ), 0 );
add( mLayeredPane );
}
public void setEnabled( boolean enabled )
{
if( enabled && mEnabled.compareAndSet( false, true ) )
{
start();
}
else if( !enabled && mEnabled.compareAndSet( true, false ) )
{
stop();
}
}
@Override
@SuppressWarnings( "incomplete-switch" )
public void channelChanged( ChannelEvent event )
{
switch( event.getEvent() )
{
case CHANGE_SELECTED:
if( !event.getChannel().isSelected() )
{
stop();
mCurrentChannel = null;
}
else
{
mCurrentChannel = event.getChannel();
if( mEnabled.get() )
{
start();
}
}
if( event.getChannel().isSelected() &&
mCurrentChannel != event.getChannel() )
{
stop();
mCurrentChannel = event.getChannel();
start();
}
break;
case CHANNEL_DELETED:
if( event.getChannel() == mCurrentChannel )
{
if( mEnabled.get() )
{
stop();
}
mCurrentChannel = null;
}
break;
case CHANGE_ENABLED:
if( event.getChannel() == mCurrentChannel &&
!event.getChannel().isProcessing() )
{
stop();
mCurrentChannel = null;
}
break;
}
}
private void start()
{
if( mEnabled.get() && mCurrentChannel != null && mCurrentChannel.isProcessing() )
{
mCurrentChannel.getProcessingChain().addRealListener( (RealSampleListener)this );
mDFTProcessor.start();
}
}
private void stop()
{
if( mCurrentChannel != null && mCurrentChannel.isProcessing() )
{
mCurrentChannel.getProcessingChain().removeRealListener( (RealSampleListener)this );
}
mDFTProcessor.stop();
mSpectrumPanel.clearSpectrum();
}
@Override
public void settingChanged( Setting setting )
{
if( mSpectrumPanel != null )
{
mSpectrumPanel.settingChanged( setting );
}
if( mOverlayPanel != null )
{
mOverlayPanel.settingChanged( setting );
}
}
@Override
public void settingDeleted( Setting setting )
{
if( mSpectrumPanel != null )
{
mSpectrumPanel.settingDeleted( setting );
}
if( mOverlayPanel != null )
{
mOverlayPanel.settingDeleted( setting );
}
}
@Override
public void receive( float sample )
{
mDecimatingSampleAssembler.receive( sample );
}
/**
* Monitors the sizing of the layered pane and resizes the spectrum and
* channel panels whenever the layered pane is resized
*/
public class ResizeListener implements ComponentListener
{
@Override
public void componentResized( ComponentEvent e )
{
Component c = e.getComponent();
mSpectrumPanel.setBounds( 0, 0, c.getWidth(), c.getHeight() );
mOverlayPanel.setBounds( 0, 0, c.getWidth(), c.getHeight() );
}
@Override
public void componentHidden( ComponentEvent arg0 ) {}
@Override
public void componentMoved( ComponentEvent arg0 ) {}
@Override
public void componentShown( ComponentEvent arg0 ) {}
}
/**
* Mouse event handler for the channel panel.
*/
public class MouseEventProcessor implements MouseMotionListener, MouseListener
{
@Override
public void mouseMoved( MouseEvent event )
{
update( event );
}
@Override
public void mouseDragged( MouseEvent event )
{
update( event );
}
private void update( MouseEvent event )
{
if( event.getComponent() == mOverlayPanel )
{
mOverlayPanel.setCursorLocation( event.getPoint() );
}
}
@Override
public void mouseEntered( MouseEvent e )
{
if( e.getComponent() == mOverlayPanel )
{
mOverlayPanel.setCursorVisible( true );
}
}
@Override
public void mouseExited( MouseEvent e )
{
mOverlayPanel.setCursorVisible( false );
}
/**
* Displays the context menu.
*/
@Override
public void mouseClicked( MouseEvent event )
{
if( SwingUtilities.isRightMouseButton( event ) )
{
JPopupMenu contextMenu = new JPopupMenu();
/**
* Color Menus
*/
JMenu colorMenu = new JMenu( "Color" );
SettingsManager sm = mResourceManager.getSettingsManager();
colorMenu.add( new ColorSettingMenuItem( sm,
ColorSettingName.SPECTRUM_CURSOR ) );
colorMenu.add( new ColorSettingMenuItem( sm,
ColorSettingName.SPECTRUM_LINE ) );
colorMenu.add( new ColorSettingMenuItem( sm,
ColorSettingName.SPECTRUM_BACKGROUND ) );
colorMenu.add( new ColorSettingMenuItem( sm,
ColorSettingName.SPECTRUM_GRADIENT_BOTTOM ) );
colorMenu.add( new ColorSettingMenuItem( sm,
ColorSettingName.SPECTRUM_GRADIENT_TOP ) );
contextMenu.add( colorMenu );
/**
* Display items: fft and frame rate
*/
JMenu displayMenu = new JMenu( "Display" );
contextMenu.add( displayMenu );
/**
* Averaging menu
*/
JMenu averagingMenu = new JMenu( "Averaging" );
averagingMenu.add(
new AveragingItem( ChannelSpectrumPanel.this, 4 ) );
displayMenu.add( averagingMenu );
/**
* Baseline menu
*/
JMenu baselineMenu = new JMenu( "Baseline" );
baselineMenu.add(
new DBScaleItem( ChannelSpectrumPanel.this, 50 ) );
displayMenu.add( baselineMenu );
/**
* FFT width
*/
JMenu fftWidthMenu = new JMenu( "FFT Width" );
displayMenu.add( fftWidthMenu );
for( FFTWidth width: FFTWidth.values() )
{
fftWidthMenu.add( new FFTWidthItem( mDFTProcessor, width ) );
}
/**
* DFT Processor Frame Rate
*/
JMenu frameRateMenu = new JMenu( "Frame Rate" );
displayMenu.add( frameRateMenu );
frameRateMenu.add( new FrameRateItem( mDFTProcessor, 14 ) );
frameRateMenu.add( new FrameRateItem( mDFTProcessor, 16 ) );
frameRateMenu.add( new FrameRateItem( mDFTProcessor, 18 ) );
frameRateMenu.add( new FrameRateItem( mDFTProcessor, 20 ) );
frameRateMenu.add( new FrameRateItem( mDFTProcessor, 25 ) );
frameRateMenu.add( new FrameRateItem( mDFTProcessor, 30 ) );
frameRateMenu.add( new FrameRateItem( mDFTProcessor, 40 ) );
frameRateMenu.add( new FrameRateItem( mDFTProcessor, 50 ) );
/**
* FFT Window Type
*/
JMenu fftWindowType = new JMenu( "Window Type" );
displayMenu.add( fftWindowType );
for( WindowType type: WindowType.values() )
{
fftWindowType.add(
new FFTWindowTypeItem( mDFTProcessor, type ) );
}
if( contextMenu != null )
{
contextMenu.show( mOverlayPanel,
event.getX(),
event.getY() );
}
}
}
@Override
public void mousePressed( MouseEvent e ) {}
@Override
public void mouseReleased( MouseEvent e ) {}
}
@Override
public int getAveraging()
{
return mSpectrumPanel.getAveraging();
}
@Override
public void setAveraging( int averaging )
{
mSpectrumPanel.setAveraging( averaging );
}
@Override
public int getDBScale()
{
return mSpectrumPanel.getDBScale();
}
@Override
public void setDBScale( int baseline )
{
mSpectrumPanel.setDBScale( baseline );
}
public class DecimatingSampleAssembler
{
private FloatHalfBandFilter mDecimationFilter = new FloatHalfBandFilter(
Filters.FIR_HALF_BAND_31T_ONE_EIGHTH_FCO, 1.0002 );
private SampleAssembler mSampleAssembler;
public DecimatingSampleAssembler( Listener<ComplexBuffer> listener )
{
mSampleAssembler = new SampleAssembler( listener );
mDecimationFilter.setListener( mSampleAssembler );
}
public void receive( float sample )
{
mDecimationFilter.receive( sample );
}
}
public class SampleAssembler implements RealSampleListener
{
private Listener<ComplexBuffer> mListener;
public SampleAssembler( Listener<ComplexBuffer> listener )
{
mListener = listener;
}
@Override
public void receive( float sample )
{
mSamples[ mSamplePointer++ ] = sample;
if( mSamplePointer >= mSamples.length )
{
if( mEnabled.get() )
{
float[] copy = Arrays.copyOf( mSamples, mSamples.length );
mListener.receive( new ComplexBuffer( copy ) );
}
mSamplePointer = 0;
if( mSamples.length != mSampleBufferSize )
{
mSamples = new float[ mSampleBufferSize ];
}
}
}
}
}
<file_sep>package decode.p25.message.ldu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.ldu.LDU1Message;
import decode.p25.reference.LinkControlOpcode;
public class CallAlert extends LDU1Message
{
private final static Logger mLog =
LoggerFactory.getLogger( CallAlert.class );
public static final int[] TARGET_ADDRESS = { 536,537,538,539,540,541,546,
547,548,549,550,551,556,557,558,559,560,561,566,567,568,569,570,571 };
public static final int[] SOURCE_ADDRESS = { 720,721,722,723,724,725,730,
731,732,733,734,735,740,741,742,743,744,745,750,751,752,753,754,755 };
public CallAlert( LDU1Message message )
{
super( message );
}
@Override
public String getEventType()
{
return LinkControlOpcode.CALL_ALERT.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " SRC ADDR: " + getSourceAddress() );
sb.append( " TGT ADDR: " + getTargetAddress() );
return sb.toString();
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
public String getSourceAddress()
{
return mMessage.getHex( SOURCE_ADDRESS, 6 );
}
}
<file_sep>package decode.fleetsync2;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import message.Message;
import filter.Filter;
import filter.FilterElement;
public class FleetsyncMessageFilter extends Filter<Message>
{
private HashMap<FleetsyncMessageType, FilterElement<FleetsyncMessageType>> mElements =
new HashMap<FleetsyncMessageType, FilterElement<FleetsyncMessageType>>();
public FleetsyncMessageFilter()
{
super( "Fleetsync Message Filter" );
for( FleetsyncMessageType type: FleetsyncMessageType.values() )
{
if( type != FleetsyncMessageType.UNKNOWN )
{
mElements.put( type, new FilterElement<FleetsyncMessageType>( type ) );
}
}
}
@Override
public boolean passes( Message message )
{
if( mEnabled && canProcess( message ) )
{
FleetsyncMessage fleet = (FleetsyncMessage)message;
if( mElements.containsKey( fleet.getMessageType() ) )
{
return mElements.get( fleet.getMessageType() ).isEnabled();
}
}
return false;
}
@Override
public boolean canProcess( Message message )
{
return message instanceof FleetsyncMessage;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return new ArrayList<FilterElement<?>>( mElements.values() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.lj1200;
import java.text.SimpleDateFormat;
import map.Plottable;
import message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alias.Alias;
import alias.AliasList;
import bits.BinaryMessage;
import edac.CRC;
import edac.CRCLJ;
public class LJ1200TransponderMessage extends Message
{
private final static Logger mLog = LoggerFactory.getLogger( LJ1200TransponderMessage.class );
public static int[] SYNC = { 0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15 };
public static int[] MESSAGE_CRC = { 64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79 };
private static SimpleDateFormat mSDF = new SimpleDateFormat( "yyyyMMdd HHmmss" );
private BinaryMessage mMessage;
private AliasList mAliasList;
private CRC mCRC;
public LJ1200TransponderMessage( BinaryMessage message, AliasList list )
{
mMessage = message;
mAliasList = list;
checkCRC();
switch( mCRC )
{
case CORRECTED:
mLog.debug( "CORR:" + message.toString() );
break;
case FAILED_CRC:
mLog.debug( "FAIL:" + message.toString() );
break;
case PASSED:
mLog.debug( "PASS:" + message.toString() );
break;
case UNKNOWN:
mLog.debug( "UNKNOWN:" + message.toString() );
break;
}
}
private void checkCRC()
{
mCRC = CRC.UNKNOWN;
}
public boolean isValid()
{
// return mCRC == CRC.PASSED || mCRC == CRC.CORRECTED;
/* Override validity check until proper CRC is implemented */
return true;
}
public String getCRC()
{
return mMessage.getHex( MESSAGE_CRC, 4 );
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( "TRANSPONDER TEST" );
return sb.toString();
}
/**
* Pads spaces onto the end of the value to make it 'places' long
*/
public String pad( String value, int places, String padCharacter )
{
StringBuilder sb = new StringBuilder();
sb.append( value );
while( sb.length() < places )
{
sb.append( padCharacter );
}
return sb.toString();
}
/**
* Pads an integer value with additional zeroes to make it decimalPlaces long
*/
public String format( int number, int decimalPlaces )
{
StringBuilder sb = new StringBuilder();
int paddingRequired = decimalPlaces - ( String.valueOf( number ).length() );
for( int x = 0; x < paddingRequired; x++)
{
sb.append( "0" );
}
sb.append( number );
return sb.toString();
}
@Override
public String getBinaryMessage()
{
return mMessage.toString();
}
@Override
public String getProtocol()
{
return "LJ-1200";
}
@Override
public String getEventType()
{
return "TRANSPONDER";
}
@Override
public String getFromID()
{
return null;
}
@Override
public Alias getFromIDAlias()
{
return null;
}
@Override
public String getToID()
{
return null;
}
@Override
public Alias getToIDAlias()
{
return null;
}
@Override
public String getMessage()
{
return toString();
}
@Override
public String getErrorStatus()
{
return mCRC.getDisplayText();
}
@Override
public Plottable getPlottable()
{
return null;
}
}
<file_sep>package decode.p25.audio;
import jmbe.iface.AudioConversionLibrary;
import jmbe.iface.AudioConverter;
import message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import audio.AudioFormats;
import audio.AudioPacket;
import audio.IAudioOutput;
import audio.MonoAudioOutput;
import audio.SquelchListener;
import audio.inverted.AudioType;
import audio.inverted.IAudioTypeListener;
import controller.ResourceManager;
import decode.p25.message.ldu.LDUMessage;
import decode.p25.message.tdu.TDUMessage;
import decode.p25.message.tdu.lc.TDULinkControlMessage;
/**
* P25 Phase 1 IMBE Audio Output converter. Processes 18-byte IMBE audio frames
* and produces PCM 48k MONO 16-bit sample output.
*
* Note: this class depends on the external JMBE library.
*/
public class P25AudioOutput implements IAudioOutput, Listener<Message>,
SquelchListener, IAudioTypeListener
{
private final static Logger mLog = LoggerFactory.getLogger( P25AudioOutput.class );
private static final String IMBE_CODEC = "IMBE";
private boolean mCanConvertAudio = false;
private boolean mEncryptedAudio = false;
private AudioConverter mAudioConverter;
private MonoAudioOutput mAudioOutput = new MonoAudioOutput();
public P25AudioOutput( ResourceManager resourceManager )
{
loadConverter();
}
/**
* Primary inject point for p25 imbe audio frame messages. Each LDU audio
* message contains 9 imbe voice frames. If the audio is not encrypted,
* we insert each audio frame asynchronously into the audio converter.
*/
public void receive( Message message )
{
if( mCanConvertAudio )
{
if( message instanceof LDUMessage )
{
LDUMessage ldu = (LDUMessage)message;
/* If we detect a valid LDU message with the encryption flag
* set to true, we toggle the encrypted audio state until we
* receive the first TDU or TDULC message, then reset it. */
if( ldu.isValid() && ldu.isEncrypted() )
{
mEncryptedAudio = true;
}
if( !mEncryptedAudio && mAudioConverter != null )
{
for( byte[] frame: ((LDUMessage)message).getIMBEFrames() )
{
byte[] audio = mAudioConverter.convert( frame );
mAudioOutput.receive( new AudioPacket( "P25 Audio", audio, 1 ) );
}
}
}
else if( message instanceof TDUMessage || message instanceof TDULinkControlMessage )
{
mEncryptedAudio = false;
}
}
}
/**
* Loads audio frame processing chain. Constructs an imbe targetdataline
* to receive the raw imbe frames. Adds an IMBE to 8k PCM format conversion
* stream wrapper. Finally, adds an upsampling (8k to 48k) stream wrapper.
*/
private void loadConverter()
{
AudioConversionLibrary library = null;
try
{
@SuppressWarnings( "rawtypes" )
Class temp = Class.forName( "jmbe.JMBEAudioLibrary" );
library = (AudioConversionLibrary)temp.newInstance();
mAudioConverter = library.getAudioConverter( IMBE_CODEC,
AudioFormats.PCM_SIGNED_48KHZ_16BITS );
if( mAudioConverter != null )
{
mCanConvertAudio = true;
mLog.info( "JMBE audio conversion library successfully loaded"
+ " - P25 audio will be available" );
}
else
{
mLog.info( "JMBE audio conversion library NOT FOUND" );
}
}
catch ( ClassNotFoundException e1 )
{
mLog.error( "Couldn't find/load JMBE audio conversion library" );
}
catch ( InstantiationException e1 )
{
mLog.error( "Couldn't instantiate JMBE audio conversion library class" );
}
catch ( IllegalAccessException e1 )
{
mLog.error( "Couldn't load JMBE audio conversion library due to "
+ "security restrictions" );
}
}
@Override
public void setAudioPlaybackEnabled( boolean enabled )
{
mAudioOutput.setMuted( !enabled );
}
@Override
public void dispose()
{
mAudioOutput.dispose();
}
@Override
public void setSquelch( SquelchState state )
{
/* not implemented */
}
@Override
public void setAudioType( AudioType type )
{
//Not implemented
}
}<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;
import controller.Editor;
import controller.channel.AbstractChannelEditor;
import controller.channel.ChannelNode;
import controller.channel.ChannelValidationException;
import decode.config.DecodeConfigFactory;
import decode.config.DecodeConfiguration;
public class DecodeComponentEditor extends AbstractChannelEditor
{
private static final long serialVersionUID = 1L;
private JComboBox<DecoderType> mComboDecoders;
private DecodeEditor mEditor;
public DecodeComponentEditor( ChannelNode channelNode )
{
super( channelNode );
/**
* ComboBox: Decoders
*/
mComboDecoders = new JComboBox<DecoderType>();
DefaultComboBoxModel<DecoderType> model =
new DefaultComboBoxModel<DecoderType>();
for( DecoderType type: DecoderType.getAvailableDecoders() )
{
model.addElement( type );
}
mComboDecoders.setModel( model );
mComboDecoders.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
DecoderType selected = mComboDecoders
.getItemAt( mComboDecoders.getSelectedIndex() );
if( selected != null )
{
DecodeConfiguration config;
if( mChannelNode.getChannel()
.getDecodeConfiguration().getDecoderType() ==
selected )
{
config = mChannelNode.getChannel()
.getDecodeConfiguration();
}
else
{
config = DecodeConfigFactory
.getDecodeConfiguration( selected );
}
//Remove the existing one
if( mEditor != null )
{
remove( mEditor );
}
//Change to the new one
mEditor = DecodeEditorFactory.getPanel( config, mChannelNode );
add( mEditor, "span 2" );
revalidate();
repaint();
}
}
});
add( mComboDecoders, "wrap" );
reset();
}
public void reset()
{
final DecoderType decoder = mChannelNode.getChannel()
.getDecodeConfiguration().getDecoderType();
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run() {
mComboDecoders.setSelectedItem( decoder );
mComboDecoders.requestFocus();
mComboDecoders.requestFocusInWindow();
}
});
}
@Override
public void save()
{
if( mEditor != null )
{
mEditor.save();
}
//The component that calls save will invoke the change broadcast
mChannelNode.getChannel()
.setDecodeConfiguration( mEditor.getConfig(), false );
}
/**
* Validates the editor against the current decode editor
*/
@Override
public void validate( Editor editor ) throws ChannelValidationException
{
super.validate( editor );
mEditor.validate( editor );
}
}
<file_sep>package decode.p25.message.tsbk;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.reference.DataUnitID;
public abstract class GroupChannelGrantExplicit extends ChannelGrant
{
public static final int[] TRANSMIT_IDENTIFIER = { 96,97,98,99 };
public static final int[] TRANSMIT_NUMBER = { 100,101,102,103,
104,105,106,107,108,109,110,111 };
public static final int[] RECEIVE_IDENTIFIER = { 112,113,114,115 };
public static final int[] RECEIVE_NUMBER = { 116,117,118,119,
120,121,122,123,124,125,126,127 };
public static final int[] GROUP_ADDRESS = { 128,129,130,131,132,133,134,135,
136,137,138,139,140,141,142,143 };
private IBandIdentifier mTransmitIdentifierUpdate;
private IBandIdentifier mReceiveIdentifierUpdate;
public GroupChannelGrantExplicit( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
if( isEmergency() )
{
sb.append( " EMERGENCY" );
}
sb.append( " XMIT:" );
sb.append( getTransmitChannelIdentifier() + "/" + getTransmitChannelNumber() );
sb.append( " RCV:" );
sb.append( getReceiveChannelIdentifier() + "/" + getReceiveChannelNumber() );
sb.append( " GRP:" );
sb.append( getGroupAddress() );
return sb.toString();
}
public int getTransmitChannelIdentifier()
{
return mMessage.getInt( TRANSMIT_IDENTIFIER );
}
public int getTransmitChannelNumber()
{
return mMessage.getInt( TRANSMIT_NUMBER );
}
public String getTransmitChannel()
{
return getTransmitChannelIdentifier() + "-" + getTransmitChannelNumber();
}
public int getReceiveChannelIdentifier()
{
return mMessage.getInt( RECEIVE_IDENTIFIER );
}
public int getReceiveChannelNumber()
{
return mMessage.getInt( RECEIVE_NUMBER );
}
public String getReceiveChannel()
{
return getReceiveChannelIdentifier() + "-" + getReceiveChannelNumber();
}
public String getGroupAddress()
{
return mMessage.getHex( GROUP_ADDRESS, 4 );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
if( identifier == getTransmitChannelIdentifier() )
{
mTransmitIdentifierUpdate = message;
}
if( identifier == getReceiveChannelIdentifier() )
{
mReceiveIdentifierUpdate = message;
}
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 2 ];
identifiers[ 0 ] = getTransmitChannelIdentifier();
identifiers[ 1 ] = getReceiveChannelIdentifier();
return identifiers;
}
public long getDownlinkFrequency()
{
return calculateDownlink( mTransmitIdentifierUpdate, getTransmitChannelNumber() );
}
public long getUplinkFrequency()
{
return calculateUplink( mReceiveIdentifierUpdate, getReceiveChannelNumber() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.rtl.e4k;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.usb.UsbException;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.LibUsbException;
import source.SourceException;
import source.tuner.TunerConfiguration;
import source.tuner.TunerConfigurationAssignment;
import source.tuner.TunerType;
import source.tuner.rtl.RTL2832TunerController.SampleRate;
import source.tuner.rtl.e4k.E4KTunerController.E4KEnhanceGain;
import source.tuner.rtl.e4k.E4KTunerController.E4KGain;
import source.tuner.rtl.e4k.E4KTunerController.E4KLNAGain;
import source.tuner.rtl.e4k.E4KTunerController.E4KMixerGain;
import controller.ResourceManager;
public class E4KTunerConfigurationPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private final static Logger mLog =
LoggerFactory.getLogger( E4KTunerConfigurationPanel.class );
private ResourceManager mResourceManager;
private E4KTunerController mController;
private E4KTunerConfiguration mSelectedConfig;
private JButton mNewConfiguration;
private JButton mDeleteConfiguration;
private JComboBox<E4KTunerConfiguration> mComboConfigurations;
private JTextField mName;
private JSpinner mFrequencyCorrection;
private JSpinner mSampleRateCorrection;
private JComboBox<E4KGain> mComboMasterGain;
private JComboBox<E4KMixerGain> mComboMixerGain;
private JComboBox<E4KLNAGain> mComboLNAGain;
private JComboBox<E4KEnhanceGain> mComboEnhanceGain;
private JComboBox<SampleRate> mComboSampleRate;
public E4KTunerConfigurationPanel( ResourceManager resourceManager,
E4KTunerController controller )
{
mResourceManager = resourceManager;
mController = controller;
init();
}
/**
* Initializes the gui components
*/
private void init()
{
setLayout( new MigLayout( "fill,wrap 2", "[grow,right][grow]", "[][][][][][][grow]" ) );
/**
* Tuner configuration selector
*/
mComboConfigurations = new JComboBox<E4KTunerConfiguration>();
mComboConfigurations.setModel( getModel() );
/* Determine which tuner configuration should be selected/displayed */
TunerConfigurationAssignment savedConfig = mResourceManager
.getSettingsManager().getSelectedTunerConfiguration(
TunerType.ELONICS_E4000, mController.getUniqueID() );
if( savedConfig != null )
{
mSelectedConfig = getNamedConfiguration(
savedConfig.getTunerConfigurationName() );
}
/* If we couldn't determine the saved/selected config, use the first one */
if( mSelectedConfig == null )
{
mSelectedConfig = mComboConfigurations.getItemAt( 0 );
//Store this config as the default for this tuner at this address
mResourceManager.getSettingsManager()
.setSelectedTunerConfiguration(
TunerType.ELONICS_E4000,
mController.getUniqueID(), mSelectedConfig );
}
mComboConfigurations.setSelectedItem( mSelectedConfig );
mComboConfigurations.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
E4KTunerConfiguration selected =
(E4KTunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
update( selected );
}
}
});
add( new JLabel( "Config:" ) );
add( mComboConfigurations, "growx,push" );
/**
* Tuner Configuration Name
*/
add( new JLabel( "Name:" ) );
mName = new JTextField();
mName.setText( mSelectedConfig.getName() );
mName.addFocusListener( new FocusListener()
{
@Override
public void focusLost( FocusEvent e )
{
/* Update the config name */
mSelectedConfig.setName( mName.getText() );
/* Reset this named config as the assigned config for this
* tuner */
mResourceManager.getSettingsManager()
.setSelectedTunerConfiguration(
TunerType.ELONICS_E4000,
mController.getUniqueID(), mSelectedConfig );
save();
}
@Override
public void focusGained( FocusEvent e ) {}
} );
add( mName, "growx,push" );
/**
* Frequency Correction
*/
SpinnerModel model =
new SpinnerNumberModel( 0.0, //initial value
-1000.0, //min
1000.0, //max
0.1 ); //step
mFrequencyCorrection = new JSpinner( model );
JSpinner.NumberEditor editor =
(JSpinner.NumberEditor)mFrequencyCorrection.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits( 1 );
editor.getTextField().setHorizontalAlignment( SwingConstants.CENTER );
mFrequencyCorrection.setValue( mSelectedConfig.getFrequencyCorrection() );
mFrequencyCorrection.addChangeListener( new ChangeListener()
{
@Override
public void stateChanged( ChangeEvent e )
{
final double value = ((SpinnerNumberModel)mFrequencyCorrection
.getModel()).getNumber().doubleValue();
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
mController.setFrequencyCorrection( value );
mSelectedConfig.setFrequencyCorrection( value );
save();
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
E4KTunerConfigurationPanel.this,
"E4K Tuner Controller - couldn't apply "
+ "frequency correction value: " + value +
e1.getLocalizedMessage() );
mLog.error( "E4K Tuner Controller - couldn't apply "
+ "frequency correction value: " + value, e1 );
}
}
} );
}
} );
add( new JLabel( "Correction PPM:" ) );
add( mFrequencyCorrection, "growx,push" );
/**
* Sample Rate
*/
mComboSampleRate = new JComboBox<>( SampleRate.values() );
mComboSampleRate.setSelectedItem( mSelectedConfig.getSampleRate() );
mComboSampleRate.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
SampleRate sampleRate =
(SampleRate)mComboSampleRate.getSelectedItem();
try
{
mController.setSampleRate( sampleRate );
mSelectedConfig.setSampleRate( sampleRate );
save();
}
catch ( SourceException | LibUsbException eSampleRate )
{
JOptionPane.showMessageDialog(
E4KTunerConfigurationPanel.this,
"E4K Tuner Controller - couldn't apply the sample "
+ "rate setting [" + sampleRate.getLabel() + "] " +
eSampleRate.getLocalizedMessage() );
mLog.error( "E4K Tuner Controller - couldn't apply sample "
+ "rate setting [" + sampleRate.getLabel() + "]",
eSampleRate );
}
}
} );
add( new JLabel( "Sample Rate:" ) );
add( mComboSampleRate, "growx,push" );
// /**
// * Sample Rate Correction
// */
// SpinnerModel sampleRateCorrectionModel =
// new SpinnerNumberModel( 0, //initial value
// -32768, //min
// 32767, //max
// 1 ); //step
//
// mSampleRateCorrection = new JSpinner( sampleRateCorrectionModel );
//
// JSpinner.NumberEditor sampleRateCorrectionEditor =
// (JSpinner.NumberEditor)mSampleRateCorrection.getEditor();
//
// DecimalFormat sampleRateCorrectionFormat =
// sampleRateCorrectionEditor.getFormat();
//
// sampleRateCorrectionFormat.setMinimumFractionDigits( 0 );
//
// sampleRateCorrectionEditor.getTextField()
// .setHorizontalAlignment( SwingConstants.CENTER );
//
// mSampleRateCorrection.addChangeListener( new ChangeListener()
// {
// @Override
// public void stateChanged( ChangeEvent e )
// {
// final int value = ((SpinnerNumberModel)mSampleRateCorrection
// .getModel()).getNumber().intValue();
//
// EventQueue.invokeLater( new Runnable()
// {
// @Override
// public void run()
// {
// try
// {
// mController.setSampleRateFrequencyCorrection( value );
// }
// catch ( SourceException | UsbException e1 )
// {
// JOptionPane.showMessageDialog(
// E4KTunerConfigurationPanel.this,
// "E4K Tuner Controller - couldn't apply "
// + "sample rate correction value: " + value +
// e1.getLocalizedMessage() );
//
// Log.error( "E4K Tuner Controller - couldn't apply "
// + "sample rate correction value: " + value +
// e1.getLocalizedMessage() );
// }
// }
// } );
// }
// } );
//
// add( mSampleRateCorrection );
// add( new JLabel( "Sample Rate Correction (ppm)" ), "wrap" );
/**
* Gain Controls
*/
JPanel gainPanel = new JPanel();
gainPanel.setLayout( new MigLayout( "fill", "[right][left][right][left]", "" ) );
gainPanel.setBorder( BorderFactory.createTitledBorder( "Gain" ) );
/* Master Gain Control */
mComboMasterGain = new JComboBox<E4KGain>( E4KGain.values() );
mComboMasterGain.setSelectedItem( mSelectedConfig.getMasterGain() );
mComboMasterGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
E4KGain gain = (E4KGain)mComboMasterGain.getSelectedItem();
mController.setGain( (E4KGain)mComboMasterGain.getSelectedItem(), true );
if( gain == E4KGain.MANUAL )
{
mComboMixerGain.setSelectedItem(
mController.getMixerGain( true ) );
mComboMixerGain.setEnabled( true );
mComboLNAGain.setSelectedItem(
mController.getLNAGain( true ) );
mComboLNAGain.setEnabled( true );
mComboEnhanceGain.setEnabled( true );
mComboEnhanceGain.setSelectedItem(
mController.getEnhanceGain( true ) );
}
else
{
mComboMixerGain.setEnabled( false );
mComboMixerGain.setSelectedItem( gain.getMixerGain() );
mComboLNAGain.setEnabled( false );
mComboLNAGain.setSelectedItem( gain.getLNAGain() );
mComboEnhanceGain.setEnabled( false );
mComboEnhanceGain.setSelectedItem( gain.getEnhanceGain() );
}
mSelectedConfig.setMasterGain( gain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
E4KTunerConfigurationPanel.this,
"E4K Tuner Controller - couldn't apply the gain "
+ "setting - " + e.getLocalizedMessage() );
mLog.error( "E4K Tuner Controller - couldn't apply "
+ "gain setting", e );
}
}
} );
mComboMasterGain.setToolTipText( "<html>Select <b>AUTOMATIC</b> for auto "
+ "gain, <b>MANUAL</b> to enable<br> independent control of "
+ "<i>Mixer</i>, <i>LNA</i> and <i>Enhance</i> gain<br>"
+ "settings, or one of the individual gain settings for<br>"
+ "semi-manual gain control</html>" );
gainPanel.add( new JLabel( "Master" ) );
gainPanel.add( mComboMasterGain );
/* Mixer Gain Control */
mComboMixerGain = new JComboBox<E4KMixerGain>( E4KMixerGain.values() );
mComboMixerGain.setSelectedItem( mSelectedConfig.getMixerGain() );
mComboMixerGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
E4KMixerGain mixerGain =
(E4KMixerGain)mComboMixerGain.getSelectedItem();
if( mComboMixerGain.isEnabled() )
{
mController.setMixerGain( mixerGain, true );
}
mSelectedConfig.setMixerGain( mixerGain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
E4KTunerConfigurationPanel.this,
"E4K Tuner Controller - couldn't apply the mixer "
+ "gain setting - " + e.getLocalizedMessage() );
mLog.error( "E4K Tuner Controller - couldn't apply mixer "
+ "gain setting", e );
}
}
} );
}
} );
mComboMixerGain.setToolTipText( "<html>Mixer Gain. Set master gain "
+ "to <b>MASTER</b> to enable adjustment</html>" );
mComboMixerGain.setEnabled( false );
gainPanel.add( new JLabel( "Mixer" ) );
gainPanel.add( mComboMixerGain, "wrap" );
/* LNA Gain Control */
mComboLNAGain = new JComboBox<E4KLNAGain>( E4KLNAGain.values() );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
mComboLNAGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
E4KLNAGain lnaGain = (E4KLNAGain)mComboLNAGain.getSelectedItem();
if( mComboLNAGain.isEnabled() )
{
mController.setLNAGain( lnaGain, true );
}
mSelectedConfig.setLNAGain( lnaGain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
E4KTunerConfigurationPanel.this,
"E4K Tuner Controller - couldn't apply the LNA "
+ "gain setting - " + e.getLocalizedMessage() );
mLog.error( "E4K Tuner Controller - couldn't apply LNA "
+ "gain setting - ", e );
}
}
} );
mComboLNAGain.setToolTipText( "<html>LNA Gain. Set master gain "
+ "to <b>MANUAL</b> to enable adjustment</html>" );
mComboLNAGain.setEnabled( false );
gainPanel.add( new JLabel( "LNA" ) );
gainPanel.add( mComboLNAGain );
/* Enhance Gain Control */
mComboEnhanceGain = new JComboBox<E4KEnhanceGain>( E4KEnhanceGain.values() );
mComboEnhanceGain.setSelectedItem( mSelectedConfig.getEnhanceGain() );
mComboEnhanceGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
E4KEnhanceGain enhanceGain =
(E4KEnhanceGain)mComboEnhanceGain.getSelectedItem();
if( mComboEnhanceGain.isEnabled() )
{
mController.setEnhanceGain( enhanceGain, true );
}
mSelectedConfig.setEnhanceGain( enhanceGain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
E4KTunerConfigurationPanel.this,
"E4K Tuner Controller - couldn't apply the enhance "
+ "gain setting - " + e.getLocalizedMessage() );
mLog.error( "E4K Tuner Controller - couldn't apply enhance "
+ "gain setting", e );
}
}
} );
mComboEnhanceGain.setToolTipText( "<html>Enhance Gain. Set master gain "
+ "to <b>MANUAL</b> to enable adjustment</html>" );
mComboEnhanceGain.setEnabled( false );
gainPanel.add( new JLabel( "Enhance" ) );
gainPanel.add( mComboEnhanceGain, "wrap" );
add( gainPanel, "span,grow,push" );
/**
* Create a new configuration
*/
mNewConfiguration = new JButton( "New" );
mNewConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
TunerConfiguration config =
mResourceManager.getSettingsManager()
.addNewTunerConfiguration(
TunerType.ELONICS_E4000,
"New Configuration" );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedItem( config );
repaint();
}
} );
add( mNewConfiguration, "growx,push" );
/**
* Delete the currently selected configuration
*/
mDeleteConfiguration = new JButton( "Delete" );
mDeleteConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
E4KTunerConfiguration selected =
(E4KTunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
int n = JOptionPane.showConfirmDialog(
E4KTunerConfigurationPanel.this,
"Are you sure you want to delete '"
+ selected.getName() + "'?",
"Are you sure?",
JOptionPane.YES_NO_OPTION );
if( n == JOptionPane.YES_OPTION )
{
mResourceManager.getSettingsManager()
.deleteTunerConfiguration( selected );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedIndex( 0 );
repaint();
}
}
}
} );
add( mDeleteConfiguration, "growx,push,wrap" );
}
/**
* Updates gui controls with the values from the tuner configuration
* @param config - tuner configuration
*/
private void update( E4KTunerConfiguration config )
{
mSelectedConfig = config;
try
{
mController.apply( config );
mName.setText( config.getName() );
mFrequencyCorrection.setValue( config.getFrequencyCorrection() );
mComboMixerGain.setSelectedItem( mSelectedConfig.getMixerGain() );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
mComboEnhanceGain.setSelectedItem( mSelectedConfig.getEnhanceGain() );
/* Apply master gain last so that the Mixer, LNA, and Enhance gain
* settings are updated with the master setting where necessary */
mComboMasterGain.setSelectedItem( mSelectedConfig.getMasterGain() );
mComboSampleRate.setSelectedItem( mSelectedConfig.getSampleRate() );
mResourceManager.getSettingsManager().setSelectedTunerConfiguration(
TunerType.ELONICS_E4000, mController.getUniqueID(), config );
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
E4KTunerConfigurationPanel.this,
"E4K Tuner Controller - couldn't "
+ "apply the tuner configuration settings - " +
e1.getLocalizedMessage() );
mLog.error( "E4K Tuner Controller - couldn't apply "
+ "config [" + config.getName() + "]", e1 );
}
}
/**
* Constructs a combo box model for the tuner configuration combo component
* by assembling a list of the tuner configurations appropriate for this
* specific tuner
*/
private ComboBoxModel<E4KTunerConfiguration> getModel()
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.ELONICS_E4000 );
DefaultComboBoxModel<E4KTunerConfiguration> model =
new DefaultComboBoxModel<E4KTunerConfiguration>();
for( TunerConfiguration config: configs )
{
model.addElement( (E4KTunerConfiguration)config );
}
return model;
}
/**
* Retrieves a specific (named) tuner configuration
*/
private E4KTunerConfiguration getNamedConfiguration( String name )
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.ELONICS_E4000 );
for( TunerConfiguration config: configs )
{
if( config.getName().contentEquals( name ) )
{
return (E4KTunerConfiguration)config;
}
}
return null;
}
/**
* Saves current tuner configuration settings
*/
private void save()
{
mResourceManager.getSettingsManager().save();
}
}
<file_sep>/*
* EmptyTileFactory.java
*
* Created on June 7, 2006, 4:58 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package org.jdesktop.swingx.mapviewer.empty;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import org.jdesktop.swingx.mapviewer.Tile;
import org.jdesktop.swingx.mapviewer.TileFactory;
import org.jdesktop.swingx.mapviewer.TileFactoryInfo;
/**
* A null implementation of TileFactory. Draws empty areas.
* @author joshy
*/
public class EmptyTileFactory extends TileFactory
{
/**
* The empty tile image.
*/
private BufferedImage emptyTile;
/**
* Creates a new instance of EmptyTileFactory
*/
public EmptyTileFactory()
{
this(new TileFactoryInfo("EmptyTileFactory 256x256", 1, 15, 17, 256, true, true, "", "x", "y", "z"));
}
/**
* Creates a new instance of EmptyTileFactory using the specified info.
* @param info the tile factory info
*/
public EmptyTileFactory(TileFactoryInfo info)
{
super(info);
int tileSize = info.getTileSize(info.getMinimumZoomLevel());
emptyTile = new BufferedImage(tileSize, tileSize, BufferedImage.TYPE_INT_ARGB);
Graphics2D g = emptyTile.createGraphics();
g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g.setColor(Color.GRAY);
g.fillRect(0, 0, tileSize, tileSize);
g.setColor(Color.WHITE);
g.drawOval(10, 10, tileSize - 20, tileSize - 20);
g.fillOval(70, 50, 20, 20);
g.fillOval(tileSize - 90, 50, 20, 20);
g.fillOval(tileSize / 2 - 10, tileSize / 2 - 10, 20, 20);
g.dispose();
}
/**
* Gets an instance of an empty tile for the given tile position and zoom on the world map.
* @param x The tile's x position on the world map.
* @param y The tile's y position on the world map.
* @param zoom The current zoom level.
*/
@Override
public Tile getTile(int x, int y, int zoom)
{
return new Tile(x, y, zoom)
{
@Override
public synchronized boolean isLoaded()
{
return true;
}
@Override
public BufferedImage getImage()
{
return emptyTile;
}
};
}
@Override
public void dispose()
{
// noop
}
/**
* Override this method to load the tile using, for example, an <code>ExecutorService</code>.
* @param tile The tile to load.
*/
@Override
protected void startLoading(Tile tile)
{
// noop
}
}
<file_sep>package spectrum.converter;
import java.util.concurrent.CopyOnWriteArrayList;
import spectrum.DFTResultsListener;
import spectrum.DFTResultsProvider;
public abstract class DFTResultsConverter
implements DFTResultsListener, DFTResultsProvider
{
private CopyOnWriteArrayList<DFTResultsListener> mListeners =
new CopyOnWriteArrayList<DFTResultsListener>();
/**
* DFT Results Converter - for converting the output of the JTransforms
* FFT library real and complex forward results
*/
public DFTResultsConverter()
{
}
public void dispose()
{
mListeners.clear();
}
@Override
public void addListener( DFTResultsListener listener )
{
mListeners.add( listener );
}
@Override
public void removeListener( DFTResultsListener listener )
{
mListeners.remove( listener );
}
protected void dispatch( float[] results )
{
for( DFTResultsListener listener: mListeners )
{
listener.receive( results );
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.ltrnet;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import message.Message;
import alias.Alias;
import alias.AliasList;
import controller.activity.ActivitySummaryProvider;
public class LTRNetActivitySummary implements ActivitySummaryProvider
{
private static final int sINT_NULL_VALUE = -1;
private DecimalFormat mDecimalFormatter = new DecimalFormat("0.00000");
private AliasList mAliasList;
private HashSet<String> mTalkgroupsFirstHeard = new HashSet<String>();
private TreeSet<String> mTalkgroups = new TreeSet<String>();
private TreeSet<String> mESNs = new TreeSet<String>();
private TreeSet<Integer> mUniqueIDs = new TreeSet<Integer>();
private TreeSet<String> mNeighborIDs = new TreeSet<String>();
private TreeSet<String> mSiteIDs = new TreeSet<String>();
private HashMap<Integer,Double> mReceiveFrequencies =
new HashMap<Integer,Double>();
private HashMap<Integer,Double> mTransmitFrequencies =
new HashMap<Integer,Double>();
private int mMonitoredLCN;
/**
* Compiles a summary of active talkgroups, unique radio ids encountered
* in the decoded messages. Talkgroups have to be heard a minimum of twice
* to be considered valid ... in order to weed out the invalid ones.
*
* Returns a textual summary of the activity
*/
public LTRNetActivitySummary( AliasList list )
{
mAliasList = list;
}
@Override
public void receive( Message message )
{
if( message instanceof LTRNetOSWMessage )
{
LTRNetOSWMessage ltr = ((LTRNetOSWMessage)message);
if( ltr.isValid() )
{
switch( ltr.getMessageType() )
{
case CA_STRT:
case CA_ENDD:
String talkgroup = ltr.getTalkgroupID();
if( mTalkgroupsFirstHeard.contains( talkgroup ) )
{
mTalkgroups.add( talkgroup );
}
else
{
mTalkgroupsFirstHeard.add( talkgroup );
}
break;
case SY_IDLE:
mMonitoredLCN = ltr.getChannel();
break;
case MA_CHNH:
break;
case MA_CHNL:
break;
case FQ_RXHI:
mReceiveFrequencies.put( ltr.getHomeRepeater(),
ltr.getFrequency() );
break;
case FQ_RXLO:
break;
case FQ_TXHI:
mTransmitFrequencies.put( ltr.getHomeRepeater(),
ltr.getFrequency() );
break;
case FQ_TXLO:
break;
case ID_ESNH:
break;
case ID_ESNL:
break;
case ID_NBOR:
String neighborID = ltr.getNeighborID();
if( neighborID != null )
{
mNeighborIDs.add( neighborID );
}
break;
case ID_UNIQ:
int uniqueid = ltr.getRadioUniqueID();
if( uniqueid != sINT_NULL_VALUE )
{
mUniqueIDs.add( uniqueid );
}
break;
case ID_SITE:
String siteID = ltr.getSiteID();
if( siteID != null )
{
mSiteIDs.add( siteID );
}
break;
case UN_KNWN:
break;
default:
break;
}
}
}
else if( message instanceof LTRNetISWMessage )
{
LTRNetISWMessage ltr = ((LTRNetISWMessage)message);
if( ltr.isValid() )
{
switch( ltr.getMessageType() )
{
case CA_STRT:
case CA_ENDD:
String talkgroup = ltr.getTalkgroupID();
if( mTalkgroupsFirstHeard.contains( talkgroup ) )
{
mTalkgroups.add( talkgroup );
}
else
{
mTalkgroupsFirstHeard.add( talkgroup );
}
break;
case ID_ESNH:
case ID_ESNL:
String esn = ltr.getESN();
if( !esn.contains( "xxxx" ) )
{
mESNs.add( ltr.getESN() );
}
break;
case ID_UNIQ:
int uniqueid = ltr.getRadioUniqueID();
if( uniqueid != sINT_NULL_VALUE )
{
mUniqueIDs.add( uniqueid );
}
break;
default:
break;
}
}
}
}
@Override
public String getSummary()
{
StringBuilder sb = new StringBuilder();
sb.append( "Activity Summary\n" );
sb.append( "Decoder:\tLTR-Net\n\n" );
if( mSiteIDs.isEmpty() )
{
sb.append( "Site:\tUnknown\n" );
}
else
{
Iterator<String> it = mSiteIDs.iterator();
while( it.hasNext() )
{
sb.append( "Site:\t" );
String siteID = it.next();
sb.append( siteID );
Alias siteAlias = mAliasList.getSiteID( String.valueOf( siteID ) );
if( siteAlias != null )
{
sb.append( " " );
sb.append( siteAlias.getName() );
}
sb.append( "\n" );
}
}
sb.append( "\nLCNs (transmit | receive)\n" );
if( mReceiveFrequencies.isEmpty() && mTransmitFrequencies.isEmpty() )
{
sb.append( " None\n" );
}
else
{
for( int x = 1; x < 21; x++ )
{
double rcv = 0.0d;
if( mReceiveFrequencies.containsKey( x ) )
{
rcv = mReceiveFrequencies.get( x );
}
double xmt = 0.0d;
if( mTransmitFrequencies.containsKey( x ) )
{
xmt = mTransmitFrequencies.get( x );
}
if( rcv > 0.0d || xmt > 0.0d )
{
if( x < 10 )
{
sb.append( " " );
}
sb.append( x );
sb.append( ": " );
if( xmt == -1.0d )
{
sb.append( "---.-----" );
}
else
{
sb.append( mDecimalFormatter.format( xmt ) );
}
sb.append( " | " );
if( rcv == -1.0d )
{
sb.append( "---.-----" );
}
else
{
sb.append( mDecimalFormatter.format( rcv ) );
}
if( x == mMonitoredLCN )
{
sb.append( " **" );
}
sb.append( "\n" );
}
}
}
sb.append( "\nTalkgroups\n" );
if( mTalkgroups.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<String> it = mTalkgroups.iterator();
while( it.hasNext() )
{
String tgid = it.next();
sb.append( " " );
sb.append( tgid );
sb.append( " " );
Alias alias = mAliasList.getTalkgroupAlias( tgid );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
sb.append( "\nRadio Unique IDs\n" );
if( mUniqueIDs.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<Integer> it = mUniqueIDs.iterator();
while( it.hasNext() )
{
int uid = it.next();
sb.append( " " );
sb.append( uid );
sb.append( " " );
Alias alias = mAliasList.getUniqueID( uid );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
sb.append( "\nESNs\n" );
if( mESNs.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<String> it = mESNs.iterator();
while( it.hasNext() )
{
String esn = it.next();
sb.append( " " );
sb.append( esn );
sb.append( " " );
Alias alias = mAliasList.getESNAlias( esn );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
sb.append( "\nNeighbor Sites\n" );
if( mNeighborIDs.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<String> it = mNeighborIDs.iterator();
while( it.hasNext() )
{
String neighbor = it.next();
sb.append( " " );
sb.append( neighbor );
sb.append( " " );
Alias alias = mAliasList.getSiteID( String.valueOf( neighbor ) );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
return sb.toString();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 settings;
import java.awt.Color;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
public class ColorSetting extends Setting
{
private static final int NO_TRANSLUCENCY = 255;
private static final int SPECTRUM_TRANSLUCENCY = 128;
private static final int CONFIG_TRANSLUCENCY = 60;
private String mRGB;
private int mAlpha;
private ColorSettingName mColorSettingName = ColorSettingName.UNKNOWN;
public ColorSetting()
{
setColor( mColorSettingName.getDefaultColor() );
}
public ColorSetting( ColorSettingName name )
{
setColor( name.getDefaultColor() );
setColorSettingName( name );
}
@XmlAttribute
public ColorSettingName getColorSettingName()
{
return mColorSettingName;
}
public void setColorSettingName( ColorSettingName name )
{
mColorSettingName = name;
}
@XmlAttribute
public String getRgb()
{
return mRGB;
}
public void setRgb( String value )
{
mRGB = value;
}
@XmlAttribute
public int getAlpha()
{
return mAlpha;
}
public void setAlpha( int value )
{
mAlpha = value;
}
@XmlTransient
public Color getColor()
{
Color temp = Color.decode( mRGB );
return new Color( temp.getRed(),
temp.getGreen(),
temp.getBlue(),
mAlpha );
}
public void setColor( Color color )
{
mRGB = Integer.toHexString( color.getRGB() );
mRGB = "#" + mRGB.substring( 2, mRGB.length() );
mAlpha = color.getAlpha();
}
public static Color getTranslucent( Color color, int translucency )
{
return new Color( color.getRed(),
color.getGreen(),
color.getBlue(),
translucency );
}
public enum ColorSettingName
{
CHANNEL_CONFIG( getTranslucent( Color.LIGHT_GRAY, CONFIG_TRANSLUCENCY ),
"Channel", "Channel Color" ),
CHANNEL_CONFIG_PROCESSING( getTranslucent( Color.GREEN, CONFIG_TRANSLUCENCY ),
"Channel Processing", "Processing Channel Color" ),
CHANNEL_CONFIG_SELECTED( getTranslucent( Color.BLUE, CONFIG_TRANSLUCENCY ),
"Channel Selected", "Selected Channel Color" ),
CHANNEL_STATE_BACKGROUND( Color.BLACK, "Background",
"Channel State Background" ),
CHANNEL_STATE_GRADIENT_TOP_CALL( Color.BLACK,
"Call Gradient Top", "Channel Call State Gradient Top" ),
CHANNEL_STATE_GRADIENT_MIDDLE_CALL( Color.BLUE,
"Call Gradient Middle", "Channel Call State Gradient Middle" ),
CHANNEL_STATE_GRADIENT_TOP_CONTROL( Color.BLACK,
"Control Gradient Top", "Channel Control State Gradient Top" ),
CHANNEL_STATE_GRADIENT_MIDDLE_CONTROL( new Color( 0xC64F00 ),
"Control Gradient Middle", "Channel Control State Gradient Middle" ),
CHANNEL_STATE_GRADIENT_TOP_DATA( Color.BLACK,
"Data Gradient Top", "Channel Data State Gradient Top" ),
CHANNEL_STATE_GRADIENT_MIDDLE_DATA( Color.BLUE,
"Data Gradient Middle", "Channel Data State Gradient Middle" ),
CHANNEL_STATE_GRADIENT_TOP_FADE( Color.BLACK,
"Fade Gradient Top", "Channel Fade State Gradient Top" ),
CHANNEL_STATE_GRADIENT_MIDDLE_FADE( Color.DARK_GRAY,
"Fade Gradient Middle", "Channel Fade State Gradient Middle" ),
CHANNEL_STATE_GRADIENT_TOP_IDLE( Color.BLACK,
"Idle Gradient Top", "Channel Idle State Gradient Top" ),
CHANNEL_STATE_GRADIENT_MIDDLE_IDLE( Color.DARK_GRAY,
"Idle Gradient Middle", "Channel Idle State Gradient Middle" ),
CHANNEL_STATE_GRADIENT_TOP_NO_TUNER( Color.RED,
"No Tuner Gradient Top", "Channel No Tuner State Gradient Top" ),
CHANNEL_STATE_GRADIENT_MIDDLE_NO_TUNER( new Color( 0x990000 ),
"No Tuner Gradient Middle", "Channel No Tuner State Gradient Middle" ),
CHANNEL_STATE_LABEL_DETAILS( Color.LIGHT_GRAY,
"Details", "Details Label Color" ),
CHANNEL_STATE_LABEL_DECODER( Color.GREEN,
"Decoder", "Decoder Label Color" ),
CHANNEL_STATE_LABEL_AUX_DECODER( Color.YELLOW,
"Aux Decoder", "Aux Decoder Label Color" ),
CHANNEL_STATE_SELECTED_CHANNEL( Color.YELLOW,
"Selected Channel Indicator", "Selected Channel Indicator Color" ),
SPECTRUM_BACKGROUND( Color.BLACK,
"Background", "Spectrum Background Color" ),
SPECTRUM_CURSOR( Color.ORANGE,
"Cursor", "Spectrum Cursor Color" ),
SPECTRUM_GRADIENT_BOTTOM( getTranslucent( Color.GREEN, SPECTRUM_TRANSLUCENCY ),
"Gradient Bottom", "Spectrum Gradient Bottom Color" ),
SPECTRUM_GRADIENT_TOP( getTranslucent( Color.WHITE, SPECTRUM_TRANSLUCENCY ),
"Gradient Top", "Spectrum Gradient Top Color" ),
SPECTRUM_LINE( getTranslucent( Color.LIGHT_GRAY, SPECTRUM_TRANSLUCENCY ),
"Line", "Spectrum Lines and Text Color" ),
UNKNOWN( Color.RED, "Unknown", "Unknown Setting Color" );
private Color mDefaultColor;
private String mLabel;
private String mDialogTitle;
private ColorSettingName( Color defaultColor,
String label,
String dialogTitle )
{
mDefaultColor = defaultColor;
mLabel = label;
mDialogTitle = dialogTitle;
}
public Color getDefaultColor()
{
return mDefaultColor;
}
public String getLabel()
{
return mLabel;
}
public String getDialogTitle()
{
return mDialogTitle;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 gui;
import java.awt.AWTException;
import java.awt.Desktop;
import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Robot;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.image.BufferedImage;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Iterator;
import java.util.ServiceLoader;
import javax.imageio.ImageIO;
import javax.sound.sampled.spi.FormatConversionProvider;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JSeparator;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import properties.SystemProperties;
import source.tuner.Tuner;
import source.tuner.TunerSelectionListener;
import spectrum.SpectralDisplayPanel;
import util.TimeStamp;
import com.jidesoft.swing.JideSplitPane;
import controller.ControllerPanel;
import controller.ResourceManager;
public class SDRTrunk
{
private final static Logger mLog = LoggerFactory.getLogger( SDRTrunk.class );
private ResourceManager mResourceManager;
private ControllerPanel mControllerPanel;
private SpectralDisplayPanel mSpectralPanel;
private JFrame mMainGui = new JFrame();
private String mTitle;
public SDRTrunk()
{
// LoggerContext lc = (LoggerContext)LoggerFactory.getILoggerFactory();
// StatusPrinter.print( lc );
mLog.info( "" );
mLog.info( "" );
mLog.info( "*******************************************************************" );
mLog.info( "**** SDRTrunk: a trunked radio and digital decoding application ***" );
mLog.info( "**** website: https://code.google.com/p/sdrtrunk ***" );
mLog.info( "*******************************************************************" );
mLog.info( "" );
mLog.info( "" );
//Setup the application home directory
Path home = getHomePath();
mLog.info( "Home path: " + home.toString() );
//Load properties file
if( home != null )
{
loadProperties( home );
}
//Log current properties setting
SystemProperties.getInstance().logCurrentSettings();
/**
* Construct the resource manager now, so that it can use the system
* properties that were just loaded
*/
mResourceManager = new ResourceManager();
mTitle = getTitle();
//Initialize the GUI
initGUI();
mLog.info( "starting main application gui" );
//Start the gui
EventQueue.invokeLater( new Runnable()
{
public void run()
{
try
{
mMainGui.setVisible( true );
}
catch( Exception e )
{
e.printStackTrace();
}
}
} );
}
/**
* Launch the application.
*/
public static void main( String[] args )
{
new SDRTrunk();
}
/**
* Initialize the contents of the frame.
*/
private void initGUI()
{
mMainGui.setLayout( new MigLayout( "insets 0 0 0 0 ",
"[grow,fill]",
"[grow,fill]") );
mControllerPanel = new ControllerPanel( mResourceManager );
mSpectralPanel = new SpectralDisplayPanel( mResourceManager );
//Register spectral panel to receive tuner selection events
mControllerPanel.getController()
.addListener( (TunerSelectionListener)mSpectralPanel );
//Add spectrum panel to receive channel change events
mResourceManager.getChannelManager().addListener( mSpectralPanel );
//init() the controller to load tuners and playlists
mControllerPanel.getController().init();
/**
* Setup main JFrame window
*/
mMainGui.setTitle( mTitle );
mMainGui.setBounds( 100, 100, 1280, 800 );
mMainGui.setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE );
mControllerPanel.getController().addListener( new TunerSelectionListener()
{
@Override
public void tunerSelected( Tuner tuner )
{
if( tuner != null )
{
mMainGui.setTitle( mTitle + " - " + tuner.getName() );
}
else
{
mMainGui.setTitle( mTitle );
}
}
} );
//Fire first tuner selection so it is displayed in the spectrum/waterfall
mControllerPanel.getController().fireFirstTunerSelected();
mSpectralPanel.setPreferredSize( new Dimension( 1280, 400 ) );
JideSplitPane splitPane = new JideSplitPane( JideSplitPane.VERTICAL_SPLIT );
splitPane.setDividerSize( 5 );
splitPane.add( mSpectralPanel );
splitPane.add( mControllerPanel );
mMainGui.add( splitPane, "cell 0 0,span,grow");
/**
* Menu items
*/
JMenuBar menuBar = new JMenuBar();
mMainGui.setJMenuBar( menuBar );
JMenu fileMenu = new JMenu( "File" );
menuBar.add( fileMenu );
JMenuItem logFilesMenu = new JMenuItem( "Logs & Recordings" );
logFilesMenu.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
Desktop.getDesktop().open( getHomePath().toFile() );
}
catch( Exception e )
{
mLog.error( "Couldn't open file explorer" );
JOptionPane.showMessageDialog( mMainGui,
"Can't launch file explorer - files are located at: " +
getHomePath().toString(),
"Can't launch file explorer",
JOptionPane.ERROR_MESSAGE );
}
}
} );
fileMenu.add( logFilesMenu );
JMenuItem settingsMenu = new JMenuItem( "Icon Manager" );
settingsMenu.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
mControllerPanel.getController().showIconManager();
}
} );
fileMenu.add( settingsMenu );
fileMenu.add( new JSeparator() );
JMenuItem exitMenu = new JMenuItem( "Exit" );
exitMenu.addActionListener(
new ActionListener()
{
public void actionPerformed( ActionEvent event )
{
System.exit( 0 );
}
}
);
fileMenu.add( exitMenu );
JMenuItem screenCaptureItem = new JMenuItem( "Screen Capture" );
screenCaptureItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
Robot robot = new Robot();
final BufferedImage image =
robot.createScreenCapture( mMainGui.getBounds() );
SystemProperties props = SystemProperties.getInstance();
Path capturePath = props.getApplicationFolder( "screen_captures" );
if( !Files.exists( capturePath ) )
{
try
{
Files.createDirectory( capturePath );
}
catch ( IOException e )
{
mLog.error( "Couldn't create 'screen_captures' "
+ "subdirectory in the " +
"SDRTrunk application directory", e );
}
}
String filename = TimeStamp.getTimeStamp( "_" ) +
"_screen_capture.png";
final Path captureFile = capturePath.resolve( filename );
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
ImageIO.write( image, "png",
captureFile.toFile() );
}
catch ( IOException e )
{
mLog.error( "Couldn't write screen capture to "
+ "file [" + captureFile.toString() + "]", e );
}
}} );
}
catch ( AWTException e )
{
mLog.error( "Exception while taking screen capture", e );
}
}
} );
menuBar.add( screenCaptureItem );
}
/**
* Loads the application properties file from the user's home directory,
* creating the properties file for the first-time, if necessary
*/
private void loadProperties( Path homePath )
{
Path propsPath = homePath.resolve( "SDRTrunk.properties" );
if( !Files.exists( propsPath ) )
{
try
{
mLog.info( "SDRTrunk - creating application properties file [" +
propsPath.toAbsolutePath() + "]" );
Files.createFile( propsPath );
}
catch ( IOException e )
{
mLog.error( "SDRTrunk - couldn't create application properties "
+ "file [" + propsPath.toAbsolutePath(), e );
}
}
if( Files.exists( propsPath ) )
{
SystemProperties.getInstance().load( propsPath );
}
else
{
mLog.error( "SDRTrunk - couldn't find or recreate the SDRTrunk " +
"application properties file" );
}
}
/**
* Gets (or creates) the SDRTRunk application home directory.
*
* Note: the user can change this setting to allow log files and other
* files to reside elsewhere on the file system.
*/
private Path getHomePath()
{
Path homePath = FileSystems.getDefault()
.getPath( System.getProperty( "user.home" ), "SDRTrunk" );
if( !Files.exists( homePath ) )
{
try
{
Files.createDirectory( homePath );
mLog.info( "SDRTrunk - created application home directory [" +
homePath.toString() + "]" );
}
catch ( Exception e )
{
homePath = null;
mLog.error( "SDRTrunk: exception while creating SDRTrunk home " +
"directory in the user's home directory", e );
}
}
return homePath;
}
private String getTitle()
{
StringBuilder sb = new StringBuilder();
sb.append( "SDRTrunk" );
try( BufferedReader reader = new BufferedReader(
new InputStreamReader( this.getClass()
.getResourceAsStream( "/sdrtrunk-version" ) ) ) )
{
String version = reader.readLine();
if( version != null )
{
sb.append( " V" );
sb.append( version );
}
}
catch( Exception e )
{
mLog.error( "Couldn't read sdrtrunk version from application jar file" );
}
return sb.toString();
}
}
<file_sep>package filter;
public class FilterElement<T> implements Comparable<FilterElement<T>>
{
private boolean mEnabled;
private T mElement;
public FilterElement( T element, boolean enabled )
{
mElement = element;
mEnabled = enabled;
}
public FilterElement( T t )
{
this( t, true );
}
public T getElement()
{
return mElement;
}
public String toString()
{
return getName();
}
public boolean isEnabled()
{
return mEnabled;
}
public void setEnabled( boolean enabled )
{
mEnabled = enabled;
}
public String getName()
{
return mElement.toString();
}
@Override
public int compareTo( FilterElement<T> other )
{
return toString().compareTo( other.toString() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 buffer;
import sample.Listener;
/**
* Delay Buffer - implements a circular delay buffer backed by an object array
*/
public class DelayBuffer<T> implements Listener<T>
{
private Object[] mBuffer;
private int mBufferPointer = 0;
private Listener<T> mListener;
public DelayBuffer( int length )
{
mBuffer = new Object[ length ];
}
@Override
@SuppressWarnings( "unchecked" )
public void receive( T value )
{
Object delayed = mBuffer[ mBufferPointer ];
mBuffer[ mBufferPointer ] = value;
mBufferPointer++;
/* Wrap the buffer pointer around to 0 when necessary */
if( mBufferPointer >= mBuffer.length )
{
mBufferPointer = 0;
}
if( mListener != null && delayed != null )
{
mListener.receive( (T)delayed );
}
}
public void setListener( Listener<T> listener )
{
mListener = listener;
}
public void removeListener( Listener<T> listener )
{
mListener = null;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 alias.talkgroup;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import net.miginfocom.swing.MigLayout;
import audio.inverted.AudioType;
import controller.ConfigurableNode;
public class TalkgroupIDEditor extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private TalkgroupIDNode mTalkgroupIDNode;
private JLabel mLabelName;
private JTextField mTextTalkgroupID;
private JLabel mLabelAudio;
private JComboBox<AudioType> mComboAudioTypes;
private String mHelpText = "Enter a formatted talkgroup identifier.\n\n"
+ "LTR Talkgroup Format: A-HH-TTT (A=Area, H=Home Repeater, "
+ "T=Talkgroup)\n\n"
+ "Passport Talkgroup Format: xxxxx (up to 5-digit number)\n\n"
+ "Wildcard: use one or more asterisks (*) for any talkgroup digits.\n\n"
+ "Audio: if the talkgroup uses simple frequency inversion, specify"
+ " the inversion frequency from the dropdown list to automatically"
+ " un-invert audio for this specific talkgroup";
public TalkgroupIDEditor( TalkgroupIDNode talkgroupIDNode )
{
mTalkgroupIDNode = talkgroupIDNode;
initGUI();
}
private void initGUI()
{
setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][][grow]" ) );
add( new JLabel( "Talkgroup ID" ), "span,align center" );
add( new JLabel( "TGID:" ) );
mTextTalkgroupID = new JTextField();
mTextTalkgroupID.setText( mTalkgroupIDNode.getTalkgroupID().getTalkgroup() );
add( mTextTalkgroupID, "growx,push" );
add( new JLabel( "Audio:" ) );
mComboAudioTypes = new JComboBox<AudioType>();
mComboAudioTypes.setModel(
new DefaultComboBoxModel<AudioType>( AudioType.values() ) );
AudioType audioType = mTalkgroupIDNode.getTalkgroupID().getAudioType();
if( audioType != null )
{
mComboAudioTypes.setSelectedItem( audioType );
}
add( mComboAudioTypes, "growx,push" );
JButton btnSave = new JButton( "Save" );
btnSave.addActionListener( TalkgroupIDEditor.this );
add( btnSave, "growx,push" );
JButton btnReset = new JButton( "Reset" );
btnReset.addActionListener( TalkgroupIDEditor.this );
add( btnReset, "growx,push" );
JTextArea helpText = new JTextArea( mHelpText );
helpText.setLineWrap( true );
add( helpText, "span,grow,push" );
}
@Override
public void actionPerformed( ActionEvent e )
{
String command = e.getActionCommand();
if( command.contentEquals( "Save" ) )
{
String tgid = mTextTalkgroupID.getText();
if( tgid != null )
{
mTalkgroupIDNode.getTalkgroupID().setTalkgroup( tgid );
((ConfigurableNode)mTalkgroupIDNode.getParent()).sort();
AudioType selected = mComboAudioTypes
.getItemAt( mComboAudioTypes.getSelectedIndex() );
if( selected != null )
{
mTalkgroupIDNode.getTalkgroupID().setAudioType( selected );
}
mTalkgroupIDNode.save();
mTalkgroupIDNode.show();
}
else
{
JOptionPane.showMessageDialog( TalkgroupIDEditor.this,
"Please enter a talkgroup ID" );
}
}
else if( command.contentEquals( "Reset" ) )
{
mTextTalkgroupID.setText(
mTalkgroupIDNode.getTalkgroupID().getTalkgroup() );
mComboAudioTypes.setSelectedItem(
mTalkgroupIDNode.getTalkgroupID().getAudioType() );
}
mTalkgroupIDNode.refresh();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.ltrnet;
import java.awt.EventQueue;
import java.util.HashMap;
import message.Message;
import alias.Alias;
import alias.AliasList;
import controller.activity.CallEvent;
import controller.activity.CallEvent.CallEventType;
import controller.activity.CallEventModel;
import controller.channel.ProcessingChain;
import controller.state.AuxChannelState;
import controller.state.ChannelState;
import controller.state.ChannelState.State;
public class LTRNetChannelState extends ChannelState
{
private String mTalkgroup;
private Alias mTalkgroupAlias;
private String mDescription;
private int mChannelNumber;
private HashMap<Integer,String> mActiveCalls = new HashMap<Integer,String>();
private LTRNetActivitySummary mActivitySummary;
public LTRNetChannelState( ProcessingChain channel, AliasList aliasList )
{
super( channel, aliasList );
mActivitySummary = new LTRNetActivitySummary( aliasList );
}
/**
* Intercept the fade event so that we can generate a call end event
*/
@Override
public void fade( final CallEventType type )
{
/*
* We can receive multiple call tear-down messages -- only respond to
* the message that can change the state to fade
*/
if( getState().canChangeTo( State.FADE ) )
{
LTRCallEvent current = getCurrentLTRCallEvent();
if( current != null )
{
/* Close out the call event. If we only received 1 call
* message, then flag it as noise and remove the call event */
if( current.isValid() )
{
mCallEventModel.setEnd( current );
}
else
{
mCallEventModel.remove( current );
}
}
}
setCurrentCallEvent( null );
mActiveCalls.clear();
super.fade( type );
}
public LTRCallEvent getCurrentLTRCallEvent()
{
CallEvent current = getCurrentCallEvent();
if( current != null )
{
return (LTRCallEvent)current;
}
return null;
}
@Override
public String getActivitySummary()
{
StringBuilder sb = new StringBuilder();
sb.append( mActivitySummary.getSummary() );
for( AuxChannelState state: mAuxChannelStates )
{
sb.append( state.getActivitySummary() );
sb.append( "\n\n" );
}
return sb.toString();
}
@Override
public void receive( Message message )
{
super.receive( message );
if( message instanceof LTRNetOSWMessage )
{
mActivitySummary.receive( message );
LTRNetOSWMessage ltr = (LTRNetOSWMessage)message;
Alias talkgroupAlias = ltr.getTalkgroupIDAlias();
switch( ltr.getMessageType() )
{
case CA_STRT:
if( mChannelNumber == 0 )
{
mChannelNumber = ltr.getChannel();
}
if( ltr.getChannel() == mChannelNumber )
{
processCallMessage( ltr );
if( ltr.getGroup() == 253 )
{
mDescription = "REGISTER";
broadcastChange( ChangedAttribute.DESCRIPTION );
}
else
{
mTalkgroup = ltr.getTalkgroupID();
broadcastChange( ChangedAttribute.TO_TALKGROUP );
if( talkgroupAlias != null )
{
mTalkgroupAlias = talkgroupAlias;
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
}
}
}
else
{
//Call Detect
if( !mActiveCalls.containsKey( ltr.getChannel() ) ||
!mActiveCalls.get( ltr.getChannel() )
.contentEquals( ltr.getTalkgroupID() ) )
{
mActiveCalls.put( ltr.getChannel(),
ltr.getTalkgroupID() );
mCallEventModel.add(
new LTRCallEvent.Builder( CallEventType.CALL_DETECT )
.aliasList( mAliasList )
.channel( String.valueOf( ltr.getChannel() ) )
.to( ltr.getTalkgroupID() )
.build() );
}
}
break;
case CA_ENDD:
if( ltr.getGroup() != 253 )
{
mTalkgroup = ltr.getTalkgroupID();
broadcastChange( ChangedAttribute.TO_TALKGROUP );
if( talkgroupAlias != null )
{
mTalkgroupAlias = talkgroupAlias;
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
}
}
fade( CallEventType.CALL_END );
break;
case ID_UNIQ:
mDescription = "REGISTER UID";
broadcastChange( ChangedAttribute.DESCRIPTION );
mTalkgroup = String.valueOf( ltr.getRadioUniqueID() );
broadcastChange( ChangedAttribute.TO_TALKGROUP );
mTalkgroupAlias = ltr.getRadioUniqueIDAlias();
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
final LTRCallEvent currentEvent = getCurrentLTRCallEvent();
if( currentEvent != null &&
currentEvent.getCallEventType() == CallEventType.REGISTER )
{
final String uid = String.valueOf( ltr.getRadioUniqueID() );
if( uid != null )
{
mCallEventModel.setFromID( currentEvent, uid );
}
}
else
{
mCallEventModel.add(
new LTRCallEvent.Builder( CallEventType.REGISTER )
.aliasList( mAliasList )
.details( "Radio Unique ID" )
.frequency( mProcessingChain.getChannel()
.getTunerChannel().getFrequency() )
.from( String.valueOf( ltr.getRadioUniqueID() ) )
.build() );
}
setState( State.CALL );
break;
case SY_IDLE:
mChannelNumber = ltr.getChannel();
broadcastChange( ChangedAttribute.CHANNEL_NUMBER );
break;
default:
break;
}
}
else if( message instanceof LTRNetISWMessage )
{
mActivitySummary.receive( message );
LTRNetISWMessage ltr = (LTRNetISWMessage)message;
Alias talkgroupAlias = ltr.getTalkgroupIDAlias();
switch( ltr.getMessageType() )
{
case CA_STRT:
processCallMessage( ltr );
if( ltr.getGroup() == 253 )
{
mDescription = "REGISTER";
broadcastChange( ChangedAttribute.DESCRIPTION );
}
else
{
mTalkgroup = ltr.getTalkgroupID();
broadcastChange( ChangedAttribute.TO_TALKGROUP );
if( talkgroupAlias != null )
{
mTalkgroupAlias = talkgroupAlias;
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
}
}
break;
case CA_ENDD:
mTalkgroup = ltr.getTalkgroupID();
broadcastChange( ChangedAttribute.TO_TALKGROUP );
if( talkgroupAlias != null )
{
mTalkgroupAlias = talkgroupAlias;
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
}
fade( CallEventType.CALL_END );
break;
case ID_UNIQ:
mDescription = "REGISTER UID";
broadcastChange( ChangedAttribute.DESCRIPTION );
mTalkgroup = String.valueOf( ltr.getRadioUniqueID() );
broadcastChange( ChangedAttribute.TO_TALKGROUP );
mTalkgroupAlias = ltr.getRadioUniqueIDAlias();
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
if( getState() != State.DATA )
{
LTRCallEvent event =
new LTRCallEvent.Builder( CallEventType.REGISTER )
.aliasList( mAliasList )
.channel( String.valueOf( ltr.getChannel() ) )
.frequency( mProcessingChain.getChannel()
.getTunerChannel().getFrequency() )
.to( ltr.getTalkgroupID() )
.build();
mCallEventModel.add( event );
setCurrentCallEvent( event );
setState( State.DATA );
}
if( mCurrentCallEvent != null )
{
mCurrentCallEvent.setFromID(
String.valueOf( ltr.getRadioUniqueID() ) );
mCurrentCallEvent.setDetails( "Unique ID" );
}
break;
case ID_ESNH:
case ID_ESNL:
mDescription = "ESN";
broadcastChange( ChangedAttribute.DESCRIPTION );
mTalkgroup = ltr.getESN();
broadcastChange( ChangedAttribute.TO_TALKGROUP );
mTalkgroupAlias = ltr.getESNAlias();
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
setState( State.DATA );
mCallEventModel.add(
new LTRCallEvent.Builder( CallEventType.REGISTER_ESN )
.aliasList( mAliasList )
.details( "ESN:" + ltr.getESN() )
.frequency( mProcessingChain.getChannel()
.getTunerChannel().getFrequency() )
.from( ltr.getESN() )
.build() );
break;
default:
break;
}
}
}
private void processCallMessage( LTRNetMessage message )
{
LTRCallEvent current = getCurrentLTRCallEvent();
if( current == null || !current.addMessage( message ) )
{
if( current != null )
{
mCallEventModel.remove( current );
}
LTRCallEvent event;
if( message.getGroup() == 253 )
{
event = new LTRCallEvent.Builder( CallEventType.REGISTER )
.aliasList( mAliasList )
.channel( String.valueOf( message.getChannel() ) )
.frequency( mProcessingChain.getChannel()
.getTunerChannel().getFrequency() )
.to( message.getTalkgroupID() )
.build();
setState( State.DATA );
}
else
{
event = new LTRCallEvent.Builder( CallEventType.CALL )
.aliasList( mAliasList )
.channel( String.valueOf( message.getChannel() ) )
.frequency( mProcessingChain.getChannel()
.getTunerChannel().getFrequency() )
.to( message.getTalkgroupID() )
.build();
setState( State.CALL );
}
mCallEventModel.add( event );
setCurrentCallEvent( event );
}
else
{
if( getState() == State.CALL )
{
setState( State.CALL );
}
else if( getState() == State.DATA )
{
setState( State.DATA );
}
}
}
public void reset()
{
mTalkgroup = null;
broadcastChange( ChangedAttribute.TO_TALKGROUP );
mTalkgroupAlias = null;
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
mDescription = null;
broadcastChange( ChangedAttribute.DESCRIPTION );
super.reset();
}
public String getToTalkgroup()
{
return mTalkgroup;
}
public Alias getToTalkgroupAlias()
{
return mTalkgroupAlias;
}
public String getDescription()
{
return mDescription;
}
public boolean hasChannelNumber()
{
return mChannelNumber != 0;
}
public int getChannelNumber()
{
return mChannelNumber;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.rtl.e4k;
import gui.control.JFrequencyControl;
import java.awt.Color;
import java.awt.EventQueue;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.SourceException;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.FrequencyChangeListener;
import source.tuner.frequency.FrequencyChangeEvent.Attribute;
import source.tuner.rtl.RTL2832InfoPanel;
import com.jidesoft.swing.JideTabbedPane;
import controller.ResourceManager;
public class E4KTunerEditorPanel extends JPanel implements FrequencyChangeListener
{
private final static Logger mLog =
LoggerFactory.getLogger( E4KTunerEditorPanel.class );
private static final long serialVersionUID = 1L;
private E4KTunerController mController;
private ResourceManager mResourceManager;
private JFrequencyControl mFrequencyControl;
public E4KTunerEditorPanel( E4KTunerController controller,
ResourceManager resourceManager )
{
mController = controller;
mResourceManager = resourceManager;
initGUI();
}
private void initGUI()
{
setLayout( new MigLayout( "fill,wrap 2", "[right][grow]", "[][][grow]" ) );
add( new JLabel( "RTL2832 with E4000 Tuner" ), "span 2, align center, wrap" );
mFrequencyControl = new JFrequencyControl();
mFrequencyControl.addListener( this );
/* Add frequency control as listener on the controller, to maintain
* sync with the tuned frequency value */
mController.addListener( mFrequencyControl );
mFrequencyControl.setFrequency( mController.getFrequency(), false );
add( mFrequencyControl, "span 2, align center, wrap" );
JideTabbedPane tabs = new JideTabbedPane();
tabs.setFont( this.getFont() );
tabs.setForeground( Color.BLACK );
tabs.addTab( "Configuration",
new E4KTunerConfigurationPanel( mResourceManager, mController ) );
tabs.addTab( "Info", new RTL2832InfoPanel( mController ) );
add( tabs, "grow,push,span" );
}
/**
* Frequency change listener for the frequency control gui component to
* apply end-user requested frequency changes against the tuner
*/
@Override
public void frequencyChanged( FrequencyChangeEvent event )
{
if( event.getAttribute() == Attribute.FREQUENCY )
{
final long frequency = event.getValue().longValue();
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
mController.setFrequency( frequency );
}
catch ( SourceException e )
{
mLog.error( "E4KTunerController - error setting frequency [" +
frequency + "]", e );
}
}
} );
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.mdc1200;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import map.Plottable;
import message.Message;
import alias.Alias;
import alias.AliasList;
import bits.BinaryMessage;
public class MDCMessage extends Message
{
private static SimpleDateFormat mSDF = new SimpleDateFormat( "yyyyMMdd HHmmss" );
private static int[] sSYNC1 = { 0,1,2,3,4,5,6,7,8,9,
10,11,12,13,14,15,16,17,18,19,
20,21,22,23,24,25,26,27,28,29,
30,31,32,33,34,35,36,37,38,39 };
private static int[] sOPCODE = { 47,46,45,44,43,42,41,40 };
private static int sANI_FLAG = 40;
private static int sDIRECTION_FLAG = 45;
private static int sACKNOWLEDGE_REQUIRED_FLAG = 46;
private static int sPACKET_TYPE_FLAG = 47;
private static int sEMERGENCY_FLAG = 48;
private static int[] sARGUMENT = { 49,50,51,52,53,54 };
private static int sBOT_EOT_FLAG = 55;
private static int[] sDIGIT_2 = { 59,58,57,56 };
private static int[] sDIGIT_1 = { 63,62,61,60 };
private static int[] sDIGIT_4 = { 67,66,65,64 };
private static int[] sDIGIT_3 = { 71,70,69,68 };
private BinaryMessage mMessage;
private AliasList mAliasList;
public MDCMessage( BinaryMessage message, AliasList list )
{
mMessage = message;
mAliasList = list;
}
public boolean isValid()
{
//TODO: add CRC and/or convolution decoding/repair
return true;
}
public PacketType getPacketType()
{
if( mMessage.get( sPACKET_TYPE_FLAG ) )
{
return PacketType.DATA;
}
else
{
return PacketType.CMND;
}
}
public Acknowledge getResponse()
{
if( mMessage.get( sACKNOWLEDGE_REQUIRED_FLAG ) )
{
return Acknowledge.YES;
}
else
{
return Acknowledge.NO;
}
}
public Direction getDirection()
{
if( mMessage.get( sDIRECTION_FLAG ) )
{
return Direction.OUT;
}
else
{
return Direction.IN;
}
}
public int getOpcode()
{
return mMessage.getInt( sOPCODE );
}
public int getArgument()
{
return mMessage.getInt( sARGUMENT );
}
public boolean isEmergency()
{
return mMessage.get( sEMERGENCY_FLAG );
}
public boolean isANI()
{
return mMessage.get( sANI_FLAG );
}
public boolean isBOT()
{
return mMessage.get( sBOT_EOT_FLAG );
}
public boolean isEOT()
{
return !mMessage.get( sBOT_EOT_FLAG );
}
public String getUnitID()
{
StringBuilder sb = new StringBuilder();
sb.append( Integer.toHexString( mMessage.getInt( sDIGIT_1 ) ).toUpperCase() );
sb.append( Integer.toHexString( mMessage.getInt( sDIGIT_2 ) ).toUpperCase() );
sb.append( Integer.toHexString( mMessage.getInt( sDIGIT_3 ) ).toUpperCase() );
sb.append( Integer.toHexString( mMessage.getInt( sDIGIT_4 ) ).toUpperCase() );
return sb.toString();
}
public MDCMessageType getMessageType()
{
switch( getOpcode() )
{
case 0:
if( isEmergency() )
{
return MDCMessageType.EMERGENCY;
}
case 1:
return MDCMessageType.ANI;
default:
return MDCMessageType.UNKNOWN;
}
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( mSDF.format( new Date( System.currentTimeMillis() ) ) );
sb.append( getMessage() );
sb.append( " [" + mMessage.toString() + "]" );
return sb.toString();
}
/**
* Pads spaces onto the end of the value to make it 'places' long
*/
public String pad( String value, int places, String padCharacter )
{
StringBuilder sb = new StringBuilder();
sb.append( value );
while( sb.length() < places )
{
sb.append( padCharacter );
}
return sb.toString();
}
/**
* Pads an integer value with additional zeroes to make it decimalPlaces long
*/
public String format( int number, int decimalPlaces )
{
StringBuilder sb = new StringBuilder();
int paddingRequired = decimalPlaces - ( String.valueOf( number ).length() );
for( int x = 0; x < paddingRequired; x++)
{
sb.append( "0" );
}
sb.append( number );
return sb.toString();
}
@SuppressWarnings( "unused" )
private int getInt( int[] bits )
{
int retVal = 0;
for( int x = 0; x < bits.length; x++ )
{
if( mMessage.get( bits[ x ] ) )
{
retVal += 1<<x;
}
}
return retVal;
}
@Override
public String getBinaryMessage()
{
return mMessage.toString();
}
@Override
public String getProtocol()
{
return "MDC-1200";
}
@Override
public String getEventType()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getFromID()
{
return getUnitID();
}
@Override
public Alias getFromIDAlias()
{
return mAliasList.getMDC1200Alias( getFromID() );
}
@Override
public String getToID()
{
// TODO Auto-generated method stub
return null;
}
@Override
public Alias getToIDAlias()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( "MDC1200 UNIT:" + getUnitID() );
if( isEmergency() )
{
sb.append( " **EMERGENCY**" );
}
if( isBOT() )
{
sb.append( " BOT" );
}
if( isEOT() )
{
sb.append( " EOT" );
}
sb.append( " OPCODE:" + format( getOpcode(), 2 ) );
sb.append( " ARG:" + format( getArgument(), 3 ) );
sb.append( " TYPE:" + getPacketType().toString() );
sb.append( " ACK:" + getResponse().toString() );
sb.append( " DIR:" + pad( getDirection().toString(), 3, " " ) );
return sb.toString();
}
@Override
public String getErrorStatus()
{
// TODO Auto-generated method stub
return null;
}
@Override
public Plottable getPlottable()
{
// TODO Auto-generated method stub
return null;
}
/**
* Provides a listing of aliases contained in the message.
*/
public List<Alias> getAliases()
{
List<Alias> aliases = new ArrayList<Alias>();
Alias from = getFromIDAlias();
if( from != null )
{
aliases.add( from );
}
Alias to = getToIDAlias();
if( to != null )
{
aliases.add( to );
}
return aliases;
}
private enum PacketType { CMND, DATA };
private enum Acknowledge { YES, NO };
private enum Direction { IN, OUT };
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 spectrum;
import java.awt.Color;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import javax.swing.JPanel;
import settings.ColorSetting;
import settings.ColorSetting.ColorSettingName;
import settings.Setting;
import settings.SettingChangeListener;
import controller.ResourceManager;
public class ChannelOverlayPanel extends JPanel implements SettingChangeListener
{
private static final long serialVersionUID = 1L;
private static DecimalFormat sFORMAT = new DecimalFormat( "000.0" );
private static DecimalFormat sCURSOR_FORMAT = new DecimalFormat( "000.0" );
private double mBandwidth = 6000.0d;
private Point mCursorLocation = new Point( 0, 0 );
private boolean mCursorVisible = false;
/**
* Colors used by this component
*/
private Color mColorSpectrumBackground;
private Color mColorSpectrumCursor;
private Color mColorSpectrumLine;
//Defines the offset at the bottom of the spectral display to account for
//the frequency labels
private float mSpectrumInset = 20.0f;
private ResourceManager mResourceManager;
/**
* Translucent overlay panel for displaying channel configurations,
* processing channels, selected channels, frequency labels and lines, and
* a cursor with a frequency readout.
*/
public ChannelOverlayPanel( ResourceManager resourceManager )
{
mResourceManager = resourceManager;
//Set the background transparent, so the spectrum display can be seen
setOpaque( false );
//Fetch color settings from settings manager
setColors();
}
public void dispose()
{
mResourceManager = null;
}
public void setCursorLocation( Point point )
{
mCursorLocation = point;
repaint();
}
public void setCursorVisible( boolean visible )
{
mCursorVisible = visible;
repaint();
}
/**
* Fetches the color settings from the settings manager
*/
private void setColors()
{
mColorSpectrumCursor = getColor( ColorSettingName.SPECTRUM_CURSOR );
mColorSpectrumLine = getColor( ColorSettingName.SPECTRUM_LINE );
mColorSpectrumBackground =
getColor( ColorSettingName.SPECTRUM_BACKGROUND );
}
/**
* Fetches a named color setting from the settings manager. If the setting
* doesn't exist, creates the setting using the defaultColor
*/
private Color getColor( ColorSettingName name )
{
ColorSetting setting =
mResourceManager.getSettingsManager()
.getColorSetting( name );
return setting.getColor();
}
/**
* Monitors for setting changes. Colors can be changed by external actions
* and will automatically update in this class
*/
@Override
public void settingChanged( Setting setting )
{
if( setting instanceof ColorSetting )
{
ColorSetting colorSetting = (ColorSetting)setting;
switch( colorSetting.getColorSettingName() )
{
case SPECTRUM_BACKGROUND:
mColorSpectrumBackground = colorSetting.getColor();
break;
case SPECTRUM_CURSOR:
mColorSpectrumCursor = colorSetting.getColor();
break;
case SPECTRUM_LINE:
mColorSpectrumLine = colorSetting.getColor();
break;
}
}
}
/**
* Renders the channel configs, lines, labels, and cursor
*/
@Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Graphics2D graphics = (Graphics2D) g;
graphics.setBackground( mColorSpectrumBackground );
RenderingHints renderHints =
new RenderingHints( RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON );
renderHints.put( RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY );
graphics.setRenderingHints( renderHints );
drawFrequencies( graphics );
drawCursor( graphics );
}
/**
* Draws a cursor on the panel, whenever the mouse is hovering over the
* panel
*/
private void drawCursor( Graphics2D graphics )
{
if( mCursorVisible )
{
drawFrequencyLine( graphics,
mCursorLocation.x,
mColorSpectrumCursor );
double value = mBandwidth *
( mCursorLocation.getX() / getSize().getWidth() );
String frequency = sCURSOR_FORMAT.format( value );
graphics.drawString( frequency ,
mCursorLocation.x + 5,
mCursorLocation.y );
}
}
/**
* Draws the frequency lines and labels every 10kHz
*/
private void drawFrequencies( Graphics2D graphics )
{
drawFrequencyLine( graphics, getAxisFromFrequency( 1000 ), Color.LIGHT_GRAY );
drawFrequencyLineAndLabel( graphics, 2000 );
drawFrequencyLine( graphics, getAxisFromFrequency( 3000 ), Color.LIGHT_GRAY );
drawFrequencyLineAndLabel( graphics, 4000 );
drawFrequencyLine( graphics, getAxisFromFrequency( 5000 ), Color.LIGHT_GRAY );
// drawFrequencyLineAndLabel( graphics, 6000 );
// drawFrequencyLine( graphics, getAxisFromFrequency( 7000 ), Color.LIGHT_GRAY );
// drawFrequencyLineAndLabel( graphics, 8000 );
// drawFrequencyLine( graphics, getAxisFromFrequency( 9000 ), Color.LIGHT_GRAY );
// drawFrequencyLineAndLabel( graphics, 10000 );
// drawFrequencyLine( graphics, getAxisFromFrequency( 11000 ), Color.LIGHT_GRAY );
}
private float getAxisFromFrequency( long frequency )
{
return (float)( getSize().getWidth() * ( (double)frequency / mBandwidth ) );
}
/**
* Draws a vertical line and a corresponding frequency label at the bottom
*/
private void drawFrequencyLineAndLabel( Graphics2D graphics, long frequency )
{
float xAxis = (float)( getSize().getWidth() *
( (double)frequency / mBandwidth ) );
drawFrequencyLine( graphics, xAxis, mColorSpectrumLine );
graphics.setColor( mColorSpectrumLine );
drawFrequencyLabel( graphics, xAxis, frequency );
}
/**
* Draws a vertical line at the xaxis
*/
private void drawFrequencyLine( Graphics2D graphics, float xaxis, Color color )
{
graphics.setColor( color );
graphics.draw( new Line2D.Float( xaxis, 0,
xaxis, (float)(getSize().getHeight()) - mSpectrumInset ) );
}
/**
* Draws a frequency label at the x-axis position, at the bottom of the panel
*/
private void drawFrequencyLabel( Graphics2D graphics,
float xaxis,
long frequency )
{
String label = sFORMAT.format( (float)frequency );
FontMetrics fontMetrics = graphics.getFontMetrics( this.getFont() );
Rectangle2D rect = fontMetrics.getStringBounds( label, graphics );
float offset = (float)rect.getWidth() / 2;
graphics.drawString( label, xaxis - offset,
(float)getSize().getHeight() - ( mSpectrumInset * 0.2f ) );
}
public void settingDeleted( Setting setting ) {}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 map;
import java.util.HashMap;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import alias.Alias;
public class Plottable implements Comparable<Plottable>
{
private long mTimestamp;
private GeoPosition mGeoPosition;
private String mID;
private Alias mAlias;
HashMap<String,String> mAttributes = new HashMap<String,String>();
public Plottable()
{
}
public Plottable( long timestamp,
GeoPosition position,
String id,
Alias alias,
HashMap<String,String> attributes )
{
this( timestamp, position, id, alias );
mAttributes = attributes;
}
public Plottable( long timestamp,
GeoPosition position,
String id,
Alias alias )
{
mTimestamp = timestamp;
mGeoPosition = position;
mID = id;
mAlias = alias;
}
public long getTimestamp()
{
return mTimestamp;
}
public void setTimestamp( long timestamp )
{
mTimestamp = timestamp;
}
public GeoPosition getGeoPosition()
{
return mGeoPosition;
}
public void setGeoPosition( GeoPosition position )
{
mGeoPosition = position;
}
public String getID()
{
return mID;
}
public void setID( String id )
{
mID = id;
}
public Alias getAlias()
{
return mAlias;
}
public void setAlias( Alias alias )
{
mAlias = alias;
}
public HashMap<String,String> getAttributes()
{
return mAttributes;
}
public void addAttribute( String key, String value )
{
mAttributes.put( key, value );
}
public void removeAttribute( String key )
{
mAttributes.remove( key );
}
public void clearAttributes()
{
mAttributes.clear();
}
/**
* Comparisons for sorting of plottables is based on timestamps
*/
@Override
public int compareTo( Plottable o )
{
if( mTimestamp == o.mTimestamp )
{
return 0;
}
else if( mTimestamp < o.mTimestamp )
{
return -1;
}
else
{
return 1;
}
}
}
<file_sep>package decode.p25.message.tsbk.osp.voice;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.GroupMultiChannelGrant;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class GroupVoiceChannelGrantUpdate extends GroupMultiChannelGrant
{
public GroupVoiceChannelGrantUpdate( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.GROUP_VOICE_CHANNEL_GRANT_UPDATE.getDescription();
}
}
<file_sep>package decode.p25.message.filter;
import java.util.Collections;
import java.util.List;
import message.Message;
import decode.p25.message.ldu.LDUMessage;
import filter.Filter;
import filter.FilterElement;
public class LDUMessageFilter extends Filter<Message>
{
public LDUMessageFilter()
{
super( "Link Data Unit" );
}
@Override
public boolean passes( Message message )
{
return mEnabled && canProcess( message );
}
@Override
public boolean canProcess( Message message )
{
return message instanceof LDUMessage;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return Collections.EMPTY_LIST;
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.tsbk.osp.control.SystemService;
import decode.p25.reference.LinkControlOpcode;
public class AdjacentSiteStatusBroadcastExplicit extends TDULinkControlMessage
{
private final static Logger mLog =
LoggerFactory.getLogger( AdjacentSiteStatusBroadcastExplicit.class );
public static final int[] LRA = { 72,73,74,75,88,89,90,91 };
public static final int[] TRANSMIT_IDENTIFIER = { 92,93,94,95 };
public static final int[] TRANSMIT_CHANNEL = { 96,97,98,99,112,113,114,115,
116,117,118,119 };
public static final int[] RFSS_ID = { 120,121,122,123,136,137,138,139 };
public static final int[] SITE_ID = { 140,141,142,143,144,145,146,147 };
public static final int[] RECEIVE_IDENTIFIER = { 160,161,162,163 };
public static final int[] RECEIVE_CHANNEL = { 164,165,166,167,168,169,170,
171,184,185,186,187 };
public AdjacentSiteStatusBroadcastExplicit( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.ADJACENT_SITE_STATUS_BROADCAST_EXPLICIT.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " LRA:" + getLocationRegistrationArea() );
sb.append( " SITE:" + getRFSubsystemID() + "-" + getSiteID() );
sb.append( " DNLINK:" + getTransmitChannelNumber() );
sb.append( " UPLINK:" + getReceiveChannelNumber() );
return sb.toString();
}
public String getLocationRegistrationArea()
{
return mMessage.getHex( LRA, 2 );
}
public String getRFSubsystemID()
{
return mMessage.getHex( RFSS_ID, 2 );
}
public String getSiteID()
{
return mMessage.getHex( SITE_ID, 2 );
}
public int getTransmitIdentifier()
{
return mMessage.getInt( TRANSMIT_IDENTIFIER );
}
public int getTransmitChannel()
{
return mMessage.getInt( TRANSMIT_CHANNEL );
}
public String getTransmitChannelNumber()
{
return getTransmitIdentifier() + "-" + getTransmitChannel();
}
public int getReceiveIdentifier()
{
return mMessage.getInt( RECEIVE_IDENTIFIER );
}
public int getReceiveChannel()
{
return mMessage.getInt( RECEIVE_CHANNEL );
}
public String getReceiveChannelNumber()
{
return getReceiveIdentifier() + "-" + getReceiveChannel();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.ltrnet;
import java.util.HashMap;
import message.Message;
import message.MessageDirection;
import message.MessageType;
import sample.Broadcaster;
import sample.Listener;
import alias.AliasList;
import bits.BinaryMessage;
public class LTRNetMessageProcessor implements Listener<BinaryMessage>
{
private Broadcaster<Message> mBroadcaster = new Broadcaster<Message>();
private HashMap<Integer,LTRNetOSWMessage> mReceiveHighAuxMessages =
new HashMap<Integer,LTRNetOSWMessage>();
private HashMap<Integer,LTRNetOSWMessage> mReceiveLowAuxMessages =
new HashMap<Integer,LTRNetOSWMessage>();
private HashMap<Integer,LTRNetOSWMessage> mTransmitHighAuxMessages =
new HashMap<Integer,LTRNetOSWMessage>();
private HashMap<Integer,LTRNetOSWMessage> mTransmitLowAuxMessages =
new HashMap<Integer,LTRNetOSWMessage>();
private LTRNetISWMessage mESNHighMessage;
private LTRNetISWMessage mESNLowMessage;
private MessageDirection mDirection;
private AliasList mAliasList;
public LTRNetMessageProcessor( MessageDirection direction,
AliasList list )
{
mDirection = direction;
mAliasList = list;
}
@Override
public void receive( BinaryMessage buffer )
{
LTRNetMessage message;
if( mDirection == MessageDirection.OSW )
{
message = new LTRNetOSWMessage( buffer, mAliasList );
if( message.isValid() )
{
if( message.getMessageType() == MessageType.FQ_TXHI )
{
mTransmitHighAuxMessages.put( message.getHomeRepeater(),
(LTRNetOSWMessage)message );
message.setAuxiliaryMessage( mTransmitLowAuxMessages.get(
message.getHomeRepeater() ) );
}
else if( message.getMessageType() == MessageType.FQ_TXLO )
{
mTransmitLowAuxMessages.put( message.getHomeRepeater(),
(LTRNetOSWMessage)message );
message.setAuxiliaryMessage( mTransmitHighAuxMessages.get(
message.getHomeRepeater() ) );
}
else if( message.getMessageType() == MessageType.FQ_RXHI )
{
mReceiveHighAuxMessages.put( message.getHomeRepeater(),
(LTRNetOSWMessage)message );
message.setAuxiliaryMessage( mReceiveLowAuxMessages.get(
message.getHomeRepeater() ) );
}
else if( message.getMessageType() == MessageType.FQ_RXLO )
{
mReceiveLowAuxMessages.put( message.getHomeRepeater(),
(LTRNetOSWMessage)message );
message.setAuxiliaryMessage( mReceiveHighAuxMessages.get(
message.getHomeRepeater() ) );
}
}
}
else
{
buffer.flip( 0, 40 );
message = new LTRNetISWMessage( buffer, mAliasList );
if( message.isValid() )
{
/**
* Catch ESN High messages to marry up with ESN Low messages. Purge
* the ESN high message after 2 messages, so that it doesn't get
* paired with the wrong esn low message
*/
if( message.getMessageType() == MessageType.ID_ESNH )
{
mESNHighMessage = (LTRNetISWMessage)message;
if( mESNLowMessage != null )
{
/* Check that the stored message is not older than
* 5 seconds */
if( System.currentTimeMillis() -
mESNLowMessage.getTimeReceived() < 5000 )
{
((LTRNetISWMessage)message).setAuxiliaryMessage( mESNLowMessage );
}
else
{
mESNLowMessage = null;
}
}
}
else if( message.getMessageType() == MessageType.ID_ESNL )
{
mESNLowMessage = (LTRNetISWMessage)message;
if( mESNHighMessage != null )
{
/* Check that the stored message is not older than 5 seconds */
if( System.currentTimeMillis() - mESNHighMessage.getTimeReceived() < 5000 )
{
((LTRNetISWMessage)message).setAuxiliaryMessage( mESNHighMessage );
}
else
{
mESNHighMessage = null;
}
}
}
}
}
mBroadcaster.receive( message );
}
public void addMessageListener( Listener<Message> listener )
{
mBroadcaster.addListener( listener );
}
public void removeMessageListener( Listener<Message> listener )
{
mBroadcaster.removeListener( listener );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.ltrstandard;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import message.MessageDirection;
import decode.DecodeEditor;
import decode.config.DecodeConfigLTRStandard;
import decode.config.DecodeConfiguration;
public class LTRStandardEditor extends DecodeEditor
{
private static final long serialVersionUID = 1L;
private JComboBox<MessageDirection> mComboDirection;
public LTRStandardEditor( DecodeConfiguration config )
{
super( config );
initGUI();
}
private void initGUI()
{
mComboDirection = new JComboBox<MessageDirection>();
mComboDirection.setModel(
new DefaultComboBoxModel<MessageDirection>( MessageDirection.values() ) );
mComboDirection.setSelectedItem( ((DecodeConfigLTRStandard)mConfig).getMessageDirection() );
mComboDirection.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
MessageDirection selected = mComboDirection
.getItemAt( mComboDirection.getSelectedIndex() );
if( selected != null )
{
((DecodeConfigLTRStandard)mConfig).setMessageDirection( selected );
}
}
} );
add( mComboDirection, "span 2" );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 dsp.fsk;
import instrument.Instrumentable;
import instrument.tap.Tap;
import instrument.tap.stream.BinaryTap;
import instrument.tap.stream.FloatTap;
import instrument.tap.stream.SymbolEventTap;
import java.util.ArrayList;
import java.util.List;
import sample.Listener;
import sample.real.RealSampleListener;
import dsp.filter.DCRemovalFilter3;
import dsp.filter.Filters;
import dsp.filter.FloatHalfBandFilter;
import dsp.filter.FloatHalfBandNoDecimateFilter;
import dsp.filter.LTRPulseShapingFilter;
import dsp.filter.SquaringFilter;
import dsp.symbol.Slicer;
import dsp.symbol.Slicer.Output;
public class LTRFSKDecoder implements RealSampleListener, Instrumentable
{
private FloatHalfBandFilter mHBFilter1;
private FloatHalfBandFilter mHBFilter2;
private FloatHalfBandFilter mHBFilter3;
private FloatHalfBandFilter mHBFilter4;
private FloatHalfBandFilter mHBFilter5;
private FloatHalfBandNoDecimateFilter mHBFilter6;
private DCRemovalFilter3 mDCFilter;
private SquaringFilter mSquaringFilter;
private LTRPulseShapingFilter mPulseShaper;
private Slicer mSlicer;
private List<Tap> mAvailableTaps;
private final String TAP_F1_F2 = "LTR FSK Demod Filter1 >< Filter2";
private final String TAP_F2_F3 = "LTR FSK Demod Filter2 >< Filter3";
private final String TAP_F3_F4 = "LTR FSK Demod Filter3 >< Filter4";
private final String TAP_F4_F5 = "LTR FSK Demod Filter4 >< Filter5";
private final String TAP_F5_F6 = "LTR FSK Demod Filter5 >< Filter6";
private final String TAP_F6_DT = "LTR FSK Demod Filter6 >< DC Filter";
private final String TAP_DT_SF1 = "LTR FSK Demod DC Filter >< Squaring Filter";
private final String TAP_SF1_PS = "LTR FSK Demod Squaring Filter >< Pulse Shaper";
private final String TAP_PS_SLICER = "LTR FSK Demod Pulse Shaper >< Slicer";
private final String TAP_SYMBOL_EVENT = "LTR FSK Demod Symbol Event";
/**
* Implements a Logic Trunked Radio sub-audible 300 baud FSK signaling
* decoder. Expects a 48000 sample rate input.
*/
public LTRFSKDecoder()
{
mHBFilter1 = new FloatHalfBandFilter(
Filters.FIR_HALF_BAND_31T_ONE_EIGHTH_FCO, 1.1002 );
mHBFilter2 = new FloatHalfBandFilter(
Filters.FIR_HALF_BAND_31T_ONE_EIGHTH_FCO, 1.1002 );
mHBFilter1.setListener( mHBFilter2 );
mHBFilter3 = new FloatHalfBandFilter(
Filters.FIR_HALF_BAND_31T_ONE_EIGHTH_FCO, 1.1002 );
mHBFilter2.setListener( mHBFilter3 );
mHBFilter4 = new FloatHalfBandFilter(
Filters.FIR_HALF_BAND_31T_ONE_EIGHTH_FCO, 1.1002 );
mHBFilter3.setListener( mHBFilter4 );
mHBFilter5 = new FloatHalfBandFilter(
Filters.FIR_HALF_BAND_31T_ONE_EIGHTH_FCO, 1.1002 );
mHBFilter4.setListener( mHBFilter5 );
mHBFilter6 = new FloatHalfBandNoDecimateFilter(
Filters.FIR_HALF_BAND_31T_ONE_EIGHTH_FCO, 1.1002 );
mHBFilter5.setListener( mHBFilter6 );
mDCFilter = new DCRemovalFilter3( 0.9946f );
mHBFilter6.setListener( mDCFilter );
mSquaringFilter = new SquaringFilter();
mDCFilter.setListener( mSquaringFilter );
mPulseShaper = new LTRPulseShapingFilter();
mSquaringFilter.setListener( mPulseShaper );
mSlicer = new Slicer( Output.NORMAL, 5 );
mPulseShaper.setListener( mSlicer );
}
@Override
public void receive( float sample )
{
mHBFilter1.receive( sample );
}
public void addListener( Listener<Boolean> listener )
{
mSlicer.setListener( listener );
}
public void removeListener( Listener<Boolean> listener )
{
mSlicer.removeListener( listener );
}
@Override
public List<Tap> getTaps()
{
if( mAvailableTaps == null )
{
mAvailableTaps = new ArrayList<Tap>();
mAvailableTaps.add( new FloatTap( TAP_F1_F2, 0, 1.0f ) );
mAvailableTaps.add( new FloatTap( TAP_F2_F3, 8, 0.5f ) );
mAvailableTaps.add( new FloatTap( TAP_F3_F4, 12, 0.25f ) );
mAvailableTaps.add( new FloatTap( TAP_F4_F5, 14, 0.125f ) );
mAvailableTaps.add( new FloatTap( TAP_F5_F6, 15, 0.0625f ) );
mAvailableTaps.add( new FloatTap( TAP_F6_DT, 31, 0.0625f ) );
mAvailableTaps.add( new FloatTap( TAP_DT_SF1, 31, 0.0625f ) );
mAvailableTaps.add( new BinaryTap( TAP_SF1_PS, 33, 0.0625f ) );
mAvailableTaps.add( new BinaryTap( TAP_PS_SLICER, 33, 0.0625f ) );
mAvailableTaps.add( new SymbolEventTap( TAP_SYMBOL_EVENT, 7, 0.0125f ) );
}
return mAvailableTaps;
}
@Override
public void addTap( Tap tap )
{
switch( tap.getName() )
{
case TAP_F1_F2:
mHBFilter1.setListener( (FloatTap)tap );
((FloatTap)tap).setListener( mHBFilter2 );
break;
case TAP_F2_F3:
mHBFilter2.setListener( (FloatTap)tap );
((FloatTap)tap).setListener( mHBFilter3 );
break;
case TAP_F3_F4:
mHBFilter3.setListener( (FloatTap)tap );
((FloatTap)tap).setListener( mHBFilter4 );
break;
case TAP_F4_F5:
mHBFilter4.setListener( (FloatTap)tap );
((FloatTap)tap).setListener( mHBFilter5 );
break;
case TAP_F5_F6:
mHBFilter5.setListener( (FloatTap)tap );
((FloatTap)tap).setListener( mHBFilter6 );
break;
case TAP_F6_DT:
mHBFilter6.setListener( (FloatTap)tap );
((FloatTap)tap).setListener( mDCFilter );
break;
case TAP_DT_SF1:
mDCFilter.setListener( (FloatTap)tap );
((FloatTap)tap).setListener( mSquaringFilter );
break;
case TAP_SF1_PS:
mSquaringFilter.setListener( (BinaryTap)tap );
((BinaryTap)tap).setListener( mPulseShaper );
break;
case TAP_PS_SLICER:
mPulseShaper.setListener( (BinaryTap)tap );
((BinaryTap)tap).setListener( mSlicer );
break;
case TAP_SYMBOL_EVENT:
mSlicer.addTap( (SymbolEventTap)tap );
break;
}
}
@Override
public void removeTap( Tap tap )
{
switch( tap.getName() )
{
case TAP_F1_F2:
mHBFilter1.setListener( mHBFilter2 );
break;
case TAP_F2_F3:
mHBFilter2.setListener( mHBFilter3 );
break;
case TAP_F3_F4:
mHBFilter3.setListener( mHBFilter4 );
break;
case TAP_F4_F5:
mHBFilter4.setListener( mHBFilter5 );
break;
case TAP_F5_F6:
mHBFilter5.setListener( mHBFilter6 );
break;
case TAP_F6_DT:
mHBFilter6.setListener( mDCFilter );
break;
case TAP_DT_SF1:
mDCFilter.setListener( mSquaringFilter );
break;
case TAP_SF1_PS:
mSquaringFilter.setListener( mPulseShaper );
break;
case TAP_PS_SLICER:
mPulseShaper.setListener( mSlicer );
break;
case TAP_SYMBOL_EVENT:
mSlicer.removeTap();
break;
}
}
}
<file_sep>package decode.p25.message.ldu;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.P25Message;
import decode.p25.reference.DataUnitID;
public abstract class LDUMessage extends P25Message
{
private final static Logger mLog = LoggerFactory.getLogger( LDUMessage.class );
public static final int IMBE_FRAME_1 = 64;
public static final int IMBE_FRAME_2 = 208;
public static final int IMBE_FRAME_3 = 392;
public static final int IMBE_FRAME_4 = 576;
public static final int IMBE_FRAME_5 = 760;
public static final int IMBE_FRAME_6 = 944;
public static final int IMBE_FRAME_7 = 1128;
public static final int IMBE_FRAME_8 = 1312;
public static final int IMBE_FRAME_9 = 1488;
public static final int[] LOW_SPEED_DATA = { 1456,1457,1458,1459,1460,1461,
1462,1463,1472,1473,1474,1475,1476,1477,1478,1479 };
public LDUMessage( BinaryMessage message, DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
public abstract boolean isEncrypted();
@Override
public String getMessage()
{
return getMessageStub();
}
public String getMessageStub()
{
StringBuilder sb = new StringBuilder();
sb.append( "NAC:" );
sb.append( getNAC() );
sb.append( " " );
sb.append( getDUID().getLabel() );
sb.append( " VOICE LSD:" );
sb.append( getLowSpeedData() );
sb.append( " " );
return sb.toString();
}
public String getLowSpeedData()
{
return mMessage.getHex( LOW_SPEED_DATA, 4 );
}
public boolean isValid()
{
// return mCRC[ 2 ] != null && mCRC[ 2 ] != CRC.FAILED_CRC;
return true;
}
/**
* Returns a 162 byte array containing 9 IMBE voice frames of 18-bytes
* (144-bits) each. Each frame is intact as transmitted and requires
* deinterleaving, error correction, derandomizing, etc.
*/
public List<byte[]> getIMBEFrames()
{
List<byte[]> frames = new ArrayList<byte[]>();
frames.add( mMessage.get( IMBE_FRAME_1, IMBE_FRAME_1 + 144 ).toByteArray() );
frames.add( mMessage.get( IMBE_FRAME_2, IMBE_FRAME_2 + 144 ).toByteArray() );
frames.add( mMessage.get( IMBE_FRAME_3, IMBE_FRAME_3 + 144 ).toByteArray() );
frames.add( mMessage.get( IMBE_FRAME_4, IMBE_FRAME_4 + 144 ).toByteArray() );
frames.add( mMessage.get( IMBE_FRAME_5, IMBE_FRAME_5 + 144 ).toByteArray() );
frames.add( mMessage.get( IMBE_FRAME_6, IMBE_FRAME_6 + 144 ).toByteArray() );
frames.add( mMessage.get( IMBE_FRAME_7, IMBE_FRAME_7 + 144 ).toByteArray() );
frames.add( mMessage.get( IMBE_FRAME_8, IMBE_FRAME_8 + 144 ).toByteArray() );
frames.add( mMessage.get( IMBE_FRAME_9, IMBE_FRAME_9 + 144 ).toByteArray() );
return frames;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.config;
import javax.xml.bind.annotation.XmlAttribute;
import source.SourceType;
import source.mixer.MixerChannel;
public class SourceConfigMixer extends SourceConfiguration
{
protected String mMixer;
protected MixerChannel mChannel = MixerChannel.LEFT; //default
public SourceConfigMixer()
{
super( SourceType.MIXER );
}
@Override
public String getDescription()
{
return getName();
}
public String getName()
{
StringBuilder sb = new StringBuilder();
sb.append( mMixer );
sb.append( "-" );
sb.append( mChannel.toString() );
return sb.toString();
}
@XmlAttribute( name= "mixer" )
public String getMixer()
{
return mMixer;
}
public void setMixer( String mixer )
{
mMixer = mixer;
}
@XmlAttribute( name = "channel" )
public MixerChannel getChannel()
{
return mChannel;
}
public void setChannel( MixerChannel channel )
{
mChannel = channel;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 map;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import org.jdesktop.swingx.JXMapViewer;
/**
* Creates a selection rectangle based on mouse input
* Also triggers repaint events in the viewer
* @author <NAME>
*/
public class SelectionAdapter extends MouseAdapter
{
private boolean dragging;
private JXMapViewer viewer;
private Point2D startPos = new Point2D.Double();
private Point2D endPos = new Point2D.Double();
/**
* @param viewer the jxmapviewer
*/
public SelectionAdapter(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void mousePressed(MouseEvent e)
{
if (e.getButton() != MouseEvent.BUTTON3)
return;
startPos.setLocation(e.getX(), e.getY());
endPos.setLocation(e.getX(), e.getY());
dragging = true;
}
@Override
public void mouseDragged(MouseEvent e)
{
if (!dragging)
return;
endPos.setLocation(e.getX(), e.getY());
viewer.repaint();
}
@Override
public void mouseReleased(MouseEvent e)
{
if (!dragging)
return;
if (e.getButton() != MouseEvent.BUTTON3)
return;
viewer.repaint();
dragging = false;
}
/**
* @return the selection rectangle
*/
public Rectangle getRectangle()
{
if (dragging)
{
int x1 = (int) Math.min(startPos.getX(), endPos.getX());
int y1 = (int) Math.min(startPos.getY(), endPos.getY());
int x2 = (int) Math.max(startPos.getX(), endPos.getX());
int y2 = (int) Math.max(startPos.getY(), endPos.getY());
return new Rectangle(x1, y1, x2-x1, y2-y1);
}
return null;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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.jdesktop.swingx.input;
import java.awt.Rectangle;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.SwingUtilities;
import org.jdesktop.swingx.JXMapViewer;
/**
* Centers the map on the mouse cursor
* if left is double-clicked or middle mouse
* button is pressed.
* @author <NAME>
* @author joshy
*/
public class CenterMapListener extends MouseAdapter
{
private JXMapViewer viewer;
/**
* @param viewer the jxmapviewer
*/
public CenterMapListener(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void mousePressed(MouseEvent evt)
{
boolean left = SwingUtilities.isLeftMouseButton(evt);
boolean middle = SwingUtilities.isMiddleMouseButton(evt);
boolean doubleClick = (evt.getClickCount() == 2);
if (middle || (left && doubleClick))
{
recenterMap(evt);
}
}
private void recenterMap(MouseEvent evt)
{
Rectangle bounds = viewer.getViewportBounds();
double x = bounds.getX() + evt.getX();
double y = bounds.getY() + evt.getY();
viewer.setCenter(new Point2D.Double(x, y));
viewer.setZoom(viewer.getZoom() - 1);
viewer.repaint();
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class AuthenticationCommand extends TSBKMessage
{
public static final int[] WACN = { 88,89,90,91,92,93,94,95,96,97,98,99,100,
101,102,103,104,105,106,107 };
public static final int[] SYSTEM_ID = { 108,109,110,111,112,113,114,115,116,
117,118,119 };
public static final int[] TARGET_ID = { 120,121,122,123,124,125,126,
127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 };
public AuthenticationCommand( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.AUTHENTICATION_COMMAND.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " WACN: " + getWACN() );
sb.append( " SYS ID: " + getSystemID() );
sb.append( " TGT ID: " + getTargetID() );
return sb.toString();
}
public String getWACN()
{
return mMessage.getHex( WACN, 5 );
}
public String getSystemID()
{
return mMessage.getHex( SYSTEM_ID, 3 );
}
public String getTargetID()
{
return mMessage.getHex( TARGET_ID, 6 );
}
public String getFullTargetID()
{
StringBuilder sb = new StringBuilder();
sb.append( getWACN() );
sb.append( "-" );
sb.append( getSystemID() );
sb.append( "-" );
sb.append( getTargetID() );
return sb.toString();
}
@Override
public String getToID()
{
return getTargetID();
}
}
<file_sep>package source.recording;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import controller.BaseNode;
public class RecordingNode extends BaseNode
{
private static final long serialVersionUID = 1L;
private JPanel mEditor;
public RecordingNode( Recording recording )
{
super( recording );
}
public Recording getRecording()
{
return (Recording)getUserObject();
}
public String toString()
{
return getRecording().toString();
}
@Override
public JPanel getEditor()
{
if( mEditor == null )
{
mEditor = new RecordingEditorPanel( this );
}
return mEditor;
}
public JPopupMenu getContextMenu()
{
JPopupMenu menu = new JPopupMenu();
JMenuItem deleteItem = new JMenuItem( "Delete" );
deleteItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
if( getRecording().hasChannels() )
{
JOptionPane.showMessageDialog( getModel().getTree(),
"Can't delete recording - currently in use. Please"
+ " disable any channel(s) that are using this "
+ "recording before deleting it",
"Can't delete recording",
JOptionPane.ERROR_MESSAGE );
}
else
{
getModel().getResourceManager().getRecordingSourceManager()
.removeRecording( getRecording() );
getModel().removeNodeFromParent( RecordingNode.this );
}
}
} );
menu.add( deleteItem );
return menu;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 edac;
public enum CRC
{
PASSED ( "*", "PASS" ),
PASSED_INV ( "#", "PASS INVERTED" ),
FAILED_CRC ( "f", "FAIL CRC" ),
FAILED_PARITY( "p", "FAIL PARITY" ),
CORRECTED ( "C", "CORRECTED" ),
UNKNOWN ( "-", "UNKNOWN");
private String mAbbreviation;
private String mDisplayText;
CRC( String abbreviation, String displayText )
{
mAbbreviation = abbreviation;
mDisplayText = displayText;
}
public String getAbbreviation()
{
return mAbbreviation;
}
public String getDisplayText()
{
return mDisplayText;
}
public static String format( CRC[] checks )
{
if( checks == null )
{
return CRC.UNKNOWN.getAbbreviation();
}
StringBuilder sb = new StringBuilder();
for( int x = 0; x < checks.length; x++ )
{
CRC check = checks[ x ];
if( check != null )
{
sb.append( check.getAbbreviation() );
}
else
{
sb.append( CRC.UNKNOWN.getAbbreviation() );
}
}
return sb.toString();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.fcd.proplusV2;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import javax.swing.JPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import source.SourceException;
import source.tuner.TunerClass;
import source.tuner.TunerConfiguration;
import source.tuner.TunerType;
import source.tuner.fcd.FCDCommand;
import source.tuner.fcd.FCDTuner;
import source.tuner.fcd.FCDTunerController;
import controller.ResourceManager;
public class FCD2TunerController extends FCDTunerController
{
private final static Logger mLog =
LoggerFactory.getLogger( FCD2TunerController.class );
public static final int sMINIMUM_TUNABLE_FREQUENCY = 150000;
public static final int sMAXIMUM_TUNABLE_FREQUENCY = 2050000000;
public static final int sSAMPLE_RATE = 192000;
private FCD2TunerConfiguration mTunerConfiguration;
private FCD2TunerEditorPanel mEditor;
public FCD2TunerController( Device device, DeviceDescriptor descriptor )
{
super( device,
descriptor,
sMINIMUM_TUNABLE_FREQUENCY,
sMAXIMUM_TUNABLE_FREQUENCY );
}
public void init() throws SourceException
{
super.init();
mFrequencyController.setSampleRate( sSAMPLE_RATE );
try
{
setFCDMode( Mode.APPLICATION );
}
catch( Exception e )
{
throw new SourceException( "error setting Mode to APPLICATION", e );
}
}
public int getCurrentSampleRate()
{
return sSAMPLE_RATE;
}
@Override
public TunerClass getTunerClass()
{
return TunerClass.FUNCUBE_DONGLE_PRO_PLUS;
}
@Override
public TunerType getTunerType()
{
return TunerType.FUNCUBE_DONGLE_PRO_PLUS;
}
public JPanel getEditor( FCDTuner tuner, ResourceManager resourceManager )
{
if( mEditor == null )
{
mEditor = new FCD2TunerEditorPanel( tuner, resourceManager );
}
return mEditor;
}
@Override
public void apply( TunerConfiguration config ) throws SourceException
{
if( config instanceof FCD2TunerConfiguration )
{
FCD2TunerConfiguration plusConfig =
(FCD2TunerConfiguration)config;
setFrequencyCorrection( plusConfig.getFrequencyCorrection() );
try
{
if( plusConfig.getGainLNA() )
{
send( FCDCommand.APP_SET_LNA_GAIN, 1 );
}
else
{
send( FCDCommand.APP_SET_LNA_GAIN, 0 );
}
}
catch ( Exception e )
{
throw new SourceException( "error while setting LNA Gain", e );
}
try
{
if( plusConfig.getGainMixer() )
{
send( FCDCommand.APP_SET_MIXER_GAIN, 1 );
}
else
{
send( FCDCommand.APP_SET_MIXER_GAIN, 0 );
}
}
catch ( Exception e )
{
throw new SourceException( "error while setting Mixer Gain", e );
}
mTunerConfiguration = plusConfig;
}
}
@Override
public TunerConfiguration getTunerConfiguration()
{
return mTunerConfiguration;
}
public int getDCCorrection()
{
int dcCorrection = -999;
try
{
ByteBuffer buffer = send( FCDCommand.APP_GET_DC_CORRECTION );
buffer.order( ByteOrder.LITTLE_ENDIAN );
return buffer.getInt( 2 );
}
catch ( Exception e )
{
mLog.error( "error getting dc correction value", e );
}
return dcCorrection;
}
public void setDCCorrection( int value )
{
try
{
send( FCDCommand.APP_SET_DC_CORRECTION, value );
}
catch ( Exception e )
{
mLog.error( "error setting dc correction to [" + value + "]", e );
}
}
public int getIQCorrection()
{
int iqCorrection = -999;
try
{
ByteBuffer buffer = send( FCDCommand.APP_GET_IQ_CORRECTION );
buffer.order( ByteOrder.LITTLE_ENDIAN );
return buffer.getInt( 2 );
}
catch ( Exception e )
{
mLog.error( "error reading IQ correction value", e );
}
return iqCorrection;
}
public void setIQCorrection( int value )
{
try
{
send( FCDCommand.APP_SET_IQ_CORRECTION, value );
}
catch ( Exception e )
{
mLog.error( "error setting IQ correction to [" + value + "]", e );
}
}
public enum Block
{
CELLULAR_BAND_BLOCKED( "Blocked" ),
NO_BAND_BLOCK( "Unblocked" ),
UNKNOWN( "Unknown" );
private String mLabel;
private Block( String label )
{
mLabel = label;
}
public String getLabel()
{
return mLabel;
}
public static Block getBlock( String block )
{
Block retVal = UNKNOWN;
if( block.equalsIgnoreCase( "No blk" ) )
{
retVal = NO_BAND_BLOCK;
}
else if( block.equalsIgnoreCase( "Cell blk" ) )
{
retVal = CELLULAR_BAND_BLOCKED;
}
return retVal;
}
}
}
<file_sep>package dsp.gain;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import sample.Provider;
import sample.complex.ComplexSample;
import buffer.FloatCircularBuffer;
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2015 <NAME>
*
* 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/>
*
* This class is modeled using concepts detailed in the GNURadio
* implementation of feed forward AGC class located at:
* https://github.com/gnuradio/gnuradio/blob/master/gr-analog/lib/
* feedforward_agc_cc_impl.cc
*
******************************************************************************/
public class ComplexFeedForwardGainControl
implements Listener<ComplexSample>, Provider<ComplexSample>
{
private final static Logger mLog =
LoggerFactory.getLogger( ComplexFeedForwardGainControl.class );
public static final float OBJECTIVE_ENVELOPE = 1.0f;
public static final float MINIMUM_ENVELOPE = 0.0001f;
private Listener<ComplexSample> mListener;
private FloatCircularBuffer mEnvelopeHistory;
private float mMaxEnvelope = 0.0f;
private float mGain = 1.0f;
/**
* Dynamic gain control for incoming sample stream to amplify or attenuate
* all samples toward an objective unity)gain, using the maximum envelope
* value detected in the stream history window.
*
* Uses the specified damping factor to limit gain swings. Damping factor
* is applied against the delta between current gain value and a recalculated
* gain value to limit how quickly the gain value will increase or decrease.
*
* @param window - history size to use in detecting maximum envelope value
* @param damping - a value between 0 < damping <= 1.0;
*/
public ComplexFeedForwardGainControl( int window )
{
mEnvelopeHistory = new FloatCircularBuffer( window );
}
@Override
public void receive( ComplexSample sample )
{
float envelope = sample.envelope();
if( envelope > mMaxEnvelope )
{
mMaxEnvelope = envelope;
adjustGain();
}
/* Replace oldest envelope value with current envelope value */
float oldestEnvelope = mEnvelopeHistory.get( envelope );
/* If the oldest envelope value was the max envelope value, then we
* have to rediscover the max value from the envelope history */
if( mMaxEnvelope == oldestEnvelope && mMaxEnvelope != envelope )
{
mMaxEnvelope = MINIMUM_ENVELOPE;
for( float value: mEnvelopeHistory.getBuffer() )
{
if( value > mMaxEnvelope )
{
mMaxEnvelope = value;
}
}
adjustGain();
}
/* Apply current gain value to the sample and send to the listener */
if( mListener != null )
{
sample.multiply( mGain );
mListener.receive( sample );
}
}
private void adjustGain()
{
mGain = OBJECTIVE_ENVELOPE / mMaxEnvelope;
}
@Override
public void setListener( Listener<ComplexSample> listener )
{
mListener = listener;
}
@Override
public void removeListener( Listener<ComplexSample> listener )
{
mListener = null;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 alias.talkgroup;
import javax.xml.bind.annotation.XmlAttribute;
import alias.AliasID;
import alias.AliasIDType;
import audio.inverted.AudioType;
public class TalkgroupID extends AliasID
{
private String mTalkgroup;
private AudioType mAudioType;
public TalkgroupID()
{
}
@XmlAttribute
public String getTalkgroup()
{
return mTalkgroup;
}
public void setTalkgroup( String talkgroup )
{
mTalkgroup = talkgroup;
}
@XmlAttribute
public AudioType getAudioType()
{
return mAudioType;
}
public void setAudioType( AudioType type )
{
mAudioType = type;
}
public boolean hasAudioType()
{
return mAudioType != null;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( "Talkgroup: " + mTalkgroup );
if( mAudioType != null )
{
sb.append( " [Audio " );
sb.append( mAudioType.getShortDisplayString() );
sb.append( "]" );
}
return sb.toString();
}
@Override
public boolean matches( AliasID id )
{
boolean retVal = false;
if( id instanceof TalkgroupID )
{
TalkgroupID tgid = (TalkgroupID)id;
//Create a pattern - replace * wildcards with regex single-char wildcard
String pattern = mTalkgroup.replace( "*", ".?" );
retVal = tgid.getTalkgroup().matches( pattern );
}
return retVal;
}
@Override
public AliasIDType getType()
{
return AliasIDType.Talkgroup;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.recording;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import controller.BaseNode;
public class RecordingGroupNode extends BaseNode
{
private static final long serialVersionUID = 1L;
public RecordingGroupNode()
{
super( null );
}
public String toString()
{
return "Recordings [" + this.getChildCount() + "]";
}
public JPopupMenu getContextMenu()
{
JPopupMenu menu = new JPopupMenu();
JMenuItem addRecordingItem = new JMenuItem( "Add Recording" );
addRecordingItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
RecordingConfiguration config = new RecordingConfiguration();
getModel().getResourceManager().getSettingsManager()
.addRecordingConfiguration( config );
Recording recording = getModel().getResourceManager()
.getRecordingSourceManager().addRecording( config );
RecordingNode node = new RecordingNode( recording );
getModel().addNode( node, RecordingGroupNode.this, 0 );
sort();
node.show();
}
} );
menu.add( addRecordingItem );
return menu;
}
public void loadRecordings()
{
List<Recording> recordings = getModel().getResourceManager()
.getRecordingSourceManager().getRecordings();
for( Recording recording: recordings )
{
RecordingNode node = new RecordingNode( recording );
getModel().addNode( node, this, 0 );
}
sort();
}
}
<file_sep>package decode.mpt1327;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import message.Message;
import decode.mpt1327.MPT1327Message.MPTMessageType;
import filter.Filter;
import filter.FilterElement;
public class MPT1327MessageFilter extends Filter<Message>
{
private HashMap<MPTMessageType,FilterElement<MPTMessageType>> mFilterElements =
new HashMap<MPTMessageType,FilterElement<MPTMessageType>>();
public MPT1327MessageFilter()
{
super( "MPT1327 Message Type Filter" );
for( MPTMessageType type: MPT1327Message.MPTMessageType.values() )
{
if( type != MPTMessageType.UNKN )
{
mFilterElements.put( type,
new FilterElement<MPTMessageType>( type ) );
}
}
}
@Override
public boolean passes( Message message )
{
if( mEnabled && canProcess( message ) )
{
MPT1327Message mpt = (MPT1327Message)message;
FilterElement<MPTMessageType> element =
mFilterElements.get( mpt.getMessageType() );
if( element != null )
{
return element.isEnabled();
}
}
return false;
}
@Override
public boolean canProcess( Message message )
{
return message instanceof MPT1327Message;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return new ArrayList<FilterElement<?>>( mFilterElements.values() );
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import decode.p25.reference.Response;
public class GroupAffiliationResponse extends TSBKMessage
{
public static final int LOCAL_GLOBAL_AFFILIATION_FLAG = 80;
public static final int[] AFFILIATION_RESPONSE = { 86,87 };
public static final int[] ANNOUNCEMENT_GROUP_ADDRESS = { 88,89,90,91,
92,93,94,95,96,97,98,99,100,101,102,103 };
public static final int[] GROUP_ADDRESS = { 104,105,106,107,108,109,110,111,
112,113,114,115,116,117,118,119 };
public static final int[] TARGET_ADDRESS = { 120,121,122,123,124,125,126,
127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 };
public GroupAffiliationResponse( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.GROUP_AFFILIATION_RESPONSE.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " AFFILIATION:" + getResponse().name() );
sb.append( " ANNOUNCE GROUP:" + getAnnouncementGroupAddress() );
sb.append( " GRP ADDR:" + getGroupAddress() );
sb.append( " TGT ADDR: " + getTargetAddress() );
return sb.toString();
}
public String getAffiliationScope()
{
return mMessage.get( LOCAL_GLOBAL_AFFILIATION_FLAG) ? " GLOBAL" : " LOCAL";
}
public Response getResponse()
{
int response = mMessage.getInt( AFFILIATION_RESPONSE );
return Response.fromValue( response );
}
public String getAnnouncementGroupAddress()
{
return mMessage.getHex( ANNOUNCEMENT_GROUP_ADDRESS, 4 );
}
public String getGroupAddress()
{
return mMessage.getHex( GROUP_ADDRESS, 4 );
}
@Override
public String getFromID()
{
return getGroupAddress();
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
@Override
public String getToID()
{
return getTargetAddress();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.fleetsync2;
import message.Message;
import alias.Alias;
import controller.state.AuxChannelState;
import controller.state.ChannelState;
import controller.state.ChannelState.ChangedAttribute;
import controller.state.ChannelState.State;
public class FleetsyncChannelState extends AuxChannelState
{
private String mFleetFrom;
private Alias mFleetFromAlias;
private String mFleetTo;
private Alias mFleetToAlias;
private String mMessage;
private String mMessageType;
private FleetsyncActivitySummary mActivitySummary;
public FleetsyncChannelState( ChannelState parentState )
{
super( parentState );
mActivitySummary =
new FleetsyncActivitySummary( parentState.getAliasList() );
}
@Override
public void reset()
{
setFleetIDFrom( null );
setFleetIDFromAlias( null );
setFleetIDTo( null );
setFleetIDToAlias( null );
setMessage( null );
setMessageType( null );
}
@Override
public void fade()
{
}
@Override
public void receive( Message message )
{
if( message instanceof FleetsyncMessage )
{
mActivitySummary.receive( message );
FleetsyncMessage fleetsync = (FleetsyncMessage)message;
setFleetIDFrom( fleetsync.getFromID() );
setFleetIDFromAlias( fleetsync.getFromIDAlias() );
FleetsyncMessageType type = fleetsync.getMessageType();
if( type != FleetsyncMessageType.ANI )
{
setFleetIDTo( fleetsync.getToID() );
setFleetIDToAlias( fleetsync.getToIDAlias() );
}
setMessageType( type.getLabel() );
switch( type )
{
case GPS:
setMessage( fleetsync.getGPSLocation() );
break;
case STATUS:
StringBuilder sb = new StringBuilder();
sb.append( fleetsync.getStatus() );
Alias status = fleetsync.getStatusAlias();
if( status != null )
{
sb.append( "/" );
sb.append( status.getName() );
}
setMessage( sb.toString() );
break;
default:
break;
}
/* Set the state to CALL on the parent channel state, so that the
* parent state timer can track turning off any updates we apply */
mParentChannelState.setState( State.CALL );
FleetsyncCallEvent fsCallEvent =
FleetsyncCallEvent.getFleetsync2Event( fleetsync );
fsCallEvent.setAliasList( mParentChannelState.getAliasList() );
mParentChannelState.receiveCallEvent( fsCallEvent );
}
}
public String getFleetIDFrom()
{
return mFleetFrom;
}
public void setFleetIDFrom( String from )
{
mFleetFrom = from;
broadcastChange( ChangedAttribute.FROM_TALKGROUP );
}
public Alias getFleetIDFromAlias()
{
return mFleetFromAlias;
}
public void setFleetIDFromAlias( Alias alias )
{
mFleetFromAlias = alias;
broadcastChange( ChangedAttribute.FROM_TALKGROUP_ALIAS );
}
public String getFleetIDTo()
{
return mFleetTo;
}
public void setFleetIDTo( String to )
{
mFleetTo = to;
broadcastChange( ChangedAttribute.TO_TALKGROUP );
}
public Alias getFleetIDToAlias()
{
return mFleetToAlias;
}
public void setFleetIDToAlias( Alias alias )
{
mFleetToAlias = alias;
broadcastChange( ChangedAttribute.TO_TALKGROUP_ALIAS );
}
public String getMessage()
{
return mMessage;
}
public void setMessage( String message )
{
mMessage = message;
broadcastChange( ChangedAttribute.MESSAGE );
}
public String getMessageType()
{
return mMessageType;
}
public void setMessageType( String type )
{
mMessageType = type;
broadcastChange( ChangedAttribute.MESSAGE_TYPE );
}
@Override
public String getActivitySummary()
{
return mActivitySummary.getSummary();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 buffer;
import java.util.ArrayList;
import java.util.Arrays;
public class FloatArrayCircularAveragingBuffer
{
private ArrayList<float[]> mBuffer;
private int mBufferPointer;
private int mBufferSize;
private float[] mAverage;
public FloatArrayCircularAveragingBuffer( int bufferSize )
{
mBufferSize = bufferSize;
mBuffer = new ArrayList<float[]>();
}
/**
* Replaces the oldest float array element in the buffer with this new
* float array element, and then returns the average of the buffer contents
* with the newElement values included in the average array
*/
public float[] get( float[] newElement )
{
/**
* If we've never setup the average array, or the newElements length is
* different than what we've been processing, reset the buffer & averages
*/
if( mAverage == null || mAverage.length != newElement.length )
{
reset( newElement.length );
}
float[] oldElement = mBuffer.get( mBufferPointer );
for( int x = 0; x < newElement.length; x++ )
{
/**
* Change the current average value in each array element by the
* difference of the new element minus the old element, divided
* by the buffer size ... average it
*/
mAverage[ x ] +=
( ( newElement[ x ] - oldElement[ x ] ) / mBufferSize );
}
mBuffer.set( mBufferPointer, newElement );
mBufferPointer++;
if( mBufferPointer >= mBufferSize )
{
mBufferPointer = 0;
}
return mAverage;
}
/**
* Clears buffer and average and fills buffer with zero-valued float arrays
*/
private void reset( int arrayLength )
{
mAverage = new float[ arrayLength ];
Arrays.fill( mAverage, 0.0f );
mBuffer.clear();
mBufferPointer = 0;
float[] emptyArray = new float[ arrayLength ];
Arrays.fill( emptyArray, 0.0f );
for( int x = 0; x < mBufferSize; x++ )
{
mBuffer.add( emptyArray );
}
}
}
<file_sep>package decode.mdc1200;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import message.Message;
import filter.Filter;
import filter.FilterElement;
public class MDCMessageFilter extends Filter<Message>
{
private HashMap<MDCMessageType, FilterElement<MDCMessageType>> mElements =
new HashMap<MDCMessageType, FilterElement<MDCMessageType>>();
public MDCMessageFilter()
{
super( "MDC-1200 Message Filter" );
for( MDCMessageType type: MDCMessageType.values() )
{
if( type != MDCMessageType.UNKNOWN )
{
mElements.put( type, new FilterElement<MDCMessageType>( type ) );
}
}
}
@Override
public boolean passes( Message message )
{
if( mEnabled && canProcess( message ) )
{
MDCMessage mdc = (MDCMessage)message;
if( mElements.containsKey( mdc.getMessageType() ) )
{
return mElements.get( mdc.getMessageType() ).isEnabled();
}
}
return false;
}
@Override
public boolean canProcess( Message message )
{
return message instanceof MDCMessage;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return new ArrayList<FilterElement<?>>( mElements.values() );
}
}
<file_sep>package decode.p25.message.filter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import message.Message;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.message.tsbk.motorola.MotorolaOpcode;
import decode.p25.message.tsbk.vendor.VendorOpcode;
import decode.p25.reference.Opcode;
import decode.p25.reference.Vendor;
import filter.Filter;
import filter.FilterElement;
import filter.FilterSet;
public class TSBKMessageFilterSet extends FilterSet<Message>
{
public TSBKMessageFilterSet()
{
super( "TSBK Trunking Signalling Block" );
addFilter( new StandardOpcodeFilter() );
addFilter( new MotorolaOpcodeFilter() );
addFilter( new VendorOpcodeFilter() );
}
// @Override
// public boolean passes( Message message )
// {
// if( mEnabled && canProcess( message ) )
// {
// TSBKMessage tsbk = (TSBKMessage)message;
//
// switch( tsbk.getVendor() )
// {
// case STANDARD:
// return
// }
// Opcode opcode = tsbk.getOpcode();
//
// return mFilterElements.get( opcode ).isEnabled();
// }
//
// return false;
// }
@Override
public boolean canProcess( Message message )
{
return message instanceof TSBKMessage;
}
public class StandardOpcodeFilter extends Filter<Message>
{
private HashMap<Opcode,FilterElement<Opcode>> mStandardElements =
new HashMap<Opcode,FilterElement<Opcode>>();
public StandardOpcodeFilter()
{
super( "Standard Opcode Filter" );
for( Opcode opcode: Opcode.values() )
{
if( opcode != Opcode.UNKNOWN )
{
mStandardElements.put( opcode,
new FilterElement<Opcode>( opcode ) );
}
}
}
@Override
public boolean passes( Message message )
{
if( mEnabled && canProcess( message ) )
{
Opcode opcode = ((TSBKMessage)message).getOpcode();
if( mStandardElements.containsKey( opcode ) )
{
return mStandardElements.get( opcode ).isEnabled();
}
}
return false;
}
@Override
public boolean canProcess( Message message )
{
return ((TSBKMessage)message).getVendor() == Vendor.STANDARD;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return new ArrayList<FilterElement<?>>( mStandardElements.values() );
}
}
public class MotorolaOpcodeFilter extends Filter<Message>
{
private HashMap<MotorolaOpcode,FilterElement<MotorolaOpcode>> mMotorolaElements =
new HashMap<MotorolaOpcode,FilterElement<MotorolaOpcode>>();
public MotorolaOpcodeFilter()
{
super( "Motorola Opcode Filter" );
for( MotorolaOpcode opcode: MotorolaOpcode.values() )
{
if( opcode != MotorolaOpcode.UNKNOWN )
{
mMotorolaElements.put( opcode,
new FilterElement<MotorolaOpcode>( opcode ) );
}
}
}
@Override
public boolean passes( Message message )
{
if( mEnabled && canProcess( message ) )
{
MotorolaOpcode opcode = ((TSBKMessage)message).getMotorolaOpcode();
if( mMotorolaElements.containsKey( opcode ) )
{
return mMotorolaElements.get( opcode ).isEnabled();
}
}
return false;
}
@Override
public boolean canProcess( Message message )
{
return ((TSBKMessage)message).getVendor() == Vendor.MOTOROLA;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return new ArrayList<FilterElement<?>>( mMotorolaElements.values() );
}
}
public class VendorOpcodeFilter extends Filter<Message>
{
private HashMap<VendorOpcode,FilterElement<VendorOpcode>> mVendorElements =
new HashMap<VendorOpcode,FilterElement<VendorOpcode>>();
public VendorOpcodeFilter()
{
super( "Vendor Opcode Filter" );
for( VendorOpcode opcode: VendorOpcode.values() )
{
if( opcode != VendorOpcode.UNKNOWN )
{
mVendorElements.put( opcode,
new FilterElement<VendorOpcode>( opcode ) );
}
}
}
@Override
public boolean passes( Message message )
{
if( mEnabled && canProcess( message ) )
{
MotorolaOpcode opcode = ((TSBKMessage)message).getMotorolaOpcode();
if( mVendorElements.containsKey( opcode ) )
{
return mVendorElements.get( opcode ).isEnabled();
}
}
return false;
}
@Override
public boolean canProcess( Message message )
{
Vendor vendor = ((TSBKMessage)message).getVendor();
return vendor != Vendor.STANDARD && vendor != Vendor.MOTOROLA;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return new ArrayList<FilterElement<?>>( mVendorElements.values() );
}
}
}
<file_sep>package decode.p25.reference;
public enum Vendor
{
STANDARD( "STANDARD", "STANDARD", 0),
STANDARD_V1( "STANDARD", "STANDARD_01", 1),
V2( "VENDOR02", "V_02", 2),
V3( "VENDOR03", "V_03", 3),
V4( "VENDOR04", "V_04", 4),
V5( "VENDOR05", "V_05", 5),
V6( "VENDOR06", "V_06", 6),
V7( "VENDOR07", "V_07", 7),
V8( "VENDOR08", "V_08", 8),
V9( "VENDOR09", "V_09", 9),
V10( "VENDOR0A", "V_0A", 10),
V11( "VENDOR0B", "V_0B", 11),
V12( "VENDOR0C", "V_0C", 12),
V13( "VENDOR0D", "V_0D", 13),
V14( "VENDOR0E", "V_0E", 14),
V15( "VENDOR0F", "V_0F", 15),
RELM( "RELM BK ", "RELM/BK RADIO", 16),
V17( "VENDOR11", "V_11", 17),
V18( "VENDOR12", "V_12", 18),
V19( "VENDOR13", "V_13", 19),
V20( "VENDOR14", "V_14", 20),
V21( "VENDOR15", "V_15", 21),
V22( "VENDOR16", "V_16", 22),
V23( "VENDOR17", "V_17", 23),
V24( "VENDOR18", "V_18", 24),
V25( "VENDOR19", "V_19", 25),
V26( "VENDOR1A", "V_1A", 26),
V27( "VENDOR1B", "V_1B", 27),
V28( "VENDOR1C", "V_1C", 28),
V29( "VENDOR1D", "V_1D", 29),
V30( "VENDOR1E", "V_1E", 30),
V31( "VENDOR1F", "V_1F", 31),
CYCOMM( "CYCOMM ", "CYCOMM", 32),
V33( "VENDOR21", "V_21", 33),
V34( "VENDOR22", "V_22", 34),
V35( "VENDOR23", "V_23", 35),
V36( "VENDOR24", "V_24", 36),
V37( "VENDOR25", "V_25", 37),
V38( "VENDOR26", "V_26", 38),
V39( "VENDOR27", "V_27", 39),
EFRATOM( "EFRATOM ", "EFRATOM", 40),
V41( "VENDOR29", "V_29", 41),
V42( "VENDOR2A", "V_2A", 42),
V43( "VENDOR2B", "V_2B", 43),
V44( "VENDOR2C", "V_2C", 44),
V45( "VENDOR2D", "V_2D", 45),
V46( "VENDOR2E", "V_2E", 46),
V47( "VENDOR2F", "V_2F", 47),
ERICSSON( "ERICSSON", "ERICSSON", 48),
V49( "VENDOR31", "V_31", 49),
V50( "VENDOR32", "V_32", 50),
V51( "VENDOR33", "V_33", 51),
V52( "VENDOR34", "V_34", 52),
V53( "VENDOR35", "V_35", 53),
V54( "VENDOR36", "V_36", 54),
V55( "VENDOR37", "V_37", 55),
DATRON( "DATRON ", "DATRON", 56),
V57( "VENDOR39", "V_39", 57),
V58( "VENDOR3A", "V_3A", 58),
V59( "VENDOR3B", "V_3B", 59),
V60( "VENDOR3C", "V_3C", 60),
V61( "VENDOR3D", "V_3D", 61),
V62( "VENDOR3E", "V_3E", 62),
V63( "VENDOR3F", "V_3F", 63),
ICOM( "ICOM ", "ICOM", 64),
V65( "VENDOR41", "V_41", 65),
V66( "VENDOR42", "V_42", 66),
V67( "VENDOR43", "V_43", 67),
V68( "VENDOR44", "V_44", 68),
V69( "VENDOR45", "V_45", 69),
V70( "VENDOR46", "V_46", 70),
V71( "VENDOR47", "V_47", 71),
GARMIN( "GARMIN ", "GARMIN", 72),
V73( "VENDOR49", "V_49", 73),
V74( "VENDOR4A", "V_4A", 74),
V75( "VENDOR4B", "V_4B", 75),
V76( "VENDOR4C", "V_4C", 76),
V77( "VENDOR4D", "V_4D", 77),
V78( "VENDOR4E", "V_4E", 78),
V79( "VENDOR4F", "V_4F", 79),
GTE( "GTE ", "GTE", 80),
V81( "VENDOR51", "V_51", 81),
V82( "VENDOR52", "V_52", 82),
V83( "VENDOR53", "V_53", 83),
V84( "VENDOR54", "V_54", 84),
IFR_SYSTEMS( "IFR SYST", "IFR SYSTEMS", 85),
V86( "VENDOR54", "V_56", 86),
V87( "VENDOR57", "V_57", 87),
V88( "VENDOR58", "V_58", 88),
V89( "VENDOR59", "V_59", 89),
V90( "VENDOR5A", "V_5A", 90),
V91( "VENDOR5B", "V_5B", 91),
V92( "VENDOR5C", "V_5C", 92),
V93( "VENDOR5D", "V_5D", 93),
V94( "VENDOR5E", "V_5E", 94),
V95( "VENDOR5F", "V_5F", 95),
GEC_MARCONI( "MARCONI ", "GEC-MARCONI", 96),
V97( "VENDOR61", "V_61", 97),
V98( "VENDOR62", "V_62", 98),
V99( "VENDOR63", "V_63", 99),
V100( "VENDOR64", "V_64", 100),
V101( "VENDOR65", "V_65", 101),
V102( "VENDOR66", "V_66", 102),
V103( "VENDOR67", "V_67", 103),
KENWOOD( "KENWOOD ", "KENWOOD", 104),
V105( "VENDOR69", "V_69", 105),
V106( "VENDOR6A", "V_6A", 106),
V107( "VENDOR6B", "V_6B", 107),
V108( "VENDOR6C", "V_6C", 108),
V109( "VENDOR6D", "V_6D", 109),
V110( "VENDOR6E", "V_6E", 110),
V111( "VENDOR6F", "V_6F", 111),
GLENAYRE( "GLENAYRE", "GLENAYRE ELECTRONICS", 112),
V113( "VENDOR71", "V_71", 113),
V114( "VENDOR72", "V_72", 114),
V115( "VENDOR73", "V_73", 115),
JAPAN_RADIO( "JAPRADCO", "JAPAN RADIO CO", 116),
V117( "VENDOR75", "V_75", 117),
V118( "VENDOR76", "V_76", 118),
V119( "VENDOR77", "V_77", 119),
KOKUSAI( "KOKUSAI ", "KOKUSAI", 120),
V121( "VENDOR79", "V_79", 121),
V122( "VENDOR7A", "V_7A", 122),
V123( "VENDOR7B", "V_7B", 123),
MAXON( "MAXON ", "MAXON", 124),
V125( "VENDOR7D", "V_7D", 125),
V126( "VENDOR7E", "V_7E", 126),
V127( "VENDOR7F", "V_7F", 127),
MIDLAND( "MIDLAND ", "MIDLAND", 128),
V129( "VENDOR81", "V_81", 129),
V130( "VENDOR82", "V_82", 130),
V131( "VENDOR83", "V_83", 131),
V132( "VENDOR84", "V_84", 132),
V133( "VENDOR85", "V_85", 133),
DANIELS( "DANIELS ", "DANIELS ELECTRONICS", 134),
V135( "VENDOR87", "V_87", 135),
V136( "VENDOR88", "V_88", 136),
V137( "VENDOR89", "V_89", 137),
V138( "VENDOR8A", "V_8A", 138),
V139( "VENDOR8B", "V_8B", 139),
V140( "VENDOR8C", "V_8C", 140),
V141( "VENDOR8D", "V_8D", 141),
V142( "VENDOR8E", "V_8E", 142),
V143( "VENDOR8F", "V_8F", 143),
MOTOROLA( "MOTOROLA", "MOTOROLA", 144),
V145( "VENDOR91", "V_91", 145),
V146( "VENDOR92", "V_92", 146),
V147( "VENDOR93", "V_93", 147),
V148( "VENDOR94", "V_94", 148),
V149( "VENDOR95", "V_95", 149),
V150( "VENDOR96", "V_96", 150),
V151( "VENDOR97", "V_97", 151),
V152( "VENDOR98", "V_98", 152),
V153( "VENDOR99", "V_99", 153),
V154( "VENDOR9A", "V_9A", 154),
V155( "VENDOR9B", "V_9B", 155),
V156( "VENDOR9C", "V_9C", 156),
V157( "VENDOR9D", "V_9D", 157),
V158( "VENDOR9E", "V_9E", 158),
V159( "VENDOR9F", "V_9F", 159),
THALES( "THALES ", "THALES", 160),
V161( "VENDORA1", "V_A1", 161),
V162( "VENDORA2", "V_A2", 162),
V163( "VENDORA3", "V_A3", 163),
MACOM( "M/A-COM ", "M/A-COM", 164),
V165( "VENDORA5", "V_A5", 165),
V166( "VENDORA6", "V_A6", 166),
V167( "VENDORA7", "V_A7", 167),
V168( "VENDORA8", "V_A8", 168),
V169( "VENDORA9", "V_A9", 169),
V170( "VENDORAA", "V_AA", 170),
V171( "VENDORAB", "V_AB", 171),
V172( "VENDORAC", "V_AC", 172),
V173( "VENDORAD", "V_AD", 173),
V174( "VENDORAE", "V_AE", 174),
V175( "VENDORAF", "V_AF", 175),
RATHEON( "RATHEON ", "RATHEON", 176),
V177( "VENDORB1", "V_B1", 177),
V178( "VENDORB2", "V_B2", 178),
V179( "VENDORB3", "V_B3", 179),
V180( "VENDORB4", "V_B4", 180),
V181( "VENDORB5", "V_B5", 181),
V182( "VENDORB6", "V_B6", 182),
V183( "VENDORB7", "V_B7", 183),
V184( "VENDORB8", "V_B8", 184),
V185( "VENDORB9", "V_B9", 185),
V186( "VENDORBA", "V_BA", 186),
V187( "VENDORBB", "V_BB", 187),
V188( "VENDORBC", "V_BC", 188),
V189( "VENDORBD", "V_BD", 189),
V190( "VENDORBE", "V_BE", 190),
V191( "VENDORBF", "V_BF", 191),
SEA( "SEA ", "SEA", 192),
V193( "VENDORC1", "V_C1", 193),
V194( "VENDORC2", "V_C2", 194),
V195( "VENDORC3", "V_C3", 195),
V196( "VENDORC4", "V_C4", 196),
V197( "VENDORC5", "V_C5", 197),
V198( "VENDORC6", "V_C6", 198),
V199( "VENDORC7", "V_C7", 199),
SECURICOR( "SECURICO", "SECURICOR", 200),
V201( "VENDORC9", "V_C9", 201),
V202( "VENDORCA", "V_CA", 202),
V203( "VENDORCB", "V_CB", 203),
V204( "VENDORCC", "V_CC", 204),
V205( "VENDORCD", "V_CD", 205),
V206( "VENDORCE", "V_CE", 206),
V207( "VENDORCF", "V_CF", 207),
ADI( "ADI ", "ADI", 208),
V209( "VENDORD1", "V_D1", 209),
V210( "VENDORD2", "V_D2", 210),
V211( "VENDORD3", "V_D3", 211),
V212( "VENDORD4", "V_D4", 212),
V213( "VENDORD5", "V_D5", 213),
V214( "VENDORD6", "V_D6", 214),
V215( "VENDORD7", "V_D7", 215),
TAIT( "TAIT ", "TAIT", 216),
V217( "VENDORD9", "V_D9", 217),
V218( "VENDORDA", "V_DA", 218),
V219( "VENDORDB", "V_DB", 219),
V220( "VENDORDC", "V_DC", 220),
V221( "VENDORDD", "V_DD", 221),
V222( "VENDORDE", "V_DE", 222),
V223( "VENDORDF", "V_DF", 223),
TELETEC( "TELETEC ", "TELETEC", 224),
V225( "VENDORE1", "V_E1", 225),
V226( "VENDORE2", "V_E2", 226),
V227( "VENDORE3", "V_E3", 227),
V228( "VENDORE4", "V_E4", 228),
V229( "VENDORE5", "V_E5", 229),
V230( "VENDORE6", "V_E6", 230),
V231( "VENDORE7", "V_E7", 231),
V232( "VENDORE8", "V_E8", 232),
V233( "VENDORE9", "V_E9", 233),
V234( "VENDOREA", "V_EA", 234),
V235( "VENDOREB", "V_EB", 235),
V236( "VENDOREC", "V_EC", 236),
V237( "VENDORED", "V_ED", 237),
V238( "VENDOREE", "V_EE", 238),
V239( "VENDOREF", "V_EF", 239),
TRANSCRYPT( "TRANSCRPT", "TRANSCRYPT", 240),
V241( "VENDORF1", "V_F1", 241),
V242( "VENDORF2", "V_F2", 242),
V243( "VENDORF3", "V_F3", 243),
V244( "VENDORF4", "V_F4", 244),
V245( "VENDORF5", "V_F5", 245),
V246( "VENDORF6", "V_F6", 246),
V247( "VENDORF7", "V_F7", 247),
V248( "VENDORF8", "V_F8", 248),
V249( "VENDORF9", "V_F9", 249),
V250( "VENDORFA", "V_FA", 250),
V251( "VENDORFB", "V_FB", 251),
V252( "VENDORFC", "V_FC", 252),
V253( "VENDORFD", "V_FD", 253),
V254( "VENDORFE", "V_FE", 254),
V255( "VENDORFF", "V_FF", 255),
VUNK( "UNKNOWN ", "UNKN", -1 );
private String mLabel;
private String mDescription;
private int mValue;
private Vendor( String label, String description, int value )
{
mLabel = label;
mDescription = description;
mValue = value;
}
public String getLabel()
{
return mLabel;
}
public String getDescription()
{
return mDescription;
}
public int getValue()
{
return mValue;
}
public static Vendor fromValue( int value )
{
if( 0 <= value && value <= 255 )
{
return values()[ value ];
}
return VUNK;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 alias;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import javax.xml.bind.annotation.XmlAttribute;
import alias.action.AliasAction;
import audio.inverted.AudioType;
public class Alias
{
private String mName;
private int mColor;
private String mIconName;
private ArrayList<AliasID> mAliasIDs = new ArrayList<AliasID>();
private List<AliasAction> mAliasActions = new ArrayList<AliasAction>();
public Alias()
{
}
public String toString()
{
return "Alias: " + mName;
}
@XmlAttribute
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
@XmlAttribute
public int getColor()
{
return mColor;
}
public void setColor( int color )
{
mColor = color;
}
public Color getMapColor()
{
return new Color( mColor );
}
@XmlAttribute
public String getIconName()
{
return mIconName;
}
public void setIconName( String iconName )
{
mIconName = iconName;
}
public ArrayList<AliasID> getId()
{
return mAliasIDs;
}
public void setId( ArrayList<AliasID> id )
{
mAliasIDs = id;
}
public void addAliasID( AliasID id )
{
mAliasIDs.add( id );
}
public void removeAliasID( AliasID id )
{
mAliasIDs.remove( id );
}
public List<AliasAction> getAction()
{
return mAliasActions;
}
public void setAction( List<AliasAction> actions )
{
mAliasActions = actions;
}
public void addAliasAction( AliasAction action )
{
mAliasActions.add( action );
}
public void removeAliasAction( AliasAction action )
{
mAliasActions.remove( action );
}
public boolean hasActions()
{
return !mAliasActions.isEmpty();
}
public boolean hasAudioType()
{
for( AliasID id: mAliasIDs )
{
if( id.hasAudioType() )
{
return true;
}
}
return false;
}
public AudioType getAudioType()
{
for( AliasID id: mAliasIDs )
{
if( id.hasAudioType() )
{
return id.getAudioType();
}
}
return AudioType.NORMAL;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 dsp.nbfm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import sample.complex.ComplexSample;
import sample.real.RealSampleBroadcaster;
import sample.real.RealSampleListener;
import dsp.filter.ComplexFIRFilter;
import dsp.filter.FilterFactory;
import dsp.filter.FloatFIRFilter;
import dsp.filter.Window.WindowType;
public class FilteringNBFMDemodulator implements Listener<ComplexSample>
{
private final static Logger mLog =
LoggerFactory.getLogger( FilteringNBFMDemodulator.class );
private RealSampleBroadcaster mBroadcaster = new RealSampleBroadcaster();
private ComplexFIRFilter mIQFilter;
private FloatFIRFilter mAudioFilter;
private FMDiscriminator mDiscriminator;
public FilteringNBFMDemodulator( double[] iqFilter, double iqGain,
double[] audioFilter, double audioGain )
{
mIQFilter = new ComplexFIRFilter( iqFilter, iqGain );
mAudioFilter = new FloatFIRFilter( audioFilter, audioGain );
mDiscriminator = new FMDiscriminator( 1 );
mIQFilter.setListener( mDiscriminator );
mDiscriminator.setListener( mAudioFilter );
mAudioFilter.setListener( mBroadcaster );
}
/**
* Implements a quadrature narrow-band demodulator that produces float
* valued demodulated, audio filtered output samples.
*/
public FilteringNBFMDemodulator()
{
this( FilterFactory.getLowPass( 48000, 5000, 7000, 48, WindowType.HAMMING, true ),
1.0002,
FilterFactory.getLowPass( 48000, 3000, 6000, 48, WindowType.HAMMING, true ),
2 );
}
/**
* Receive method for complex samples that are fed into this class to be
* processed
*/
@Override
public void receive( ComplexSample quadratureSample )
{
mIQFilter.receive( quadratureSample );
}
/**
* Adds a listener to receive demodulated samples
*/
public void addListener( RealSampleListener listener )
{
mBroadcaster.addListener( listener );
}
/**
* Removes a listener from receiving demodulated samples
*/
public void removeListener( RealSampleListener listener )
{
mBroadcaster.removeListener( listener );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 alias;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import map.MapIcon;
import alias.action.AliasAction;
import alias.action.beep.BeepAction;
import alias.action.beep.BeepActionNode;
import alias.action.clip.ClipAction;
import alias.action.clip.ClipActionNode;
import alias.action.script.ScriptAction;
import alias.action.script.ScriptActionNode;
import alias.esn.ESNNode;
import alias.esn.Esn;
import alias.fleetsync.FleetsyncID;
import alias.fleetsync.FleetsyncIDNode;
import alias.fleetsync.StatusID;
import alias.fleetsync.StatusIDNode;
import alias.mdc.MDC1200ID;
import alias.mdc.MDC1200IDNode;
import alias.mobileID.MINNode;
import alias.mobileID.Min;
import alias.mpt1327.MPT1327ID;
import alias.mpt1327.MPT1327IDNode;
import alias.siteID.SiteID;
import alias.siteID.SiteIDNode;
import alias.talkgroup.TalkgroupID;
import alias.talkgroup.TalkgroupIDNode;
import alias.uniqueID.UniqueID;
import alias.uniqueID.UniqueIDNode;
import controller.ConfigurableNode;
public class AliasNode extends ConfigurableNode
{
private static final long serialVersionUID = 1L;
public AliasNode( Alias alias )
{
super( alias );
}
@Override
public JPanel getEditor()
{
return new AliasEditor( this, getModel().getResourceManager() );
}
public Alias getAlias()
{
return (Alias)getUserObject();
}
public String getIconPath()
{
String icon = getAlias().getIconName();
MapIcon mapIcon = getModel().getResourceManager()
.getSettingsManager().getMapIcon( icon );
if( mapIcon != null )
{
return mapIcon.getPath();
}
else
{
return null;
}
}
public void init()
{
for( AliasID aliasID: getAlias().getId() )
{
if( aliasID instanceof Esn )
{
getModel().addNode( new ESNNode( (Esn)aliasID ),
AliasNode.this, getChildCount() );
}
else if( aliasID instanceof FleetsyncID )
{
getModel().addNode( new FleetsyncIDNode( (FleetsyncID)aliasID ),
AliasNode.this, getChildCount() );
}
else if( aliasID instanceof MDC1200ID )
{
getModel().addNode( new MDC1200IDNode( (MDC1200ID)aliasID ),
AliasNode.this, getChildCount() );
}
else if( aliasID instanceof Min )
{
getModel().addNode( new MINNode( (Min)aliasID ),
AliasNode.this, getChildCount() );
}
else if( aliasID instanceof MPT1327ID )
{
getModel().addNode( new MPT1327IDNode( (MPT1327ID)aliasID ),
AliasNode.this, getChildCount() );
}
else if( aliasID instanceof SiteID )
{
getModel().addNode( new SiteIDNode( (SiteID)aliasID ),
AliasNode.this, getChildCount() );
}
else if( aliasID instanceof StatusID )
{
getModel().addNode( new StatusIDNode( (StatusID)aliasID ),
AliasNode.this, getChildCount() );
}
else if( aliasID instanceof TalkgroupID )
{
getModel().addNode( new TalkgroupIDNode( (TalkgroupID)aliasID ),
AliasNode.this, getChildCount() );
}
else if( aliasID instanceof UniqueID )
{
getModel().addNode( new UniqueIDNode( (UniqueID)aliasID ),
AliasNode.this, getChildCount() );
}
}
for( AliasAction action: getAlias().getAction() )
{
if( action instanceof BeepAction )
{
getModel().addNode( new BeepActionNode( (BeepAction)action ),
AliasNode.this, getChildCount() );
}
else if( action instanceof ClipAction )
{
getModel().addNode( new ClipActionNode( (ClipAction)action ),
AliasNode.this, getChildCount() );
}
else if( action instanceof ScriptAction )
{
getModel().addNode( new ScriptActionNode( (ScriptAction)action ),
AliasNode.this, getChildCount() );
}
}
sort();
}
public String toString()
{
return getAlias().getName() + " [" + this.getChildCount() + "]";
}
public JPopupMenu getContextMenu()
{
JPopupMenu retVal = new JPopupMenu();
JMenu addIDMenu = new JMenu( "Add ID" );
JMenuItem addESNItem = new JMenuItem( "ESN" );
addESNItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
Esn esn = new Esn();
getAlias().addAliasID( esn );
ESNNode node = new ESNNode( esn );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addESNItem );
JMenuItem addFleetsyncItem = new JMenuItem( "Fleetsync" );
addFleetsyncItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
FleetsyncID fs = new FleetsyncID();
getAlias().addAliasID( fs );
FleetsyncIDNode node = new FleetsyncIDNode( fs );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addFleetsyncItem );
JMenuItem addMDCItem = new JMenuItem( "MDC-1200" );
addMDCItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
MDC1200ID mdc = new MDC1200ID();
getAlias().addAliasID( mdc );
MDC1200IDNode node = new MDC1200IDNode( mdc );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addMDCItem );
JMenuItem addMINItem = new JMenuItem( "MIN" );
addMINItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
Min min = new Min();
getAlias().addAliasID( min );
MINNode node = new MINNode( min );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addMINItem );
JMenuItem addMPTItem = new JMenuItem( "MPT-1327" );
addMPTItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
MPT1327ID mpt = new MPT1327ID();
getAlias().addAliasID( mpt );
MPT1327IDNode node = new MPT1327IDNode( mpt );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addMPTItem );
JMenuItem addSiteItem = new JMenuItem( "Site" );
addSiteItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
SiteID siteID = new SiteID();
getAlias().addAliasID( siteID );
SiteIDNode node = new SiteIDNode( siteID );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addSiteItem );
JMenuItem addStatusItem = new JMenuItem( "Status" );
addStatusItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
StatusID statusID = new StatusID();
getAlias().addAliasID( statusID );
StatusIDNode node = new StatusIDNode( statusID );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addStatusItem );
JMenuItem addTalkgroupItem = new JMenuItem( "Talkgroup" );
addTalkgroupItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
TalkgroupID tg = new TalkgroupID();
getAlias().addAliasID( tg );
TalkgroupIDNode node = new TalkgroupIDNode( tg );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addTalkgroupItem );
JMenuItem addUniqueIDItem = new JMenuItem( "Unique ID" );
addUniqueIDItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
UniqueID uid = new UniqueID();
getAlias().addAliasID( uid );
UniqueIDNode node = new UniqueIDNode( uid );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addIDMenu.add( addUniqueIDItem );
retVal.add( addIDMenu );
JMenu addActionMenu = new JMenu( "Add Action" );
JMenuItem addClipItem = new JMenuItem( "Audio Clip" );
addClipItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
ClipAction clipAction = new ClipAction();
getAlias().addAliasAction( clipAction );
ClipActionNode node = new ClipActionNode( clipAction );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addActionMenu.add( addClipItem );
JMenuItem addBeepItem = new JMenuItem( "Beep" );
addBeepItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
BeepAction beepAction = new BeepAction();
getAlias().addAliasAction( beepAction );
BeepActionNode node = new BeepActionNode( beepAction );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addActionMenu.add( addBeepItem );
JMenuItem addScriptItem = new JMenuItem( "Script" );
addScriptItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
ScriptAction scriptAction = new ScriptAction();
getAlias().addAliasAction( scriptAction );
ScriptActionNode node = new ScriptActionNode( scriptAction );
getModel().addNode( node,
AliasNode.this,
AliasNode.this.getChildCount() );
node.show();
}
} );
addActionMenu.add( addScriptItem );
retVal.add( addActionMenu );
retVal.addSeparator();
JMenuItem deleteItem = new JMenuItem( "Delete" );
deleteItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
int n = JOptionPane.showConfirmDialog( getModel().getTree(),
"Are you sure you want to permanently delete this node?" );
if( n == JOptionPane.YES_OPTION )
{
GroupNode parent = (GroupNode)getParent();
parent.getGroup().removeAlias( getAlias() );
save();
getModel().removeNodeFromParent( AliasNode.this );
}
}
} );
retVal.add( deleteItem );
return retVal;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.tait;
import message.Message;
import sample.Listener;
import alias.AliasList;
import controller.activity.ActivitySummaryProvider;
public class Tait1200ActivitySummary implements ActivitySummaryProvider,
Listener<Message>
{
private AliasList mAliasList;
public Tait1200ActivitySummary( AliasList list )
{
mAliasList = list;
}
public void dispose()
{
}
@Override
public void receive( Message message )
{
if( message instanceof Tait1200GPSMessage )
{
Tait1200GPSMessage tait = ((Tait1200GPSMessage)message);
//Do something here in the future
}
}
@Override
public String getSummary()
{
StringBuilder sb = new StringBuilder();
sb.append( "=============================\n" );
sb.append( "Decoder:\tTait-1200I\n\n" );
return sb.toString();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source;
import source.mixer.MixerManager;
import controller.ResourceManager;
import controller.channel.ProcessingChain;
public class SourceManager {
/**
* NOTE: each source will auto-start once a listener registers on it to
* receive samples and should auto-stop once a listener de-registers
*
* Each channel object will handle the starting and stopping of each channel
* processing chain.
*
* Source Manager will reach out to the MixerManager or the TunerManager
* to get source objects to pass off to the channel object, as requested.
*/
private ResourceManager mResourceManager;
public SourceManager( ResourceManager resourceManager )
{
mResourceManager = resourceManager;
}
public Source getSource( ProcessingChain channel ) throws SourceException
{
Source retVal = null;
if( channel != null )
{
switch( channel.getChannel()
.getSourceConfiguration().getSourceType() )
{
case MIXER:
retVal = MixerManager.getInstance().getSource( channel );
break;
case TUNER:
retVal = mResourceManager.getTunerManager().getSource( channel );
break;
case RECORDING:
retVal = mResourceManager.getRecordingSourceManager()
.getSource( channel );
case NONE:
default:
break;
}
}
return retVal;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.mdc1200;
import java.util.Iterator;
import java.util.TreeSet;
import message.Message;
import sample.Listener;
import alias.Alias;
import alias.AliasList;
import controller.activity.ActivitySummaryProvider;
public class MDCActivitySummary implements ActivitySummaryProvider,
Listener<Message>
{
private AliasList mAliasList;
private TreeSet<String> mIdents = new TreeSet<String>();
private TreeSet<String> mEmergencyIdents = new TreeSet<String>();
/**
* Compiles a summary of active talkgroups, unique radio ids encountered
* in the decoded messages. Talkgroups have to be heard a minimum of twice
* to be considered valid ... in order to weed out the invalid ones.
*
* Returns a textual summary of the activity
*/
public MDCActivitySummary( AliasList list )
{
mAliasList = list;
}
@Override
public void receive( Message message )
{
if( message instanceof MDCMessage )
{
MDCMessage mdc = ((MDCMessage)message);
mIdents.add( mdc.getUnitID() );
if( mdc.isEmergency() )
{
mEmergencyIdents.add( mdc.getUnitID() );
}
}
}
@Override
public String getSummary()
{
StringBuilder sb = new StringBuilder();
sb.append( "=============================\n" );
sb.append( "Decoder:\tMDC-1200\n\n" );
sb.append( "MDC-1200 Idents\n" );
if( mIdents.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<String> it = mIdents.iterator();
while( it.hasNext() )
{
String ident = it.next();
sb.append( " " );
sb.append( ident );
sb.append( " " );
Alias alias = mAliasList.getMDC1200Alias( ident );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
sb.append( "MDC-1200 Emergency Idents\n" );
if( mEmergencyIdents.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<String> it = mEmergencyIdents.iterator();
while( it.hasNext() )
{
String ident = it.next();
sb.append( " " );
sb.append( ident );
sb.append( " " );
Alias alias = mAliasList.getMDC1200Alias( ident );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
return sb.toString();
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class AdjacentStatusBroadcast extends TSBKMessage implements IdentifierReceiver
{
public static final int[] LOCATION_REGISTRATION_AREA = { 80,81,82,83,84,85,
86,87 };
public static final int CONVENTIONAL_CHANNEL_FLAG = 88;
public static final int SITE_FAILURE_CONDITION_FLAG = 89;
public static final int VALID_FLAG = 90;
public static final int ACTIVE_NETWORK_CONNECTION_FLAG = 91;
public static final int[] SYSTEM_ID = { 92,93,94,95,96,97,98,99,100,101,
102,103 };
public static final int[] RFSS_ID = { 104,105,106,107,108,109,110,111 };
public static final int[] SITE_ID = { 112,113,114,115,116,117,118,119 };
public static final int[] IDENTIFIER = { 120,121,122,123 };
public static final int[] CHANNEL = { 124,125,126,127,128,129,130,131,132,
133,134,135 };
public static final int[] SYSTEM_SERVICE_CLASS = { 136,137,138,139,140,141,
142,143 };
private IBandIdentifier mIdentifierUpdate;
public AdjacentStatusBroadcast( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.ADJACENT_STATUS_BROADCAST.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " LRA:" + getLocationRegistrationArea() );
sb.append( " SYS:" + getSystemID() );
sb.append( " SITE:" + getRFSS() + "-" + getSiteID() );
sb.append( " CHAN:" + getIdentifier() + "-" + getChannel() );
sb.append( " DN:" + getDownlinkFrequency() );
sb.append( " UP:" + getUplinkFrequency() );
if( isConventionalChannel() )
{
sb.append( " CONVENTIONAL" );
}
if( isSiteFailureCondition() )
{
sb.append( " FAILURE-CONDITION" );
}
if( isValidSiteInformation() )
{
sb.append( " VALID-INFO" );
}
if( hasActiveNetworkConnection() )
{
sb.append( " ACTIVE-NETWORK-CONN" );
}
sb.append( SystemService.toString( getSystemServiceClass() ) );
return sb.toString();
}
public String getLocationRegistrationArea()
{
return mMessage.getHex( LOCATION_REGISTRATION_AREA, 2 );
}
public boolean isConventionalChannel()
{
return mMessage.get( CONVENTIONAL_CHANNEL_FLAG );
}
public boolean isSiteFailureCondition()
{
return mMessage.get( SITE_FAILURE_CONDITION_FLAG );
}
public boolean isValidSiteInformation()
{
return mMessage.get( VALID_FLAG );
}
public boolean hasActiveNetworkConnection()
{
return mMessage.get( ACTIVE_NETWORK_CONNECTION_FLAG );
}
public String getUniqueID()
{
StringBuilder sb = new StringBuilder();
sb.append( getSystemID() );
sb.append( ":" );
sb.append( getRFSS() );
sb.append( ":" );
sb.append( getSiteID() );
return sb.toString();
}
public String getSystemID()
{
return mMessage.getHex( SYSTEM_ID, 3 );
}
public String getRFSS()
{
return mMessage.getHex( RFSS_ID, 2 );
}
public String getSiteID()
{
return mMessage.getHex( SITE_ID, 2 );
}
public int getChannel()
{
return mMessage.getInt( CHANNEL );
}
public int getIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
public int getSystemServiceClass()
{
return mMessage.getInt( SYSTEM_SERVICE_CLASS );
}
public long getDownlinkFrequency()
{
return calculateDownlink( mIdentifierUpdate, getChannel() );
}
public long getUplinkFrequency()
{
return calculateUplink( mIdentifierUpdate, getChannel() );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
/* we're only expecting 1 identifier, so use whatever is received */
mIdentifierUpdate = message;
}
public int[] getIdentifiers()
{
int[] idens = new int[ 1 ];
idens[ 0 ] = getIdentifier();
return idens;
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.tsbk.osp.control.SystemService;
import decode.p25.reference.LinkControlOpcode;
import decode.p25.reference.Service;
public class AdjacentSiteStatusBroadcast extends TDULinkControlMessage
implements IdentifierReceiver
{
private final static Logger mLog =
LoggerFactory.getLogger( AdjacentSiteStatusBroadcast.class );
public static final int[] LRA = { 72,73,74,75,88,89,90,91 };
public static final int[] SYSTEM_ID = { 96,97,98,99,112,113,114,115,
116,117,118,119 };
public static final int[] RFSS_ID = { 120,121,122,123,136,137,138,139 };
public static final int[] SITE_ID = { 140,141,142,143,144,145,146,147 };
public static final int[] IDENTIFIER = { 160,161,162,163 };
public static final int[] CHANNEL = { 164,165,166,167,168,169,170,
171,184,185,186,187 };
public static final int[] SYSTEM_SERVICE_CLASS = { 188,189,190,191,192,193,
194,195 };
private IBandIdentifier mIdentifierUpdate;
public AdjacentSiteStatusBroadcast( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.ADJACENT_SITE_STATUS_BROADCAST.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " LRA:" + getLocationRegistrationArea() );
sb.append( " SYS:" + getSystemID() );
sb.append( " SITE:" + getRFSubsystemID() + "-" + getSiteID() );
sb.append( " CHAN:" + getChannel() );
sb.append( " " + Service.getServices( getSystemServiceClass() ).toString() );
return sb.toString();
}
public String getLocationRegistrationArea()
{
return mMessage.getHex( LRA, 2 );
}
public String getSystemID()
{
return mMessage.getHex( SYSTEM_ID, 3 );
}
public String getRFSubsystemID()
{
return mMessage.getHex( RFSS_ID, 2 );
}
public String getSiteID()
{
return mMessage.getHex( SITE_ID, 2 );
}
public int getIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
public String getChannel()
{
return getIdentifier() + "-" + getChannelNumber();
}
public int getChannelNumber()
{
return mMessage.getInt( CHANNEL );
}
public int getSystemServiceClass()
{
return mMessage.getInt( SYSTEM_SERVICE_CLASS );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
mIdentifierUpdate = message;
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 1 ];
identifiers[ 0 ] = getIdentifier();
return identifiers;
}
public long getDownlinkFrequency()
{
return calculateDownlink( mIdentifierUpdate, getChannelNumber() );
}
public long getUplinkFrequencyB()
{
return calculateUplink( mIdentifierUpdate, getChannelNumber() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.hackrf;
import gui.control.JFrequencyControl;
import java.awt.Color;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.usb.UsbException;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.SourceException;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.FrequencyChangeListener;
import source.tuner.frequency.FrequencyChangeEvent.Attribute;
import source.tuner.hackrf.HackRFTunerController.BoardID;
import com.jidesoft.swing.JideTabbedPane;
import controller.ResourceManager;
public class HackRFTunerEditorPanel extends JPanel
implements FrequencyChangeListener
{
private static final long serialVersionUID = 1L;
private final static Logger mLog =
LoggerFactory.getLogger( HackRFTunerEditorPanel.class );
private JFrequencyControl mFrequencyControl;
private HackRFTuner mTuner;
private HackRFTunerController mController;
private ResourceManager mResourceManager;
public HackRFTunerEditorPanel( HackRFTuner tuner,
ResourceManager resourceManager )
{
mTuner = tuner;
mController = mTuner.getController();
mResourceManager = resourceManager;
initGUI();
}
private void initGUI()
{
setLayout( new MigLayout( "fill,wrap 2",
"[right,grow][grow]",
"[][][][][][grow]" ) );
BoardID board = BoardID.INVALID;
try
{
board = mTuner.getController().getBoardID();
}
catch ( UsbException e )
{
mLog.error( "couldn't read HackRF board identifier", e );
}
add( new JLabel( board.getLabel() ), "span,align center" );
mFrequencyControl = new JFrequencyControl();
mFrequencyControl.addListener( this );
/* Add frequency control as frequency change listener. This creates a
* feedback loop, so the control does not rebroadcast the event */
mTuner.addListener( mFrequencyControl );
mFrequencyControl.setFrequency( mController.getFrequency(), false );
add( mFrequencyControl, "span,align center" );
JideTabbedPane tabs = new JideTabbedPane();
tabs.setFont( this.getFont() );
tabs.setForeground( Color.BLACK );
add( tabs, "span,grow,push" );
tabs.add( "Config", new HackRFTunerConfigurationPanel(
mResourceManager, mTuner.getController() ) );
tabs.add( "Info", new HackRFInformationPanel( mTuner.getController() ) );
}
@Override
public void frequencyChanged( FrequencyChangeEvent event )
{
if( event.getAttribute() == Attribute.FREQUENCY )
{
try
{
mController.setFrequency( event.getValue().longValue() );
}
catch ( SourceException e )
{
mLog.error( "error setting frequency [" + event.getValue().longValue() + "]", e );
}
}
}
}
<file_sep>package decode.p25.message.pdu.osp.voice;
import java.util.Date;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.pdu.PDUMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import edac.CRCP25;
public class TelephoneInterconnectChannelGrantExplicit extends PDUMessage
implements IdentifierReceiver
{
/* Service Options */
public static final int EMERGENCY_FLAG = 128;
public static final int ENCRYPTED_CHANNEL_FLAG = 129;
public static final int DUPLEX_MODE = 130;
public static final int SESSION_MODE = 131;
public static final int[] ADDRESS = { 88,89,90,91,92,93,94,95,96,97,
98,99,100,101,102,103,104,105,106,107,108,109,110,111 };
public static final int[] SERVICE_OPTIONS = { 128,129,130,131,132,133,134,
135 };
public static final int[] TRANSMIT_IDENTIFIER = { 160,161,162,163 };
public static final int[] TRANSMIT_NUMBER = { 164,165,166,167,168,169,170,
171,172,173,174,175 };
public static final int[] RECEIVE_IDENTIFIER = { 176,177,178,179 };
public static final int[] RECEIVE_NUMBER = { 180,181,182,183,184,185,186,
187,188,189,190,191 };
public static final int[] CALL_TIMER = { 192,193,194,195,196,197,198,199,
200,201,202,203,204,205,206,207 };
public static final int[] MULTIPLE_BLOCK_CRC = { 224,225,226,227,228,229,
230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255 };
private IBandIdentifier mTransmitIdentifierUpdate;
private IBandIdentifier mReceiveIdentifierUpdate;
public TelephoneInterconnectChannelGrantExplicit( BinaryMessage message,
DataUnitID duid, AliasList aliasList )
{
super( message, duid, aliasList );
/* Header block is already error detected/corrected - perform error
* detection correction on the intermediate and final data blocks */
mMessage = CRCP25.correctPDU1( mMessage );
mCRC[ 1 ] = mMessage.getCRC();
}
@Override
public String getEventType()
{
return Opcode.TELEPHONE_INTERCONNECT_VOICE_CHANNEL_GRANT.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
if( isEmergency() )
{
sb.append( " EMERGENCY" );
}
sb.append( " ADDR:" );
sb.append( getAddress() );
sb.append( " CALL TIMER:" );
sb.append( mTimeDurationFormat.format( new Date( getCallTimer() ) ) );
sb.append( " CHAN DN:" + getTransmitChannelIdentifier() + "-" + getTransmitChannelNumber() );
sb.append( " " + getDownlinkFrequency() );
sb.append( " CHAN UP:" + getReceiveChannelIdentifier() + "-" + getReceiveChannelNumber() );
sb.append( " " + getUplinkFrequency() );
return sb.toString();
}
public boolean isEmergency()
{
return mMessage.get( EMERGENCY_FLAG );
}
public boolean isEncrypted()
{
return mMessage.get( ENCRYPTED_CHANNEL_FLAG );
}
public DuplexMode getDuplexMode()
{
return mMessage.get( DUPLEX_MODE ) ? DuplexMode.FULL : DuplexMode.HALF;
}
public SessionMode getSessionMode()
{
return mMessage.get( SESSION_MODE ) ?
SessionMode.CIRCUIT : SessionMode.PACKET;
}
public String getAddress()
{
return mMessage.getHex( ADDRESS, 6 );
}
/*
* Call timer in milliseconds
*/
public long getCallTimer()
{
int timer = mMessage.getInt( CALL_TIMER );
return timer / 100;
}
public int getTransmitChannelIdentifier()
{
return mMessage.getInt( TRANSMIT_IDENTIFIER );
}
public int getTransmitChannelNumber()
{
return mMessage.getInt( TRANSMIT_NUMBER );
}
public String getTransmitChannel()
{
return getTransmitChannelIdentifier() + "-" + getTransmitChannelNumber();
}
public int getReceiveChannelIdentifier()
{
return mMessage.getInt( RECEIVE_IDENTIFIER );
}
public int getReceiveChannelNumber()
{
return mMessage.getInt( RECEIVE_NUMBER );
}
public String getReceiveChannel()
{
return getReceiveChannelIdentifier() + "-" + getReceiveChannelNumber();
}
public long getDownlinkFrequency()
{
return calculateDownlink( mTransmitIdentifierUpdate, getTransmitChannelNumber() );
}
public long getUplinkFrequency()
{
return calculateUplink( mReceiveIdentifierUpdate, getReceiveChannelNumber() );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
if( identifier == getTransmitChannelIdentifier() )
{
mTransmitIdentifierUpdate = message;
}
if( identifier == getReceiveChannelIdentifier() )
{
mReceiveIdentifierUpdate = message;
}
}
public int[] getIdentifiers()
{
int[] idens = new int[ 2 ];
idens[ 0 ] = getTransmitChannelIdentifier();
idens[ 1 ] = getReceiveChannelIdentifier();
return idens;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 eventlog;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.file.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import util.TimeStamp;
public abstract class EventLogger
{
private final static Logger mLog =
LoggerFactory.getLogger( EventLogger.class );
/* Illegal filename characters */
private static final String[] mIllegalCharacters =
{ "#", "%", "&", "{", "}", "\\", "<", ">", "*", "?", "/",
" ", "$", "!", "'", "\"", ":", "@", "+", "`", "|", "=" };
private Path mLogDirectory;
private String mFileNameSuffix;
private String mLogFileName;
protected Writer mLogFile;
public EventLogger( Path logDirectory, String fileNameSuffix )
{
mLogDirectory = logDirectory;
mFileNameSuffix = fileNameSuffix;
}
public String toString()
{
if( mLogFileName != null )
{
return mLogFileName;
}
else
{
return "Unknown";
}
}
public abstract String getHeader();
public void start()
{
try
{
StringBuilder sb = new StringBuilder();
sb.append( mLogDirectory );
sb.append( File.separator );
sb.append( TimeStamp.getTimeStamp( "_" ) );
sb.append( "_" );
sb.append( replaceIllegalCharacters( mFileNameSuffix ) );
mLogFileName = sb.toString();
mLog.info( "Creating log file:" + mLogFileName );
mLogFile = new OutputStreamWriter(new FileOutputStream( mLogFileName ) );
write( getHeader() );
}
catch (FileNotFoundException e)
{
mLog.error("Couldn't create log file in directory:" + mLogDirectory );
}
}
/**
* Replaces any illegal filename characters in the proposed filename
*/
private String replaceIllegalCharacters( String filename )
{
for( String illegalCharacter: mIllegalCharacters )
{
filename = filename.replace( illegalCharacter, "_" );
}
return filename;
}
public void stop()
{
if( mLogFile != null )
{
try
{
mLogFile.flush();
mLogFile.close();
}
catch( Exception e )
{
mLog.error( "Couldn't close log file:" + mFileNameSuffix );
}
}
}
protected void write( String eventLogEntry )
{
try
{
mLogFile.write( eventLogEntry + "\n" );
}
catch ( IOException e )
{
mLog.error( "Error writing entry to event log file", e );
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.fcd;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
public class FCDTunerDetailsPanel extends JPanel
{
private static final long serialVersionUID = 1L;
public FCDTunerDetailsPanel( FCDTunerController controller )
{
setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][][][grow]" ) );
add( new JLabel( "USB ID:" ) );
add( new JLabel( controller.getUSBID() ) );
add( new JLabel( "USB Address:" ) );
add( new JLabel( controller.getUSBAddress() ) );
add( new JLabel( "USB Speed:" ) );
add( new JLabel( controller.getUSBSpeed() ) );
add( new JLabel( "Cellular Band:" ) );
add( new JLabel( controller.getConfiguration().getBandBlocking()
.getLabel() ) );
add( new JLabel( "Firmware:" ) );
add( new JLabel( controller.getConfiguration().getFirmware() ) );
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class SecondaryControlChannelBroadcastExplicit
extends SecondaryControlChannelBroadcast
{
private final static Logger mLog = LoggerFactory.getLogger(
SecondaryControlChannelBroadcastExplicit.class );
public SecondaryControlChannelBroadcastExplicit( BinaryMessage message,
DataUnitID duid, AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.SECONDARY_CONTROL_CHANNEL_BROADCAST_EXPLICIT.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " SITE:" + getRFSS() + "-" + getSiteID() );
sb.append( " DOWNLINK:" + getIdentifier1() + "-" + getChannel1() );
sb.append( " " + getDownlinkFrequency1() );
sb.append( " SVC1:" +
SystemService.toString( getSystemServiceClass1() ) );
if( hasChannel2() )
{
sb.append( " UPLINK:" + getIdentifier2() + "-" + getChannel2() );
sb.append( " " + getUplinkFrequency1() );
sb.append( " SVC2:" +
SystemService.toString( getSystemServiceClass2() ) );
}
return sb.toString();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 edac;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bits.BinaryMessage;
/**
* P25 CRC check/correction methods
*/
public class CRCP25
{
private final static Logger mLog = LoggerFactory.getLogger( CRCP25.class );
/**
* CRC-CCITT 16-bit checksums for a message length of 80 bits plus 16
* additional checksums representing CRC checksum bit errors
*
* Generated by:
* CRCUtil.generate( 80, 16, 0x11021l, 0xFFFFl, true );
*/
public static final int[] CCITT_80_CHECKSUMS = new int[]
{
0x1BCB, 0x8DE5, 0xC6F2, 0x6B69, 0xB5B4, 0x52CA, 0x2175, 0x90BA, 0x404D,
0xA026, 0x5803, 0xAC01, 0xD600, 0x6310, 0x3998, 0x14DC, 0x27E, 0x92F,
0x8497, 0xC24B, 0xE125, 0xF092, 0x7059, 0xB82C, 0x5406, 0x2213, 0x9109,
0xC884, 0x6C52, 0x3E39, 0x9F1C, 0x479E, 0x2BDF, 0x95EF, 0xCAF7, 0xE57B,
0xF2BD, 0xF95E, 0x74BF, 0xBA5F, 0xDD2F, 0xEE97, 0xF74B, 0xFBA5, 0xFDD2,
0x76F9, 0xBB7C, 0x55AE, 0x22C7, 0x9163, 0xC8B1, 0xE458, 0x7A3C, 0x350E,
0x1297, 0x894B, 0xC4A5, 0xE252, 0x7939, 0xBC9C, 0x565E, 0x233F, 0x919F,
0xC8CF, 0xE467, 0xF233, 0xF919, 0xFC8C, 0x7656, 0x333B, 0x999D, 0xCCCE,
0x6E77, 0xB73B, 0xDB9D, 0xEDCE, 0x7EF7, 0xBF7B, 0xDFBD, 0xEFDE, 0x0001,
0x0002, 0x0004, 0x0008, 0x0010, 0x0020, 0x0040, 0x0080, 0x0100, 0x0200,
0x0400, 0x0800, 0x1000, 0x2000, 0x4000, 0x8000
};
/**
* Confirmed Packet Data Unit CRC-9 checksums, generated by:
*
* long[] table = generate( 135, 9, 0x259l, 0x1FF, false, Parity.NONE );
*/
public static final int[] CRC9_CHECKSUMS = new int[]
{
0x1E7, 0x1F3, 0x1F9, 0x1FC, 0x0D2, 0x045, 0x122, 0x0BD, 0x15E, 0x083,
0x141, 0x1A0, 0x0FC, 0x052, 0x005, 0x102, 0x0AD, 0x156, 0x087, 0x143,
0x1A1, 0x1D0, 0x0C4, 0x04E, 0x00B, 0x105, 0x182, 0x0ED, 0x176, 0x097,
0x14B, 0x1A5, 0x1D2, 0x0C5, 0x162, 0x09D, 0x14E, 0x08B, 0x145, 0x1A2,
0x0FD, 0x17E, 0x093, 0x149, 0x1A4, 0x0FE, 0x053, 0x129, 0x194, 0x0E6,
0x05F, 0x12F, 0x197, 0x1CB, 0x1E5, 0x1F2, 0x0D5, 0x16A, 0x099, 0x14C,
0x08A, 0x069, 0x134, 0x0B6, 0x077, 0x13B, 0x19D, 0x1CE, 0x0CB, 0x165,
0x1B2, 0x0F5, 0x17A, 0x091, 0x148, 0x088, 0x068, 0x018, 0x020, 0x03C,
0x302, 0x035, 0x11A, 0x0A1, 0x150, 0x084, 0x06E, 0x01B, 0x10D, 0x186,
0x0EF, 0x177, 0x1BB, 0x1DD, 0x1EE, 0x0DB, 0x16D, 0x1B6, 0x0F7, 0x17B,
0x1BD, 0x1DE, 0x0C3, 0x161, 0x1B0, 0x0F4, 0x056, 0x007, 0x103, 0x181,
0x1C0, 0x0CC, 0x04A, 0x009, 0x104, 0x0AE, 0x07B, 0x13D, 0x19E, 0x0E3,
0x171, 0x1B8, 0x0F0, 0x054, 0x006, 0x02F, 0x117, 0x18B, 0x1C5, 0x1E2,
0x0DD, 0x16E, 0x09B, 0x14D, 0x1A6
};
/**
* CRC-32 checksums for PDU1 ( HEADER + 1 Block ) messages, generated by:
*
* CRCUtil.generate( 64, 32, 0x104C11DB7l, 0xFFFFFFFFl, true );
*/
public static final long[] PDU1_CHECKSUMS = new long[]
{
0x86FFAACCl, 0x411F5BBDl, 0xA08FADDEl, 0x52275834l, 0x2B7322C1l,
0x95B99160l, 0x48BC466Bl, 0xA45E2335l, 0xD22F119Al, 0x6B770616l,
0x37DB0DD0l, 0x198D0833l, 0x8CC68419l, 0xC663420Cl, 0x61512FDDl,
0xB0A897EEl, 0x5A34C52Cl, 0x2F7AEC4Dl, 0x97BD7626l, 0x49BE35C8l,
0x26BF943Fl, 0x935FCA1Fl, 0xC9AFE50Fl, 0xE4D7F287l, 0xF26BF943l,
0xF935FCA1l, 0xFC9AFE50l, 0x7C2DF1F3l, 0xBE16F8F9l, 0xDF0B7C7Cl,
0x6DE530E5l, 0xB6F29872l, 0x5919C2E2l, 0x2EEC6FAAl, 0x1516B90El,
0x08EBD25Cl, 0x061567F5l, 0x830AB3FAl, 0x43E5D726l, 0x23926548l,
0x13A9BC7Fl, 0x89D4DE3Fl, 0xC4EA6F1Fl, 0xE275378Fl, 0xF13A9BC7l,
0xF89D4DE3l, 0xFC4EA6F1l, 0xFE275378l, 0x7D732767l, 0xBEB993B3l,
0xDF5CC9D9l, 0xEFAE64ECl, 0x75B7BCADl, 0xBADBDE56l, 0x5F0D61F0l,
0x2DE63E23l, 0x96F31F11l, 0xCB798F88l, 0x67DC491Fl, 0xB3EE248Fl,
0xD9F71247l, 0xECFB8923l, 0xF67DC491l, 0xFB3EE248l, 0x00000001l,
0x00000002l, 0x00000004l, 0x00000008l, 0x00000010l, 0x00000020l,
0x00000040l, 0x00000080l, 0x00000100l, 0x00000200l, 0x00000400l,
0x00000800l, 0x00001000l, 0x00002000l, 0x00004000l, 0x00008000l,
0x00010000l, 0x00020000l, 0x00040000l, 0x00080000l, 0x00100000l,
0x00200000l, 0x00400000l, 0x00800000l, 0x01000000l, 0x02000000l,
0x04000000l, 0x08000000l, 0x10000000l, 0x20000000l, 0x40000000l,
0x80000000l
};
/**
* CRC-32 checksums for PDU2 ( HEADER + 2 Blocks ) messages, generated by:
*
* CRCUtil.generate( 160, 32, 0x104C11DB7l, 0xFFFFFFFFl, true );
*/
public static final long[] PDU2_CHECKSUMS = new long[]
{
0x9D231959l, 0xCE918CACl, 0x6528488Dl, 0xB2942446l, 0x5B2A9CF8l,
0x2FF5C0A7l, 0x97FAE053l, 0xCBFD7029l, 0xE5FEB814l, 0x709FD2D1l,
0xB84FE968l, 0x5E477A6Fl, 0xAF23BD37l, 0xD791DE9Bl, 0xEBC8EF4Dl,
0xF5E477A6l, 0x7892B508l, 0x3E29D45Fl, 0x9F14EA2Fl, 0xCF8A7517l,
0xE7C53A8Bl, 0xF3E29D45l, 0xF9F14EA2l, 0x7E98298Al, 0x3D2C9A1El,
0x1CF6C3D4l, 0x0C1BEF31l, 0x860DF798l, 0x41667517l, 0xA0B33A8Bl,
0xD0599D45l, 0xE82CCEA2l, 0x7676E98Al, 0x395BFA1El, 0x1ECD73D4l,
0x0D063731l, 0x86831B98l, 0x41210317l, 0xA090818Bl, 0xD04840C5l,
0xE8242062l, 0x76729EEAl, 0x3959C1AEl, 0x1ECC6E0Cl, 0x0D06B9DDl,
0x86835CEEl, 0x412120ACl, 0x22F01E8Dl, 0x91780F46l, 0x4ADC8978l,
0x270ECA67l, 0x93876533l, 0xC9C3B299l, 0xE4E1D94Cl, 0x7010627Dl,
0xB808313El, 0x5E649644l, 0x2D52C5F9l, 0x96A962FCl, 0x49343FA5l,
0xA49A1FD2l, 0x502D8132l, 0x2A764E42l, 0x175BA9FAl, 0x09CD5A26l,
0x068623C8l, 0x01239F3Fl, 0x8091CF9Fl, 0xC048E7CFl, 0xE02473E7l,
0xF01239F3l, 0xF8091CF9l, 0xFC048E7Cl, 0x7C62C9E5l, 0xBE3164F2l,
0x5D783CA2l, 0x2CDC908Al, 0x140EC69El, 0x0867ED94l, 0x06537811l,
0x8329BC08l, 0x43F450DFl, 0xA1FA286Fl, 0xD0FD1437l, 0xE87E8A1Bl,
0xF43F450Dl, 0xFA1FA286l, 0x7F6F5F98l, 0x3DD72117l, 0x9EEB908Bl,
0xCF75C845l, 0xE7BAE422l, 0x71BDFCCAl, 0x3ABE70BEl, 0x1F3FB684l,
0x0DFF5599l, 0x86FFAACCl, 0x411F5BBDl, 0xA08FADDEl, 0x52275834l,
0x2B7322C1l, 0x95B99160l, 0x48BC466Bl, 0xA45E2335l, 0xD22F119Al,
0x6B770616l, 0x37DB0DD0l, 0x198D0833l, 0x8CC68419l, 0xC663420Cl,
0x61512FDDl, 0xB0A897EEl, 0x5A34C52Cl, 0x2F7AEC4Dl, 0x97BD7626l,
0x49BE35C8l, 0x26BF943Fl, 0x935FCA1Fl, 0xC9AFE50Fl, 0xE4D7F287l,
0xF26BF943l, 0xF935FCA1l, 0xFC9AFE50l, 0x7C2DF1F3l, 0xBE16F8F9l,
0xDF0B7C7Cl, 0x6DE530E5l, 0xB6F29872l, 0x5919C2E2l, 0x2EEC6FAAl,
0x1516B90El, 0x08EBD25Cl, 0x061567F5l, 0x830AB3FAl, 0x43E5D726l,
0x23926548l, 0x13A9BC7Fl, 0x89D4DE3Fl, 0xC4EA6F1Fl, 0xE275378Fl,
0xF13A9BC7l, 0xF89D4DE3l, 0xFC4EA6F1l, 0xFE275378l, 0x7D732767l,
0xBEB993B3l, 0xDF5CC9D9l, 0xEFAE64ECl, 0x75B7BCADl, 0xBADBDE56l,
0x5F0D61F0l, 0x2DE63E23l, 0x96F31F11l, 0xCB798F88l, 0x67DC491Fl,
0xB3EE248Fl, 0xD9F71247l, 0xECFB8923l, 0xF67DC491l, 0xFB3EE248l,
0x00000001l, 0x00000002l, 0x00000004l, 0x00000008l, 0x00000010l,
0x00000020l, 0x00000040l, 0x00000080l, 0x00000100l, 0x00000200l,
0x00000400l, 0x00000800l, 0x00001000l, 0x00002000l, 0x00004000l,
0x00008000l, 0x00010000l, 0x00020000l, 0x00040000l, 0x00080000l,
0x00100000l, 0x00200000l, 0x00400000l, 0x00800000l, 0x01000000l,
0x02000000l, 0x04000000l, 0x08000000l, 0x10000000l, 0x20000000l,
0x40000000l, 0x80000000l
};
/**
* CRC-32 checksums for PDU3 ( HEADER + 3 Blocks ) messages, generated by:
*
* CRCUtil.generate( 256, 32, 0x104C11DB7l, 0xFFFFFFFFl, true );
*/
public static final long[] PDU3_CHECKSUMS = new long[]
{
0xAA5FA470l, 0x574F5CE3l, 0xABA7AE71l, 0xD5D3D738l, 0x68896547l,
0xB444B2A3l, 0xDA225951l, 0xED112CA8l, 0x74E8188Fl, 0xBA740C47l,
0xDD3A0623l, 0xEE9D0311l, 0xF74E8188l, 0x79C7CE1Fl, 0xBCE3E70Fl,
0xDE71F387l, 0xEF38F9C3l, 0xF79C7CE1l, 0xFBCE3E70l, 0x7F8791E3l,
0xBFC3C8F1l, 0xDFE1E478l, 0x6D907CE7l, 0xB6C83E73l, 0xDB641F39l,
0xEDB20F9Cl, 0x74B98915l, 0xBA5CC48Al, 0x5F4EEC9El, 0x2DC7F894l,
0x14837291l, 0x8A41B948l, 0x4740527Fl, 0xA3A0293Fl, 0xD1D0149Fl,
0xE8E80A4Fl, 0xF4740527l, 0xFA3A0293l, 0xFD1D0149l, 0xFE8E80A4l,
0x7D27CE89l, 0xBE93E744l, 0x5D297D79l, 0xAE94BEBCl, 0x552AD185l,
0xAA9568C2l, 0x572A3ABAl, 0x29F59386l, 0x169A4718l, 0x092DAD57l,
0x8496D6ABl, 0xC24B6B55l, 0xE125B5AAl, 0x72F2540El, 0x3B19A4DCl,
0x1FEC5CB5l, 0x8FF62E5Al, 0x459B99F6l, 0x20AD4220l, 0x12362FCBl,
0x891B17E5l, 0xC48D8BF2l, 0x60264B22l, 0x3273AB4Al, 0x1B595B7El,
0x0FCC2364l, 0x05869F69l, 0x82C34FB4l, 0x43012901l, 0xA1809480l,
0x52A0C49Bl, 0xA950624Dl, 0xD4A83126l, 0x68349648l, 0x367AC5FFl,
0x9B3D62FFl, 0xCD9EB17Fl, 0xE6CF58BFl, 0xF367AC5Fl, 0xF9B3D62Fl,
0xFCD9EB17l, 0xFE6CF58Bl, 0xFF367AC5l, 0xFF9B3D62l, 0x7DAD106Al,
0x3CB606EEl, 0x1C3B8DACl, 0x0C7D480Dl, 0x863EA406l, 0x417FDCD8l,
0x22DF60B7l, 0x916FB05Bl, 0xC8B7D82Dl, 0xE45BEC16l, 0x704D78D0l,
0x3A4632B3l, 0x9D231959l, 0xCE918CACl, 0x6528488Dl, 0xB2942446l,
0x5B2A9CF8l, 0x2FF5C0A7l, 0x97FAE053l, 0xCBFD7029l, 0xE5FEB814l,
0x709FD2D1l, 0xB84FE968l, 0x5E477A6Fl, 0xAF23BD37l, 0xD791DE9Bl,
0xEBC8EF4Dl, 0xF5E477A6l, 0x7892B508l, 0x3E29D45Fl, 0x9F14EA2Fl,
0xCF8A7517l, 0xE7C53A8Bl, 0xF3E29D45l, 0xF9F14EA2l, 0x7E98298Al,
0x3D2C9A1El, 0x1CF6C3D4l, 0x0C1BEF31l, 0x860DF798l, 0x41667517l,
0xA0B33A8Bl, 0xD0599D45l, 0xE82CCEA2l, 0x7676E98Al, 0x395BFA1El,
0x1ECD73D4l, 0x0D063731l, 0x86831B98l, 0x41210317l, 0xA090818Bl,
0xD04840C5l, 0xE8242062l, 0x76729EEAl, 0x3959C1AEl, 0x1ECC6E0Cl,
0x0D06B9DDl, 0x86835CEEl, 0x412120ACl, 0x22F01E8Dl, 0x91780F46l,
0x4ADC8978l, 0x270ECA67l, 0x93876533l, 0xC9C3B299l, 0xE4E1D94Cl,
0x7010627Dl, 0xB808313El, 0x5E649644l, 0x2D52C5F9l, 0x96A962FCl,
0x49343FA5l, 0xA49A1FD2l, 0x502D8132l, 0x2A764E42l, 0x175BA9FAl,
0x09CD5A26l, 0x068623C8l, 0x01239F3Fl, 0x8091CF9Fl, 0xC048E7CFl,
0xE02473E7l, 0xF01239F3l, 0xF8091CF9l, 0xFC048E7Cl, 0x7C62C9E5l,
0xBE3164F2l, 0x5D783CA2l, 0x2CDC908Al, 0x140EC69El, 0x0867ED94l,
0x06537811l, 0x8329BC08l, 0x43F450DFl, 0xA1FA286Fl, 0xD0FD1437l,
0xE87E8A1Bl, 0xF43F450Dl, 0xFA1FA286l, 0x7F6F5F98l, 0x3DD72117l,
0x9EEB908Bl, 0xCF75C845l, 0xE7BAE422l, 0x71BDFCCAl, 0x3ABE70BEl,
0x1F3FB684l, 0x0DFF5599l, 0x86FFAACCl, 0x411F5BBDl, 0xA08FADDEl,
0x52275834l, 0x2B7322C1l, 0x95B99160l, 0x48BC466Bl, 0xA45E2335l,
0xD22F119Al, 0x6B770616l, 0x37DB0DD0l, 0x198D0833l, 0x8CC68419l,
0xC663420Cl, 0x61512FDDl, 0xB0A897EEl, 0x5A34C52Cl, 0x2F7AEC4Dl,
0x97BD7626l, 0x49BE35C8l, 0x26BF943Fl, 0x935FCA1Fl, 0xC9AFE50Fl,
0xE4D7F287l, 0xF26BF943l, 0xF935FCA1l, 0xFC9AFE50l, 0x7C2DF1F3l,
0xBE16F8F9l, 0xDF0B7C7Cl, 0x6DE530E5l, 0xB6F29872l, 0x5919C2E2l,
0x2EEC6FAAl, 0x1516B90El, 0x08EBD25Cl, 0x061567F5l, 0x830AB3FAl,
0x43E5D726l, 0x23926548l, 0x13A9BC7Fl, 0x89D4DE3Fl, 0xC4EA6F1Fl,
0xE275378Fl, 0xF13A9BC7l, 0xF89D4DE3l, 0xFC4EA6F1l, 0xFE275378l,
0x7D732767l, 0xBEB993B3l, 0xDF5CC9D9l, 0xEFAE64ECl, 0x75B7BCADl,
0xBADBDE56l, 0x5F0D61F0l, 0x2DE63E23l, 0x96F31F11l, 0xCB798F88l,
0x67DC491Fl, 0xB3EE248Fl, 0xD9F71247l, 0xECFB8923l, 0xF67DC491l,
0xFB3EE248l, 0x00000001l, 0x00000002l, 0x00000004l, 0x00000008l,
0x00000010l, 0x00000020l, 0x00000040l, 0x00000080l, 0x00000100l,
0x00000200l, 0x00000400l, 0x00000800l, 0x00001000l, 0x00002000l,
0x00004000l, 0x00008000l, 0x00010000l, 0x00020000l, 0x00040000l,
0x00080000l, 0x00100000l, 0x00200000l, 0x00400000l, 0x00800000l,
0x01000000l, 0x02000000l, 0x04000000l, 0x08000000l, 0x10000000l,
0x20000000l, 0x40000000l, 0x80000000l
};
/**
* Performs error detection and single-bit error correction against the
* data blocks of a PDU1 message.
*/
public static BinaryMessage correctPDU1( BinaryMessage message )
{
return correctPDU( message, PDU1_CHECKSUMS, 224 );
}
/**
* Performs error detection and single-bit error correction against the
* data blocks of a PDU2 message.
*/
public static BinaryMessage correctPDU2( BinaryMessage message )
{
return correctPDU( message, PDU2_CHECKSUMS, 320 );
}
/**
* Performs error detection and single-bit error correction against the
* data blocks of a PDU3 message.
*/
public static BinaryMessage correctPDU3( BinaryMessage message )
{
return correctPDU( message, PDU3_CHECKSUMS, 416 );
}
public static BinaryMessage correctPDU( BinaryMessage message, long[] checksums, int crcStart )
{
long calculated = 0; //Starting value
int messageStart = 160;
/* Iterate the set bits and XOR running checksum with lookup value */
for (int i = message.nextSetBit( messageStart );
i >= messageStart && i < crcStart;
i = message.nextSetBit( i+1 ) )
{
calculated ^= checksums[ i - messageStart ];
}
long checksum = getLongChecksum( message, crcStart, 32 );
long error = calculated ^ checksum;
if( error == 0 || error == 0xFFFFFFFFl )
{
message.setCRC( CRC.PASSED );
return message;
}
else
{
int errorLocation = getBitError( error, checksums );
if( errorLocation >= 0 )
{
message.flip( errorLocation + messageStart );
message.setCRC( CRC.CORRECTED );
return message;
}
}
message.setCRC( CRC.FAILED_CRC );
return message;
}
/**
* Error detection and correction of single-bit errors for CCITT 16-bit
* CRC protected 80-bit messages.
*/
public static BinaryMessage correctCCITT80( BinaryMessage message,
int messageStart,
int crcStart )
{
int calculated = 0; //Starting value
/* Iterate the set bits and XOR running checksum with lookup value */
for (int i = message.nextSetBit( messageStart );
i >= messageStart && i < crcStart;
i = message.nextSetBit( i+1 ) )
{
calculated ^= CCITT_80_CHECKSUMS[ i - messageStart ];
}
int checksum = getIntChecksum( message, crcStart, 16 );
int residual = calculated ^ checksum;
if( residual == 0 || residual == 0xFFFF )
{
message.setCRC( CRC.PASSED );
return message;
}
else
{
int errorLocation = getBitError( residual, CCITT_80_CHECKSUMS );
if( errorLocation >= 0 )
{
message.flip( errorLocation + messageStart );
message.setCRC( CRC.CORRECTED );
return message;
}
}
message.setCRC( CRC.FAILED_CRC );
return message;
}
/**
* Error detection for CRC-9 protected Confirmed Packet Data blocks. These
* data blocks have a slightly complicated structure because the checksum
* is located between bits 7-15, within a 144 bit block. The checksums
* were generated assuming that the message is contiguous from 0 - 134 bits.
* No data correction is performed.
*/
public static CRC checkCRC9( BinaryMessage message, int messageStart )
{
int calculated = 0x0; //Initial fill of all ones
/* Iterate the set bits and XOR running checksum with lookup value */
for (int i = message.nextSetBit( messageStart );
i >= messageStart && i < messageStart + 144;
i = message.nextSetBit( i+1 ) )
{
/* message bits before the CRC */
if( i < ( messageStart + 7 ) )
{
calculated ^= CRC9_CHECKSUMS[ i - messageStart ];
}
/* message bits after the CRC */
else if( i > ( messageStart + 15 ) )
{
calculated ^= CRC9_CHECKSUMS[ i - messageStart - 9 ];
}
}
int checksum = message.getInt( messageStart + 7, messageStart + 15 );
int residual = calculated ^ checksum;
// mLog.debug( "CALC:" + calculated + " CHECK:" + checksum + " RESID:" + residual );
if( residual == 0 || residual == 0x1FF )
{
return CRC.PASSED;
}
return CRC.FAILED_CRC;
}
/**
* Performs Galois 24/12/7 error detection and correction against the 12
* encoded 24-bit message segments following the 64-bit NID in the message
*
* @return - true if all 12 segments of the message can be checked/corrected
*/
public static boolean correctGalois24( BinaryMessage tdulc )
{
boolean passes = true;
int x = 64;
while( x < tdulc.size() && passes )
{
tdulc = Golay24.checkAndCorrect( tdulc, x );
passes = tdulc.getCRC() == CRC.PASSED;
x += 24;
}
return passes;
}
/**
* Calculates the value of the message checksum as a long
*/
public static long getLongChecksum( BinaryMessage message,
int crcStart, int crcLength )
{
return message.getLong( crcStart, crcStart + crcLength - 1 );
}
/**
* Calculates the value of the message checksum as an integer
*/
public static int getIntChecksum( BinaryMessage message,
int crcStart, int crcLength )
{
return message.getInt( crcStart, crcStart + crcLength - 1 );
}
/**
* Identifies any single bit error position that matches the checksum error.
*/
public static int getBitError( long checksumError, long[] checksums )
{
for( int x = 0; x < checksums.length; x++ )
{
if( checksums[ x ] == checksumError )
{
return x;
}
}
return -1;
}
/**
* Identifies any single bit error position that matches the checksum error.
*/
public static int getBitError( int checksumError, int[] checksums )
{
for( int x = 0; x < checksums.length; x++ )
{
if( checksums[ x ] == checksumError )
{
return x;
}
}
return -1;
}
public static void main( String[] args )
{
String raw = "000000001000001100000001010001111011000100001010010001111100000000000101000000000000000001000000000000110000000000000001101010101010101010101010";
BinaryMessage message = BinaryMessage.load( raw );
mLog.debug( "MSG:" + message.toString() );
CRC results = checkCRC9( message, 0 );
mLog.debug( "COR:" + message.toString() );
mLog.debug( "Results: " + results.getDisplayText() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 audio.inverted;
import audio.InversionFrequency;
import sample.real.RealSampleListener;
import util.Oscillator;
import dsp.filter.Filters;
import dsp.filter.FloatFIRFilter;
/**
* Applies audio inversion (or un-inversion) to a stream of float audio samples
* by multiplying each successive sample by either a 1 or a -1 value.
*/
public class AudioInverter implements RealSampleListener
{
private Oscillator mSineWaveGenerator;
private FloatFIRFilter mPostInversionLowPassFilter;
private RealSampleListener mListener;
public AudioInverter( int inversionFrequency, int sampleRate )
{
mSineWaveGenerator = new Oscillator( inversionFrequency, sampleRate );
mPostInversionLowPassFilter = new FloatFIRFilter(
Filters.FIRLP_55TAP_48000FS_3000FC.getCoefficients(), 1.04 );
mPostInversionLowPassFilter.setListener( new FilteredSampleProcessor() );
}
public AudioInverter( InversionFrequency frequency, int sampleRate )
{
this( frequency.getFrequency(), sampleRate );
}
public void setListener( RealSampleListener listener )
{
mListener = listener;
}
@Override
public void receive( float sample )
{
//Multiply the sample by the folding frequency and then send it to
//the low pass filter
if( mPostInversionLowPassFilter != null )
{
mPostInversionLowPassFilter.receive(
sample * mSineWaveGenerator.nextFloat() );
}
}
/**
* Simple class to receive the output of the FIR low pass filter and then
* send it to the registered listener(s)
*/
class FilteredSampleProcessor implements RealSampleListener
{
@Override
public void receive( float sample )
{
if( mListener != null )
{
mListener.receive( sample );
}
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.channel;
import java.util.ArrayList;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlSeeAlso( { ChannelRange.class } )
public class ChannelMap
{
private String mName;
private ArrayList<ChannelRange> mRanges = new ArrayList<ChannelRange>();
public ChannelMap()
{
this( "New Channel Map" );
}
public ChannelMap( String name )
{
mName = name;
}
public String toString()
{
return mName;
}
/**
* Creates a copy of this channel map
*/
public ChannelMap copyOf()
{
ChannelMap map = new ChannelMap( mName );
for( ChannelRange range: mRanges )
{
map.addRange( range.copyOf() );
}
return map;
}
public int getInvalidRange()
{
for( int x = 0; x < mRanges.size(); x++ )
{
if( !mRanges.get( x ).isValid() )
{
return x;
}
}
return -1;
}
public ArrayList<ChannelRange> getRanges()
{
return mRanges;
}
@XmlElement( name = "range" )
public void setRanges( ArrayList<ChannelRange> ranges )
{
mRanges = ranges;
}
@XmlAttribute
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
public long getFrequency( int channelNumber )
{
for( ChannelRange range: mRanges )
{
if( range.hasChannel( channelNumber ) )
{
return range.getFrequency( channelNumber );
}
}
return 0;
}
public void addRange( ChannelRange range )
{
mRanges.add( range );
}
public void deleteRange( ChannelRange range )
{
mRanges.remove( range );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.fcd;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import javax.swing.JPanel;
import javax.usb.UsbClaimException;
import javax.usb.UsbException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
import source.SourceException;
import source.tuner.TunerClass;
import source.tuner.TunerConfiguration;
import source.tuner.TunerController;
import source.tuner.TunerType;
import source.tuner.fcd.proV1.FCD1TunerController.Block;
import controller.ResourceManager;
public abstract class FCDTunerController extends TunerController
{
private final static Logger mLog =
LoggerFactory.getLogger( FCDTunerController.class );
public final static byte FCD_INTERFACE = (byte)0x2;
public final static byte FCD_ENDPOINT_IN = (byte)0x82;
public final static byte FCD_ENDPOINT_OUT = (byte)0x2;
private Device mDevice;
private DeviceDescriptor mDeviceDescriptor;
private DeviceHandle mDeviceHandle;
private FCDConfiguration mConfiguration = new FCDConfiguration();
/**
* Generic FCD tuner controller - contains functionality common across both
* funcube dongle tuners
*
* @param device
* @param descriptor
* @param minTunableFrequency
* @param maxTunableFrequency
*/
public FCDTunerController( Device device,
DeviceDescriptor descriptor,
int minTunableFrequency,
int maxTunableFrequency )
{
super( minTunableFrequency, maxTunableFrequency );
mDevice = device;
mDeviceDescriptor = descriptor;
}
/**
* Initializes the controller by opening the USB device and claiming the
* HID interface.
*
* Invoke this method after constructing this class to setup the
* controller.
*
* @throws SourceException if cannot open and claim the USB device
*/
public void init() throws SourceException
{
mDeviceHandle = new DeviceHandle();
int result = LibUsb.open( mDevice, mDeviceHandle );
if( result != LibUsb.SUCCESS )
{
mDeviceHandle = null;
throw new SourceException( "libusb couldn't open funcube usb "
+ "device [" + LibUsb.errorName( result ) + "]" );
}
claimInterface();
}
/**
* Disposes of resources. Closes the USB device and interface.
*/
public void dispose()
{
if( mDeviceHandle != null )
{
try
{
LibUsb.close( mDeviceHandle );
}
catch( Exception e )
{
mLog.error( "error while closing device handle", e );
}
mDeviceHandle = null;
}
mDeviceDescriptor = null;
mDevice = null;
}
/**
* Sample rate of the tuner
*/
public abstract int getCurrentSampleRate() throws SourceException;
/**
* Tuner class
*/
public abstract TunerClass getTunerClass();
/**
* Tuner type
*/
public abstract TunerType getTunerType();
/**
* Editor panel (GUI) component.
*/
public abstract JPanel getEditor( FCDTuner tuner,
ResourceManager resourceManager );
/**
* Applies the settings in the tuner configuration
*/
public abstract void apply( TunerConfiguration config )
throws SourceException;
/**
* Returns the currently applied tuner configuration or null if one hasn't
* yet been applied
*/
public abstract TunerConfiguration getTunerConfiguration();
/**
* USB address (bus/port)
*/
public String getUSBAddress()
{
if( mDevice != null )
{
StringBuilder sb = new StringBuilder();
sb.append( "Bus:" );
int bus = LibUsb.getBusNumber( mDevice );
sb.append( bus );
sb.append( " Port:" );
int port = LibUsb.getPortNumber( mDevice );
sb.append( port );
return sb.toString();
}
return "UNKNOWN";
}
/**
* USB Vendor and Product ID
*/
public String getUSBID()
{
if( mDeviceDescriptor != null )
{
StringBuilder sb = new StringBuilder();
sb.append( String.format( "%04X",
(int)( mDeviceDescriptor.idVendor() & 0xFFFF ) ) );
sb.append( ":" );
sb.append( String.format( "%04X",
(int)( mDeviceDescriptor.idProduct() & 0xFFFF ) ) );
return sb.toString();
}
return "UNKNOWN";
}
/**
* USB Port Speed. Should be 2.0 for both types of funcube dongles
*/
public String getUSBSpeed()
{
if( mDevice != null )
{
int speed = LibUsb.getDeviceSpeed( mDevice );
switch( speed )
{
case 0:
return "1.1 LOW";
case 1:
return "1.1 FULL";
case 2:
return "2.0 HIGH";
case 3:
return "3.0 SUPER";
default:
}
}
return "UNKNOWN";
}
/**
* Set fcd interface mode
*/
public void setFCDMode( Mode mode ) throws UsbException, UsbClaimException
{
ByteBuffer response = null;
switch( mode )
{
case APPLICATION:
response = send( FCDCommand.BL_QUERY );
break;
case BOOTLOADER:
response = send( FCDCommand.APP_RESET );
break;
default:
break;
}
if( response != null )
{
mConfiguration.set( response );
}
else
{
mConfiguration.setModeUnknown();
}
}
/**
* Sets the actual (uncorrected) device frequency
*/
public void setTunedFrequency( long frequency ) throws SourceException
{
try
{
send( FCDCommand.APP_SET_FREQUENCY_HZ, frequency );
}
catch( Exception e )
{
throw new SourceException( "Couldn't set FCD Local " +
"Oscillator Frequency [" + frequency + "]", e );
}
}
/**
* Gets the actual (uncorrected) device frequency
*/
public long getTunedFrequency() throws SourceException
{
try
{
ByteBuffer buffer = send( FCDCommand.APP_GET_FREQUENCY_HZ );
buffer.order( ByteOrder.LITTLE_ENDIAN );
return (int)( buffer.getInt( 2 ) & 0xFFFFFFFF );
}
catch( Exception e )
{
throw new SourceException( "FCDTunerController - "
+ "couldn't get LO frequency", e );
}
}
/**
* Returns the FCD device configuration
*/
public FCDConfiguration getConfiguration()
{
return mConfiguration;
}
/**
* Claims the USB interface. Attempts to detach the active kernel driver if
* one is currently attached.
*/
private void claimInterface() throws SourceException
{
if( mDeviceHandle != null )
{
int result = LibUsb.kernelDriverActive( mDeviceHandle, FCD_INTERFACE );
if( result == 1 )
{
result = LibUsb.detachKernelDriver( mDeviceHandle,
FCD_INTERFACE );
if( result != LibUsb.SUCCESS )
{
mLog.error( "failed attempt to detach kernel driver [" +
LibUsb.errorName( result ) + "]" );
}
}
result = LibUsb.claimInterface( mDeviceHandle, FCD_INTERFACE );
if( result != LibUsb.SUCCESS )
{
throw new SourceException( "couldn't claim usb interface [" +
LibUsb.errorName( result ) + "]" );
}
}
else
{
throw new SourceException( "couldn't claim usb hid interface - no "
+ "device handle" );
}
}
/**
* Performs an interrupt write to the OUT endpoint.
* @param buffer - direct allocated buffer. Must be 64 bytes in length.
*
* @throws LibUsbException on error
*/
private void write( ByteBuffer buffer ) throws LibUsbException
{
if( mDeviceHandle != null )
{
IntBuffer transferred = IntBuffer.allocate( 1 );
int result = LibUsb.interruptTransfer( mDeviceHandle,
FCD_ENDPOINT_OUT,
buffer,
transferred,
500l );
if( result != LibUsb.SUCCESS )
{
throw new LibUsbException( "error writing byte buffer",
result );
}
// else if( transferred.get() != buffer.capacity() )
// {
// throw new LibUsbException( "transferred bytes [" +
// transferred.get( 0 ) + "] is not what was expected [" +
// buffer.capacity() + "]", result );
// }
}
else
{
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
}
/**
* Performs an interrupt write to the OUT endpoint for the FCD command.
* @param command - no-argument command to write
* @throws LibUsbException - on error
*/
private void write( FCDCommand command ) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 64 );
buffer.put( 0, command.getCommand() );
buffer.put( 1, (byte)0x00 );
write( buffer );
}
/**
* Convenience logger for debugging read/write operations
*/
@SuppressWarnings( "unused" )
private void log( String label, ByteBuffer buffer )
{
StringBuilder sb = new StringBuilder();
sb.append( label );
sb.append( " " );
sb.append( buffer.get( 0 ) );
sb.append( " | " );
for( int x = 0; x < 64; x++ )
{
sb.append( String.format( "%02X", (int)( buffer.get( x ) & 0xFF ) ) );
sb.append( " " );
}
mLog.debug( sb.toString() );
}
/**
* Performs an interrupt write to the OUT endpoint for the FCD command.
* @param command - command to write
* @param argument - value to write with the command
* @throws LibUsbException - on error
*/
private void write( FCDCommand command, long argument ) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 64 );
/* The FCD expects little-endian formatted values */
buffer.order( ByteOrder.LITTLE_ENDIAN );
buffer.put( 0, command.getCommand() );
buffer.putLong( 1, argument );
write( buffer );
}
/**
* Performs an interrupt read against the endpoint
* @return buffer read from FCD
* @throws LibUsbException on error
*/
private ByteBuffer read() throws LibUsbException
{
if( mDeviceHandle != null )
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 64 );
IntBuffer transferred = IntBuffer.allocate( 1 );
int result = LibUsb.interruptTransfer( mDeviceHandle,
FCD_ENDPOINT_IN,
buffer,
transferred,
500l );
if( result != LibUsb.SUCCESS )
{
throw new LibUsbException( "error reading byte buffer",
result );
}
else if( transferred.get( 0 ) != buffer.capacity() )
{
throw new LibUsbException( "received bytes [" +
transferred.get( 0 ) + "] didn't match expected "
+ "length [" + buffer.capacity() + "]", result );
}
return buffer;
}
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
/**
* Sends the FCD command and argument. Performs a read to complete the
* command.
*
* @param command - command to send
* @param argument - command argument to send
* @throws LibUsbException - on error
*/
protected void send( FCDCommand command, long argument ) throws LibUsbException
{
write( command, argument );
read();
}
/**
* Sends the no-argument FCD command. Performs a read to complete the
* command.
*
* @param command - command to send
* @throws LibUsbException - on error
*/
protected ByteBuffer send( FCDCommand command ) throws LibUsbException
{
write( command );
return read();
}
/**
* FCD configuration string parsing class
*/
public class FCDConfiguration
{
private String mConfig;
private Mode mMode;
public FCDConfiguration()
{
mConfig = null;
mMode = Mode.UNKNOWN;
}
private void setModeUnknown()
{
mConfig = null;
mMode = Mode.UNKNOWN;
}
/**
* Extracts the configuration string from the buffer
*/
public void set( ByteBuffer buffer )
{
if( buffer.capacity() == 64 )
{
byte[] data = new byte[ 64 ];
for( int x = 0; x < 64; x++ )
{
data[ x ] = buffer.get( x );
}
mConfig = new String( data );
mMode = Mode.getMode( mConfig );
}
else
{
mConfig = null;
mMode = Mode.ERROR;
}
}
public Mode getMode()
{
return mMode;
}
public FCDModel getModel()
{
FCDModel retVal = FCDModel.FUNCUBE_UNKNOWN;
switch( mMode )
{
case APPLICATION:
retVal = FCDModel.getFCD( mConfig.substring( 15, 22 ) );
break;
case BOOTLOADER:
case UNKNOWN:
case ERROR:
break;
}
return retVal;
}
public Block getBandBlocking()
{
Block retVal = Block.UNKNOWN;
switch( mMode )
{
case APPLICATION:
retVal = Block.getBlock( mConfig.substring( 23, 33 ).trim() );
break;
case BOOTLOADER:
case UNKNOWN:
case ERROR:
break;
}
return retVal;
}
public String getFirmware()
{
String retVal = null;
switch( mMode )
{
case APPLICATION:
retVal = mConfig.substring( 9, 14 );
break;
case BOOTLOADER:
case UNKNOWN:
case ERROR:
break;
}
return retVal;
}
public String toString()
{
return getModel().getLabel();
}
}
public enum Mode
{
APPLICATION,
BOOTLOADER,
ERROR,
UNKNOWN;
public static Mode getMode( String config )
{
Mode retVal = UNKNOWN;
if( config == null )
{
retVal = ERROR;
}
else
{
if( config.length() >= 8 )
{
String mode = config.substring( 2, 8 ).trim();
if( mode.equalsIgnoreCase( "FCDAPP" ) )
{
retVal = APPLICATION;
}
else if( mode.equalsIgnoreCase( "FCDBL" ) )
{
retVal = BOOTLOADER;
}
}
}
return retVal;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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.jdesktop.swingx.input;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.geom.Point2D;
import org.jdesktop.swingx.JXMapViewer;
/**
* used to pan using the arrow keys
* @author joshy
*/
public class PanKeyListener extends KeyAdapter
{
private static final int OFFSET = 10;
private JXMapViewer viewer;
/**
* @param viewer the jxmapviewer
*/
public PanKeyListener(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void keyPressed(KeyEvent e)
{
int delta_x = 0;
int delta_y = 0;
int requestedZoom = 0;
switch ( e.getKeyCode() )
{
case KeyEvent.VK_LEFT:
case KeyEvent.VK_NUMPAD4:
delta_x = -OFFSET;
break;
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_NUMPAD6:
delta_x = OFFSET;
break;
case KeyEvent.VK_UP:
case KeyEvent.VK_NUMPAD8:
delta_y = -OFFSET;
break;
case KeyEvent.VK_DOWN:
case KeyEvent.VK_NUMPAD2:
delta_y = OFFSET;
break;
case KeyEvent.VK_MINUS:
case KeyEvent.VK_SUBTRACT:
requestedZoom = 1;
break;
case KeyEvent.VK_ADD:
case KeyEvent.VK_EQUALS:
requestedZoom = -1;
break;
}
if (delta_x != 0 || delta_y != 0)
{
Rectangle bounds = viewer.getViewportBounds();
double x = bounds.getCenterX() + delta_x;
double y = bounds.getCenterY() + delta_y;
viewer.setCenter(new Point2D.Double(x, y));
viewer.repaint();
}
if( requestedZoom != 0 )
{
int zoomLevel = viewer.getZoom() + requestedZoom;
viewer.setZoom( zoomLevel );
}
}
}
<file_sep>package source.recording;
import java.io.File;
import java.util.ArrayList;
import java.util.concurrent.RejectedExecutionException;
import source.SourceException;
import source.tuner.TunerChannel;
import source.tuner.TunerChannelProvider;
import source.tuner.TunerChannelSource;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.FrequencyChangeListener;
import source.tuner.frequency.FrequencyChangeEvent.Attribute;
import controller.ResourceManager;
import controller.ThreadPoolManager;
public class Recording implements Comparable<Recording>,
FrequencyChangeListener,
TunerChannelProvider
{
private ResourceManager mResourceManager;
private RecordingConfiguration mConfiguration;
private ArrayList<TunerChannelSource> mTunerChannels =
new ArrayList<TunerChannelSource>();
private long mCenterFrequency;
public Recording( ResourceManager resourceManager,
RecordingConfiguration configuration )
{
mResourceManager = resourceManager;
mConfiguration = configuration;
mCenterFrequency = mConfiguration.getCenterFrequency();
}
public void setAlias( String alias )
{
mConfiguration.setAlias( alias );
mResourceManager.getSettingsManager().save();
}
public void setRecordingFile( File file ) throws SourceException
{
if( hasChannels() )
{
throw new SourceException( "Recording source - can't change "
+ "recording file while channels are enabled against the "
+ "current recording." );
}
mConfiguration.setFilePath( file.getAbsolutePath() );
mResourceManager.getSettingsManager().save();
}
/**
* Indicates if this recording is currently playing/providing samples to
* tuner channel sources
*/
public boolean hasChannels()
{
return mTunerChannels.size() > 0;
}
@Override
public TunerChannelSource getChannel( ThreadPoolManager threadPoolManager,
TunerChannel channel ) throws RejectedExecutionException,
SourceException
{
// TODO Auto-generated method stub
return null;
}
@Override
public void releaseChannel( TunerChannelSource source )
{
// TODO Auto-generated method stub
}
public RecordingConfiguration getRecordingConfiguration()
{
return mConfiguration;
}
public String toString()
{
return mConfiguration.getAlias();
}
@Override
public void frequencyChanged( FrequencyChangeEvent event )
{
if( event.getAttribute() == Attribute.FREQUENCY )
{
long frequency = event.getValue().longValue();
mConfiguration.setCenterFrequency( frequency );
mResourceManager.getSettingsManager().save();
mCenterFrequency = frequency;
for( TunerChannelSource channel: mTunerChannels )
{
channel.frequencyChanged( event );
}
}
}
@Override
public int compareTo( Recording other )
{
return getRecordingConfiguration().getAlias()
.compareTo( other.getRecordingConfiguration().getAlias() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.mpt1327;
import java.awt.EventQueue;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import settings.ColorSetting;
import settings.Setting;
import alias.Alias;
import alias.AliasList;
import controller.channel.Channel;
import controller.state.ChannelState.ChangedAttribute;
import controller.state.ChannelStatePanel;
public class MPT1327Panel extends ChannelStatePanel
{
private static final long serialVersionUID = 1L;
private JLabel mProtocol;
private JLabel mSourceLabel;
private JLabel mChannelLabel;
private JLabel mStateLabel;
private JLabel mTalkgroup;
private JLabel mTalkgroupAlias;
private JLabel mSiteLabel;
private JLabel mSite;
private JLabel mSiteAliasLabel;
private MPT1327ChannelState mState;
private AliasList mAliasList;
public MPT1327Panel( Channel channel )
{
super( channel );
mState = (MPT1327ChannelState)channel.getProcessingChain().getChannelState();
mState.addListener( this );
mAliasList = mState.getAliasList();
init();
}
public void dispose()
{
super.dispose();
mState = null;
mAliasList = null;
}
public void init()
{
mProtocol = new JLabel( "MPT1327" );
mProtocol.setFont( mFontDecoder );
mProtocol.setForeground( mColorLabelDecoder );
mSourceLabel = new JLabel( mChannel.getSourceConfiguration().getDescription() );
mSourceLabel.setFont( mFontDetails );
mSourceLabel.setForeground( mColorLabelDetails );
mChannelLabel = new JLabel( mChannel.getChannelDisplayName() );
mChannelLabel.setFont( mFontDetails );
mChannelLabel.setForeground( mColorLabelDetails );
mStateLabel = new JLabel( mChannel.getProcessingChain().
getChannelState().getState().getDisplayValue() );
mStateLabel.setFont( mFontDecoder );
mStateLabel.setForeground( mColorLabelDecoder );
mTalkgroup = new JLabel( mState.getFromTalkgroup() );
mTalkgroup.setFont( mFontDecoder );
mTalkgroup.setForeground( mColorLabelDecoder );
mTalkgroupAlias = new JLabel();
mTalkgroupAlias.setFont( mFontDecoder );
mTalkgroupAlias.setForeground( mColorLabelDecoder );
Alias alias = getTalkgroupAlias( mState.getFromTalkgroup() );
if( alias != null )
{
mTalkgroupAlias.setText( alias.getName() );
mTalkgroupAlias.setIcon( getIcon( alias ) );
}
mSiteLabel = new JLabel( "Site:" );
mSiteLabel.setFont( mFontDetails );
mSiteLabel.setForeground( mColorLabelDetails );
mSite = new JLabel( String.valueOf( mState.getSite() ) );
mSite.setFont( mFontDecoder );
mSite.setForeground( mColorLabelDecoder );
mSiteAliasLabel = new JLabel();
mSiteAliasLabel.setFont( mFontDecoder );
mSiteAliasLabel.setForeground( mColorLabelDecoder );
Alias siteAlias = getSiteAlias( mState.getSite() );
if( siteAlias != null )
{
mSiteAliasLabel.setText( siteAlias.getName() );
}
add( mProtocol );
add( mSourceLabel );
add( mChannelLabel, "wrap" );
add( mStateLabel );
add( mTalkgroup );
add( mTalkgroupAlias, "wrap" );
add( mSiteLabel );
add( mSite );
add( mSiteAliasLabel, "wrap" );
}
@Override
public void receive( final ChangedAttribute changedAttribute )
{
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
switch( changedAttribute )
{
case CHANNEL_STATE:
mStateLabel.setText( mState.getState().getDisplayValue() );
break;
case CHANNEL_SITE_NUMBER:
mSite.setText( String.valueOf( mState.getSite() ) );
Alias siteAlias = getSiteAlias( mState.getSite() );
if( siteAlias != null )
{
mSiteAliasLabel.setText( siteAlias.getName() );
}
repaint();
break;
case FROM_TALKGROUP:
mTalkgroup.setText( mState.getFromTalkgroup() );
Alias alias = getTalkgroupAlias( mState.getFromTalkgroup() );
if( alias != null )
{
mTalkgroupAlias.setText( alias.getName() );
mTalkgroupAlias.setIcon( getIcon( alias ) );
}
repaint();
break;
}
}
} );
}
private ImageIcon getIcon( Alias alias )
{
if( alias != null )
{
String iconName = alias.getIconName();
if( iconName != null )
{
return getSettingsManager().getImageIcon( iconName, 12 );
}
}
return null;
}
private Alias getSiteAlias( String site )
{
if( site != null && mAliasList != null )
{
return mAliasList.getSiteID( site );
}
return null;
}
private Alias getTalkgroupAlias( String talkgroup )
{
if( talkgroup != null && mAliasList != null )
{
return mAliasList.getTalkgroupAlias( talkgroup );
}
return null;
}
@Override
public void trafficChannelAdded( Channel traffic )
{
if( !getTrafficPanels().keySet().contains( traffic ) )
{
MPT1327TrafficPanel panel =
new MPT1327TrafficPanel( traffic );
getTrafficPanels().put( traffic, panel );
addPanel( panel );
}
}
@Override
public void settingChanged( Setting setting )
{
super.settingChanged( setting );
if( setting instanceof ColorSetting )
{
ColorSetting colorSetting = (ColorSetting)setting;
switch( colorSetting.getColorSettingName() )
{
case CHANNEL_STATE_LABEL_DECODER:
if( mProtocol != null )
{
mProtocol.setForeground( mColorLabelDecoder );
}
if( mStateLabel != null )
{
mStateLabel.setForeground( mColorLabelDecoder );
}
if( mTalkgroup != null )
{
mTalkgroup.setForeground( mColorLabelDecoder );
}
if( mTalkgroupAlias != null )
{
mTalkgroupAlias.setForeground( mColorLabelDecoder );
}
if( mSite != null )
{
mSite.setForeground( mColorLabelDecoder );
}
if( mSiteAliasLabel != null )
{
mSiteAliasLabel.setForeground( mColorLabelDecoder );
}
break;
case CHANNEL_STATE_LABEL_DETAILS:
if( mSourceLabel != null )
{
mSourceLabel.setForeground( mColorLabelDetails );
}
if( mChannelLabel != null )
{
mChannelLabel.setForeground( mColorLabelDetails );
}
if( mSiteLabel != null )
{
mSiteLabel.setForeground( mColorLabelDetails );
}
break;
}
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.TreeNode;
public class BaseNode extends DefaultMutableTreeNode
implements Comparable<BaseNode>
{
private static final long serialVersionUID = 1L;
/**
* Model backing the JTree and nodes. Since we're primarily interacting
* with the model via JTree tree nodes via context menus, injecting a
* reference to the model facilitates nodal access to the model's methods
*/
protected ConfigurationControllerModel mModel = null;
/**
* Implements a base node that has a reference to the underlying
* tree data model to facilitate tree node operations from nodal context
* menus.
*/
public BaseNode( Object object )
{
super( object );
}
/**
* Override this method to return a custom icon for the node
* @return
*/
public String getIconPath()
{
return null;
}
public Color getBackgroundColor()
{
return null;
}
public String toString()
{
if( getUserObject() != null )
{
return (String)getUserObject();
}
else
{
return "SDRTrunk";
}
}
public JPanel getEditor()
{
return new EmptyEditor();
}
/**
* Comparator to support nodal sorting/ordering
*/
@Override
public int compareTo( BaseNode node )
{
return toString().compareTo( node.toString() );
}
/**
* This method only needs to be called once on the root node and all nodes
* in the tree will then have a reference to the model via getModel()
*/
public void setModel( ConfigurationControllerModel model )
{
mModel = model;
}
/**
* Returns reference to the SystemTreeModel. Only ConfigurableNode types
* or children are allowed in this tree, so this method assumes that the
* node or parent is of ConfigurableNode class or subclass.
*
* Reference to the model is required to enable node context operations
* like adding/deleting/stopping/starting.
*/
public ConfigurationControllerModel getModel()
{
if( mModel == null )
{
TreeNode parent = getParent();
if( parent != null )
{
return ((BaseNode)parent).getModel();
}
else
{
return null;
}
}
else
{
return mModel;
}
}
/**
* Supports a context menu for any children of the BaseNode. Override the
* method in the child node to provide a custom context menu for that node.
*/
public JPopupMenu getContextMenu()
{
return null;
}
/**
* Invokes a recursive delete() on all children to perform any cleanup
* operations prior to deleting. Override this method to perform cleanup
* operations specific to the node. Remember to also either invoke
* super.delete(), or specifically call .delete() on any children of the
* node with the custom delete method.
*/
public void delete()
{
for( int x = 0; x < getChildCount(); x++ )
{
BaseNode node = (BaseNode)getChildAt( x );
//Tell the node to delete its children
node.delete();
//Delete the child node
getModel().deleteNode( node );
}
}
public void show()
{
getModel().showNode( this );
}
public void refresh()
{
if( getModel() != null )
{
getModel().nodeChanged( this );
}
}
public void sort()
{
List<BaseNode> nodesToSort = new ArrayList<BaseNode>();
while( children().hasMoreElements() )
{
BaseNode child = (BaseNode)children().nextElement();
nodesToSort.add( child );
getModel().removeNodeFromParent( child );
}
if( !nodesToSort.isEmpty() )
{
Collections.sort( nodesToSort );
for( BaseNode node: nodesToSort )
{
getModel().insertNodeInto( node, this, getChildCount() );
}
}
}
}
<file_sep>package decode.p25.message.tsbk.motorola;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.reference.DataUnitID;
public class PatchGroupVoiceChannelGrant extends MotorolaTSBKMessage
implements IdentifierReceiver
{
/* Service Options */
public static final int EMERGENCY_FLAG = 80;
public static final int ENCRYPTED_CHANNEL_FLAG = 81;
public static final int DUPLEX_MODE = 82;
public static final int SESSION_MODE = 83;
public static final int[] PRIORITY = { 85,86,87 };
public static final int[] CHANNEL = { 88,89,90,91 };
public static final int[] IDENTIFIER = { 92,93,94,95,96,97,98,99,100,101,
102,103 };
public static final int[] PATCH_GROUP_ADDRESS = { 104,105,106,107,108,109,
110,111,112,113,114,115,116,117,118,119 };
public static final int[] SOURCE_ADDRESS = { 120,121,122,123,124,125,126,
127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 };
private IBandIdentifier mIdentifierUpdate;
public PatchGroupVoiceChannelGrant( BinaryMessage message, DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return MotorolaOpcode.PATCH_GROUP_CHANNEL_GRANT.getLabel();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
if( isEmergency() )
{
sb.append( " EMERGENCY" );
}
sb.append( " PATCH GROUP:" );
sb.append( getPatchGroupAddress() );
sb.append( " FROM:" );
sb.append( getSourceAddress() );
sb.append( " PRI:" );
sb.append( getPriority() );
sb.append( " CHAN:" );
sb.append( getChannelIdentifier() + "-" + getChannelNumber() );
sb.append( " DN:" + getDownlinkFrequency() );
sb.append( " UP:" + getUplinkFrequency() );
return sb.toString();
}
public String getPatchGroupAddress()
{
return mMessage.getHex( PATCH_GROUP_ADDRESS, 4 );
}
public String getSourceAddress()
{
return mMessage.getHex( SOURCE_ADDRESS, 6 );
}
public boolean isEmergency()
{
return mMessage.get( EMERGENCY_FLAG );
}
public boolean isEncryptedChannel()
{
return mMessage.get( ENCRYPTED_CHANNEL_FLAG );
}
public DuplexMode getDuplexMode()
{
return mMessage.get( DUPLEX_MODE ) ? DuplexMode.FULL : DuplexMode.HALF;
}
public SessionMode getSessionMode()
{
return mMessage.get( SESSION_MODE ) ?
SessionMode.CIRCUIT : SessionMode.PACKET;
}
/**
* 1 = Lowest, 4 = Default, 7 = Highest
*/
public int getPriority()
{
return mMessage.getInt( PRIORITY );
}
public int getChannelIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
public int getChannelNumber()
{
return mMessage.getInt( CHANNEL );
}
public String getChannel()
{
return getChannelIdentifier() + "-" + getChannelNumber();
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
mIdentifierUpdate = message;
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 1 ];
identifiers[ 0 ] = getChannelIdentifier();
return identifiers;
}
public long getDownlinkFrequency()
{
return calculateDownlink( mIdentifierUpdate, getChannelNumber() );
}
public long getUplinkFrequency()
{
return calculateUplink( mIdentifierUpdate, getChannelNumber() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller;
import alias.action.AliasActionManager;
import map.MapService;
import playlist.PlaylistManager;
import record.RecorderManager;
import settings.SettingsManager;
import source.SourceManager;
import source.recording.RecordingSourceManager;
import source.tuner.TunerManager;
import controller.channel.ChannelManager;
import eventlog.EventLogManager;
/**
* Manager for system wide resources
*/
public class ResourceManager
{
private ChannelManager mChannelManager;
private EventLogManager mEventLogManager;
private PlaylistManager mPlaylistManager;
private RecorderManager mRecorderManager;
private RecordingSourceManager mRecordingSourceManager;
private SettingsManager mSettingsManager;
private SourceManager mSourceManager;
private TunerManager mTunerManager;
private ConfigurationControllerModel mController;
private MapService mMapService;
private ThreadPoolManager mThreadPoolManager;
public ResourceManager()
{
this( new SettingsManager(),
new PlaylistManager(),
new EventLogManager(),
new RecorderManager() );
}
public ResourceManager( SettingsManager settingsManager,
PlaylistManager playlistManager,
EventLogManager eventLogManager,
RecorderManager recorderManager )
{
mSettingsManager = settingsManager;
mPlaylistManager = playlistManager;
mEventLogManager = eventLogManager;
mRecorderManager = recorderManager;
/**
* ChannelManager requires a reference to the ResourceManager so that
* channel processing chains can access system wide resources
*/
mChannelManager = new ChannelManager( this );
mSourceManager = new SourceManager( this );
mRecordingSourceManager = new RecordingSourceManager( this );
mTunerManager = new TunerManager( this );
mController = new ConfigurationControllerModel( this );
mMapService = new MapService( this );
mThreadPoolManager = new ThreadPoolManager();
}
public ConfigurationControllerModel getController()
{
return mController;
}
public ThreadPoolManager getThreadPoolManager()
{
return mThreadPoolManager;
}
public void setController( ConfigurationControllerModel controller )
{
mController = controller;
}
public TunerManager getTunerManager()
{
return mTunerManager;
}
public MapService getMapService()
{
return mMapService;
}
public SettingsManager getSettingsManager()
{
return mSettingsManager;
}
public void setSettingsManager( SettingsManager manager )
{
mSettingsManager = manager;
}
public PlaylistManager getPlaylistManager()
{
return mPlaylistManager;
}
public void setPlaylistManager( PlaylistManager aliasManager )
{
mPlaylistManager = aliasManager;
}
public EventLogManager getEventLogManager()
{
return mEventLogManager;
}
public void setEventLogManager( EventLogManager eventLogManager )
{
mEventLogManager = eventLogManager;
}
public RecorderManager getRecorderManager()
{
return mRecorderManager;
}
public void setRecorderManager( RecorderManager recorderManager )
{
mRecorderManager = recorderManager;
}
public SourceManager getSourceManager()
{
return mSourceManager;
}
public void setSourceManager( SourceManager sourceManager )
{
mSourceManager = sourceManager;
}
public RecordingSourceManager getRecordingSourceManager()
{
return mRecordingSourceManager;
}
public void setRecordingSourceManager( RecordingSourceManager manager )
{
mRecordingSourceManager = manager;
}
public ChannelManager getChannelManager()
{
return mChannelManager;
}
public void setChannelManager( ChannelManager channelManager )
{
mChannelManager = channelManager;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* Java port of librtlsdr <https://github.com/steve-m/librtlsdr>
*
* Copyright (C) 2013 <NAME> <<EMAIL>>
* Copyright (C) 2013 <NAME> <<EMAIL>>
*
* 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 source.tuner.rtl.r820t;
import java.nio.ByteBuffer;
import javax.swing.JPanel;
import javax.usb.UsbException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.LibUsbException;
import source.SourceException;
import source.tuner.TunerConfiguration;
import source.tuner.TunerType;
import source.tuner.rtl.RTL2832TunerController;
import controller.ResourceManager;
public class R820TTunerController extends RTL2832TunerController
{
private final static Logger mLog =
LoggerFactory.getLogger( R820TTunerController.class );
public static final long MIN_FREQUENCY = 3180000;
public static final long MAX_FREQUENCY = 1782030000;
public static final int R820T_IF_FREQUENCY = 3570000;
public static final byte VERSION = (byte)49;
public static final byte[] BIT_REV_LOOKUP_TABLE =
{ (byte)0x0, (byte)0x8, (byte)0x4, (byte)0xC,
(byte)0x2, (byte)0xA, (byte)0x6, (byte)0xE,
(byte)0x1, (byte)0x9, (byte)0x5, (byte)0xD,
(byte)0x3, (byte)0xB, (byte)0x7, (byte)0xF };
/* R820T I2C address */
private byte mI2CAddress = (byte)0x34;
/* Shadow register is used to keep a cached (in-memory) copy of all
* registers, so that we don't have to read a full byte from a register in
* order to apply a masked value and then re-write the full byte. With the
* shadow register, we can apply the masked value to the cached value, and
* then just write the masked byte, skipping the need to read the byte
* first. */
private int[] mShadowRegister =
{ 0x00, 0x00, 0x00, 0x00, 0x00, 0x83, 0x32, 0x75,
0xC0, 0x40, 0xD6, 0x6C, 0xF5, 0x63, 0x75, 0x68,
0x6C, 0x83, 0x80, 0x00, 0x0F, 0x00, 0xC0, 0x30,
0x48, 0xCC, 0x60, 0x00, 0x54, 0xAE, 0x4A, 0xC0 };
private JPanel mEditor;
public R820TTunerController( Device device,
DeviceDescriptor deviceDescriptor )
throws SourceException
{
super( device, deviceDescriptor, MIN_FREQUENCY, MAX_FREQUENCY );
}
@Override
public TunerType getTunerType()
{
return TunerType.RAFAELMICRO_R820T;
}
@Override
public void setSampleRateFilters( int sampleRate ) throws LibUsbException
{
//TODO: why is this being forced as an abstract method on sub classes?
}
@Override
public void apply( TunerConfiguration tunerConfig ) throws SourceException
{
if( tunerConfig != null &&
tunerConfig instanceof R820TTunerConfiguration )
{
R820TTunerConfiguration config = (R820TTunerConfiguration)tunerConfig;
try
{
SampleRate sampleRate = config.getSampleRate();
setSampleRate( sampleRate );
double correction = config.getFrequencyCorrection();
setFrequencyCorrection( correction );
R820TGain masterGain = config.getMasterGain();
setGain( masterGain, true );
if( masterGain == R820TGain.MANUAL )
{
R820TMixerGain mixerGain = config.getMixerGain();
setMixerGain( mixerGain, true );
R820TLNAGain lnaGain = config.getLNAGain();
setLNAGain( lnaGain, true );
R820TVGAGain vgaGain = config.getVGAGain();
setVGAGain( vgaGain, true );
}
}
catch( UsbException e )
{
throw new SourceException( "R820TTunerController - usb error "
+ "while applying tuner config", e );
}
}
}
/**
* Controller gui editor component for this tuner
*/
public JPanel getEditor( ResourceManager resourceManager )
{
if( mEditor == null )
{
mEditor = new R820TTunerEditorPanel( this, resourceManager );
}
return mEditor;
}
/**
* Not implemented.
*/
@Override
public long getTunedFrequency() throws SourceException
{
return 0;
}
/**
* Sets the center frequency. Setting the frequency is a two-part process
* of setting the multiplexer and then setting the Oscillator (PLL).
*/
@Override
public void setTunedFrequency( long frequency ) throws SourceException
{
try
{
enableI2CRepeater( mDeviceHandle, true );
boolean controlI2C = false;
long offsetFrequency = frequency + R820T_IF_FREQUENCY;
setMux( offsetFrequency, controlI2C );
setPLL( offsetFrequency, controlI2C );
enableI2CRepeater( mDeviceHandle, false );
}
catch( UsbException e )
{
throw new SourceException( "R820TTunerController - exception "
+ "while setting frequency [" + frequency + "] - " +
e.getLocalizedMessage() );
}
}
/**
* Overrides the same method from the RTL2832 tuner controller to apply
* settings specific to the R820T tuner.
*/
public void setSamplingMode( SampleMode mode ) throws LibUsbException
{
switch( mode )
{
case QUADRATURE:
/* Set intermediate frequency to R820T IF frequency */
setIFFrequency( R820T_IF_FREQUENCY );
/* Enable spectrum inversion */
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0x15,
(short)0x01,
1 );
/* Set default i/q path */
writeDemodRegister( mDeviceHandle,
Page.ZERO,
(short)0x06,
(short)0x80,
1 );
break;
default:
break;
}
}
/**
* Sets the multiplexer for the desired center frequency.
*/
private void setMux( long frequency, boolean controlI2C ) throws UsbException
{
FrequencyRange range = FrequencyRange.getRangeForFrequency( frequency );
/* Set open drain */
writeR820TRegister( Register.DRAIN, range.getOpenDrain(), controlI2C );
/* RF_MUX, Polymux */
writeR820TRegister( Register.RF_POLY_MUX, range.getRFMuxPolyMux(), controlI2C );
/* TF Band */
writeR820TRegister( Register.TF_BAND, range.getTFC(), controlI2C );
/* XTAL CAP & Drive */
writeR820TRegister( Register.PLL_XTAL_CAPACITOR_AND_DRIVE,
range.getXTALHighCap0P(), controlI2C );
/* Register 8 - what is it? */
writeR820TRegister( Register.UNKNOWN_REGISTER_8, (byte)0x00, controlI2C );
/* Register 9 - what is it? */
writeR820TRegister( Register.UNKNOWN_REGISTER_9, (byte)0x00, controlI2C );
}
/**
* Initializes the tuner for use.
*/
public void init() throws SourceException
{
/* Initialize the super class to open and claim the usb interface*/
super.init();
try
{
mLog.debug( "initializing RTL2832 tuner baseband" );
initBaseband( mDeviceHandle );
mLog.debug( "enabling I2C repeater" );
enableI2CRepeater( mDeviceHandle, true );
boolean i2CRepeaterControl = false;
mLog.debug( "initializing R820T tuner" );
initTuner( i2CRepeaterControl );
mLog.debug( "disabling I2C repeater" );
enableI2CRepeater( mDeviceHandle, false );
mLog.debug( "initializing RTL2832 tuner controller super class" );
}
catch( UsbException e )
{
throw new SourceException( "error during init()", e );
}
}
/**
* Initializes the tuner section.
*/
public void initTuner( boolean controlI2C ) throws UsbException
{
/* Disable zero IF mode */
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0xB1,
(short)0x1A,
1 );
/* Only enable in-phase ADC input */
writeDemodRegister( mDeviceHandle,
Page.ZERO,
(short)0x08,
(short)0x4D,
1 );
/* Set intermediate frequency to R820T IF frequency (3.57 MHz) */
setIFFrequency( R820T_IF_FREQUENCY );
/* Enable spectrum inversion */
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0x15,
(short)0x01,
1 );
initializeRegisters( controlI2C );
setTVStandard( controlI2C );
systemFrequencySelect( 0, controlI2C );
}
/**
* Partially implements the r82xx_set_tv_standard() method from librtlsdr.
* Sets standard to digital tv to support sdr operations only.
*/
private void setTVStandard( boolean controlI2C ) throws UsbException
{
/* Init Flag & Xtal check Result */
writeR820TRegister( Register.XTAL_CHECK, (byte)0x00, controlI2C );
/* Set version */
writeR820TRegister( Register.VERSION, VERSION, controlI2C );
/* LT Gain Test */
writeR820TRegister( Register.LNA_TOP, (byte)0x00, controlI2C );
int calibrationCode = 0;
for( int x = 0; x < 2; x++ )
{
/* Set filter cap */
writeR820TRegister( Register.FILTER_CAPACITOR, (byte)0x6B, controlI2C );
/* Set calibration clock on */
writeR820TRegister( Register.CALIBRATION_CLOCK, (byte)0x04, controlI2C );
/* XTAL capacitor 0pF for PLL */
writeR820TRegister( Register.PLL_XTAL_CAPACITOR, (byte)0x00, controlI2C );
setPLL( 56000 * 1000, controlI2C );
/* Start trigger */
writeR820TRegister( Register.CALIBRATION_TRIGGER, (byte)0x10, controlI2C );
/* Stop trigger */
writeR820TRegister( Register.CALIBRATION_TRIGGER, (byte)0x00, controlI2C );
/* Set calibration clock off */
writeR820TRegister( Register.CALIBRATION_CLOCK, (byte)0x00, controlI2C );
calibrationCode = getCalibrationCode( controlI2C );
if( !calibrationSuccessful( calibrationCode ) )
{
mLog.error( "Calibration NOT successful - code: " +
calibrationCode );
}
}
if( calibrationCode == 0x0F )
{
calibrationCode = 0;
}
/* Write calibration code */
byte filt_q = 0x10;
writeR820TRegister( Register.FILTER_CALIBRATION_CODE,
(byte)( calibrationCode | filt_q ), controlI2C );
/* Set BW, Filter gain & HP Corner */
writeR820TRegister( Register.BANDWIDTH_FILTER_GAIN_HIGHPASS_FILTER_CORNER,
(byte)0x6B, controlI2C );
/* Set Image_R */
writeR820TRegister( Register.IMAGE_REVERSE, (byte)0x00, controlI2C );
/* Set filter_3db, V6MHz */
writeR820TRegister( Register.FILTER_GAIN, (byte)0x10, controlI2C );
/* Channel filter extension */
writeR820TRegister( Register.CHANNEL_FILTER_EXTENSION, (byte)0x60, controlI2C );
/* Loop through */
writeR820TRegister( Register.LOOP_THROUGH, (byte)0x00, controlI2C );
/* Loop through attenuation */
writeR820TRegister( Register.LOOP_THROUGH_ATTENUATION, (byte)0x00, controlI2C );
/* Filter extension widest */
writeR820TRegister( Register.FILTER_EXTENSION_WIDEST, (byte)0x00, controlI2C );
/* RF poly filter current */
writeR820TRegister( Register.RF_POLY_FILTER_CURRENT, (byte)0x60, controlI2C );
}
/**
* Indicates if a calibration request was successful.
*/
private boolean calibrationSuccessful( int calibrationCode )
{
return calibrationCode != 0 && calibrationCode != 0x0F;
}
/**
* Returns the calibration code resulting from a calibration request.
*/
private int getCalibrationCode( boolean controlI2C ) throws UsbException
{
return getStatusRegister( 4, controlI2C ) & 0x0F;
}
/**
* Sets the system IF frequency
*/
private void systemFrequencySelect( long frequency, boolean controlI2C )
throws UsbException
{
/* LNA top? */
writeR820TRegister( Register.LNA_TOP2, (byte)0xE5, controlI2C );
byte mixer_top;
byte cp_cur;
byte div_buf_cur;
if( frequency == 506000000 ||
frequency == 666000000 ||
frequency == 818000000 )
{
mixer_top = (byte)0x14;
cp_cur = (byte)0x28;
div_buf_cur = (byte)0x20;
}
else
{
mixer_top = (byte)0x24;
cp_cur = (byte)0x38;
div_buf_cur = (byte)0x30;
}
writeR820TRegister( Register.MIXER_TOP, mixer_top, controlI2C );
writeR820TRegister( Register.LNA_VTH_L, (byte)0x53, controlI2C );
writeR820TRegister( Register.MIXER_VTH_L, (byte)0x75, controlI2C );
/* Air-In only for Astrometa */
writeR820TRegister( Register.AIR_CABLE1_INPUT_SELECTOR, (byte)0x00, controlI2C );
writeR820TRegister( Register.CABLE2_INPUT_SELECTOR, (byte)0x00, controlI2C );
writeR820TRegister( Register.CP_CUR, cp_cur, controlI2C );
writeR820TRegister( Register.DIVIDER_BUFFER_CURRENT, div_buf_cur, controlI2C );
writeR820TRegister( Register.FILTER_CURRENT, (byte)0x40, controlI2C );
/* if( type != TUNER_ANALOG_TV ) ... */
writeR820TRegister( Register.LNA_TOP, (byte)0x00, controlI2C );
writeR820TRegister( Register.MIXER_TOP2, (byte)0x00, controlI2C );
writeR820TRegister( Register.PRE_DETECT, (byte)0x00, controlI2C );
writeR820TRegister( Register.AGC_CLOCK, (byte)0x30, controlI2C );
writeR820TRegister( Register.LNA_TOP, (byte)0x18, controlI2C );
writeR820TRegister( Register.MIXER_TOP2, mixer_top, controlI2C );
/* LNA discharge current */
writeR820TRegister( Register.LNA_DISCHARGE_CURRENT, (byte)0x14, controlI2C );
/* AGC clock 1 khz, external det1 cap 1u */
writeR820TRegister( Register.AGC_CLOCK, (byte)0x20, controlI2C );
}
/**
* Sets the tuner's Phase-Locked-Loop (PLL) oscillator used for frequency
* (tuning) control
*
* @param frequency - desired center frequency
* @param controlI2C - control the I2C repeater locally
* @throws UsbException - if unable to set any of the R820T registers
*/
private void setPLL( long frequency, boolean controlI2C ) throws UsbException
{
/* Set reference divider to 0 */
writeR820TRegister( Register.REFERENCE_DIVIDER_2, (byte)0x00, controlI2C );
/* Set PLL autotune to 128kHz */
writeR820TRegister( Register.PLL_AUTOTUNE, (byte)0x00, controlI2C );
/* Set VCO current to 100 */
writeR820TRegister( Register.VCO_CURRENT, (byte)0x80, controlI2C );
/* Set the frequency divider - adjust for vco_fine_tune status */
FrequencyDivider divider = FrequencyDivider.fromFrequency( frequency );
int statusRegister4 = getStatusRegister( 4, controlI2C );
int vco_fine_tune = ( statusRegister4 & 0x30 ) >> 4;
int div_num = divider.getDividerNumber( vco_fine_tune );
writeR820TRegister( Register.DIVIDER, (byte)( div_num << 5 ), controlI2C );
/* Get the integral number for this divider and frequency */
Integral integral = divider.getIntegral( frequency );
writeR820TRegister( Register.PLL, integral.getRegisterValue(), controlI2C );
/* Calculate the sigma-delta modulator fractional setting. If it's
* non-zero, power up the sdm and apply the fractional setting,
* otherwise turn it off */
int sdm = divider.getSDM( integral, frequency );
if( sdm != 0 )
{
writeR820TRegister( Register.SIGMA_DELTA_MODULATOR_POWER,
(byte)0x00, controlI2C );
writeR820TRegister( Register.SIGMA_DELTA_MODULATOR_MSB,
(byte)( ( sdm >> 8 ) & 0xFF ), controlI2C );
writeR820TRegister( Register.SIGMA_DELTA_MODULATOR_LSB,
(byte)( sdm & 0xFF ), controlI2C );
}
else
{
writeR820TRegister( Register.SIGMA_DELTA_MODULATOR_POWER,
(byte)0x08, controlI2C );
}
/* Check to see if the PLL locked with these divider, integral and sdm
* settings */
if( !isPLLLocked( controlI2C ) )
{
/* Increase VCO current */
writeR820TRegister( Register.VCO_CURRENT, (byte)0x60, controlI2C );
if( !isPLLLocked( controlI2C ) )
{
throw new UsbException( "R820T Tuner Controller - couldn't "
+ "achieve PLL lock on frequency [" + frequency + "]" );
}
}
/* set pll autotune to 8kHz */
writeR820TRegister( Register.PLL_AUTOTUNE_VARIANT, (byte)0x08, controlI2C );
}
/**
* Indicates if the Phase Locked Loop (PLL) oscillator is locked following
* a change in the tuned center frequency. Checks status register 2 to see
* if the PLL locked indicator bit is set.
*/
private boolean isPLLLocked( boolean controlI2C ) throws UsbException
{
int register = getStatusRegister( 2, controlI2C );
return ( register & 0x40 ) == 0x40;
}
/**
* Writes initial starting value of registers 0x05 through 0x1F using the
* default value initialized in the shadow register array. This method only
* needs to be called once, upon initialization.
* @throws UsbException
*/
private void initializeRegisters( boolean controlI2C ) throws UsbException
{
for( int x = 5; x < mShadowRegister.length; x++ )
{
writeI2CRegister( mDeviceHandle,
mI2CAddress,
(byte)x,
(byte)mShadowRegister[ x ],
controlI2C );
}
}
/**
* Returns the contents of status registers 0 through 4
*/
private int getStatusRegister( int register, boolean controlI2C ) throws UsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 5 );
read( mDeviceHandle, mI2CAddress, Block.I2C, buffer );
return bitReverse( buffer.get( register ) & 0xFF );
}
/**
* Assumes value is a byte value and reverses the bits in the byte.
*/
private static int bitReverse( int value )
{
return BIT_REV_LOOKUP_TABLE[ value & 0x0F ] << 4 |
BIT_REV_LOOKUP_TABLE[ ( value & 0xF0 ) >> 4 ];
}
/**
* Writes the byte value to the specified register, optionally controlling
* the I2C repeater as needed.
*/
public void writeR820TRegister( Register register,
byte value,
boolean controlI2C ) throws UsbException
{
if( register.isMasked() )
{
int current = mShadowRegister[ register.getRegister() ];
value = (byte)( ( current & ~register.getMask() ) |
( value & register.getMask() ) );
}
writeI2CRegister( mDeviceHandle, mI2CAddress,
(byte)register.getRegister(), value, controlI2C );
mShadowRegister[ register.getRegister() ] = value;
// Log.info( "R820T writing register " +
// String.format( "%02X", register.getRegister() ) + " value " +
// String.format( "%02X", value ) );
}
/**
* Reads the specified register, optionally controlling the I2C repeater
*/
public int readR820TRegister( Register register, boolean controlI2C )
throws UsbException
{
int value = readI2CRegister( mDeviceHandle,
mI2CAddress,
(byte)register.getRegister(),
controlI2C );
return value;
}
/**
* Sets master gain by applying gain component values to LNA, Mixer and
* VGA gain registers.
*/
public void setGain( R820TGain gain, boolean controlI2C ) throws UsbException
{
setLNAGain( gain.getLNAGain(), controlI2C );
setMixerGain( gain.getMixerGain(), controlI2C );
setVGAGain( gain.getVGAGain(), controlI2C );
}
/**
* Sets LNA gain
*/
public void setLNAGain( R820TLNAGain gain, boolean controlI2C ) throws UsbException
{
writeR820TRegister( Register.LNA_GAIN, gain.getSetting(), controlI2C );
}
/**
* Sets Mixer gain
*/
public void setMixerGain( R820TMixerGain gain, boolean controlI2C ) throws UsbException
{
writeR820TRegister( Register.MIXER_GAIN, gain.getSetting(), controlI2C );
}
/**
* Sets VGA gain
*/
public void setVGAGain( R820TVGAGain gain, boolean controlI2C ) throws UsbException
{
writeR820TRegister( Register.VGA_GAIN, gain.getSetting(), controlI2C );
}
/**
* R820T VGA gain settings
*/
public enum R820TVGAGain
{
GAIN_0( "0", 0x00 ),
GAIN_26( "26", 0x01 ),
GAIN_52( "52", 0x02 ),
GAIN_82( "82", 0x03 ),
GAIN_124( "124", 0x04 ),
GAIN_159( "159", 0x05 ),
GAIN_183( "183", 0x06 ),
GAIN_196( "196", 0x07 ),
GAIN_210( "210", 0x08 ),
GAIN_242( "242", 0x09 ),
GAIN_278( "278", 0x0A ),
GAIN_312( "312", 0x0B ),
GAIN_347( "347", 0x0C ),
GAIN_384( "384", 0x0D ),
GAIN_419( "419", 0x0E ),
GAIN_455( "455", 0x0F );
private String mLabel;
private int mSetting;
private R820TVGAGain( String label, int setting )
{
mLabel = label;
mSetting = setting;
}
public String toString()
{
return mLabel;
}
public byte getSetting()
{
return (byte)mSetting;
}
}
/**
* R820T Low Noise Amplifier gain settings
*/
public enum R820TLNAGain
{
AUTOMATIC( "Automatic", 0x00 ),
GAIN_0( "0", 0x10 ),
GAIN_9( "9", 0x11 ),
GAIN_21( "21", 0x12 ),
GAIN_61( "61", 0x13 ),
GAIN_99( "99", 0x14 ),
GAIN_112( "112", 0x15 ),
GAIN_143( "143", 0x16 ),
GAIN_165( "165", 0x17 ),
GAIN_191( "191", 0x18 ),
GAIN_222( "222", 0x19 ),
GAIN_248( "248", 0x1A ),
GAIN_262( "262", 0x1B ),
GAIN_281( "281", 0x1C ),
GAIN_286( "286", 0x1D ),
GAIN_321( "321", 0x1E ),
GAIN_334( "334", 0x1F );
private String mLabel;
private int mSetting;
private R820TLNAGain( String label, int setting )
{
mLabel = label;
mSetting = setting;
}
public String toString()
{
return mLabel;
}
public byte getSetting()
{
return (byte)mSetting;
}
}
/**
* R820T mixer gain settings
*/
public enum R820TMixerGain
{
AUTOMATIC( "Automatic", 0x10 ),
GAIN_0( "0", 0x00 ),
GAIN_5( "5", 0x01 ),
GAIN_15( "15", 0x02 ),
GAIN_25( "25", 0x03 ),
GAIN_44( "44", 0x04 ),
GAIN_53( "53", 0x05 ),
GAIN_63( "63", 0x06 ),
GAIN_88( "88", 0x07 ),
GAIN_105( "105", 0x08 ),
GAIN_115( "115", 0x09 ),
GAIN_123( "123", 0x0A ),
GAIN_139( "139", 0x0B ),
GAIN_152( "152", 0x0C ),
GAIN_158( "158", 0x0D ),
GAIN_161( "161", 0x0E ),
GAIN_153( "153", 0x0F );
private String mLabel;
private int mSetting;
private R820TMixerGain( String label, int setting )
{
mLabel = label;
mSetting = setting;
}
public String toString()
{
return mLabel;
}
public byte getSetting()
{
return (byte)mSetting;
}
}
/**
* R820T Master gain settings
*/
public enum R820TGain
{
AUTOMATIC( "Automatic", R820TVGAGain.GAIN_312, R820TLNAGain.AUTOMATIC, R820TMixerGain.AUTOMATIC ),
MANUAL( "Manual", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_248, R820TMixerGain.GAIN_123 ),
GAIN_0( "0", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_0, R820TMixerGain.GAIN_0 ),
GAIN_9( "9", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_9, R820TMixerGain.GAIN_0 ),
GAIN_14( "14", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_9, R820TMixerGain.GAIN_5 ),
GAIN_26( "26", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_21, R820TMixerGain.GAIN_5 ),
GAIN_36( "36", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_21, R820TMixerGain.GAIN_15 ),
GAIN_76( "76", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_61, R820TMixerGain.GAIN_15 ),
GAIN_86( "86", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_61, R820TMixerGain.GAIN_25 ),
GAIN_124( "124", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_99, R820TMixerGain.GAIN_25 ),
GAIN_143( "143", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_99, R820TMixerGain.GAIN_44 ),
GAIN_156( "156", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_112, R820TMixerGain.GAIN_44 ),
GAIN_165( "165", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_112, R820TMixerGain.GAIN_53 ),
GAIN_196( "196", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_143, R820TMixerGain.GAIN_53 ),
GAIN_208( "208", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_143, R820TMixerGain.GAIN_63 ),
GAIN_228( "228", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_165, R820TMixerGain.GAIN_63 ),
GAIN_253( "253", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_165, R820TMixerGain.GAIN_88 ),
GAIN_279( "279", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_191, R820TMixerGain.GAIN_88 ),
GAIN_296( "296", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_191, R820TMixerGain.GAIN_105 ),
GAIN_327( "327", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_222, R820TMixerGain.GAIN_105 ),
GAIN_337( "337", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_222, R820TMixerGain.GAIN_115 ),
GAIN_363( "363", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_248, R820TMixerGain.GAIN_115 ),
GAIN_371( "371", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_248, R820TMixerGain.GAIN_123 ),
GAIN_385( "385", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_262, R820TMixerGain.GAIN_123 ),
GAIN_401( "401", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_262, R820TMixerGain.GAIN_139 ),
GAIN_420( "420", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_281, R820TMixerGain.GAIN_139 ),
GAIN_433( "433", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_281, R820TMixerGain.GAIN_152 ),
GAIN_438( "438", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_286, R820TMixerGain.GAIN_152 ),
GAIN_444( "444", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_286, R820TMixerGain.GAIN_158 ),
GAIN_479( "479", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_321, R820TMixerGain.GAIN_158 ),
GAIN_482( "482", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_321, R820TMixerGain.GAIN_161 ),
GAIN_495( "495", R820TVGAGain.GAIN_210, R820TLNAGain.GAIN_334, R820TMixerGain.GAIN_161 );
private String mLabel;
private R820TVGAGain mVGAGain;
private R820TLNAGain mLNAGain;
private R820TMixerGain mMixerGain;
private R820TGain( String label, R820TVGAGain vga, R820TLNAGain lna, R820TMixerGain mixer )
{
mLabel = label;
mVGAGain = vga;
mLNAGain = lna;
mMixerGain = mixer;
}
public String toString()
{
return mLabel;
}
public R820TVGAGain getVGAGain()
{
return mVGAGain;
}
public R820TLNAGain getLNAGain()
{
return mLNAGain;
}
public R820TMixerGain getMixerGain()
{
return mMixerGain;
}
}
/**
* R820T tuner registers and register mask values
*/
public enum Register
{
LNA_GAIN( 0x05, 0x1F ),
AIR_CABLE1_INPUT_SELECTOR( 0x05, 0x60 ),
LOOP_THROUGH( 0x05, 0x80 ),
CABLE2_INPUT_SELECTOR( 0x06, 0x08 ),
FILTER_GAIN( 0x06, 0x30 ),
PRE_DETECT( 0x06, 0x40 ),
MIXER_GAIN( 0x07, 0x1F ),
IMAGE_REVERSE( 0x07, 0x80 ),
UNKNOWN_REGISTER_8( 0x08, 0x3F ),
UNKNOWN_REGISTER_9( 0x09, 0x3F ),
FILTER_CALIBRATION_CODE( 0x0A, 0x1F ),
FILTER_CURRENT( 0x0A, 0x60 ),
CALIBRATION_TRIGGER( 0x0B, 0x10 ),
FILTER_CAPACITOR( 0x0B, 0x60 ),
BANDWIDTH_FILTER_GAIN_HIGHPASS_FILTER_CORNER( 0x0B, 0xEF ),
XTAL_CHECK( 0x0C, 0x0F ),
VGA_GAIN( 0x0C, 0x9F ),
LNA_VTH_L( 0x0D, 0x0 ),
MIXER_VTH_L( 0x0E, 0x0 ),
CALIBRATION_CLOCK( 0x0F, 0x04 ),
FILTER_EXTENSION_WIDEST( 0x0F, 0x80 ),
PLL_XTAL_CAPACITOR( 0x10, 0x03 ),
UNKNOWN_REGISTER_10( 0x10, 0x04 ),
PLL_XTAL_CAPACITOR_AND_DRIVE( 0x10, 0x0B ),
REFERENCE_DIVIDER_2( 0x10, 0x10 ),
CAPACITOR_SELECTOR( 0x10, 0x1B ),
DIVIDER( 0x10, 0xE0 ),
CP_CUR( 0x11, 0x38 ),
SIGMA_DELTA_MODULATOR_POWER( 0x12, 0x08 ),
VCO_CURRENT( 0x12, 0xE0 ),
VERSION( 0x13, 0x3F ),
PLL( 0x14, 0x0 ),
SIGMA_DELTA_MODULATOR_LSB( 0x15, 0x0 ),
SIGMA_DELTA_MODULATOR_MSB( 0x16, 0x0 ),
DRAIN( 0x17, 0x08 ),
DIVIDER_BUFFER_CURRENT( 0x17, 0x30 ),
RF_POLY_FILTER_CURRENT( 0x19, 0x60 ),
PLL_AUTOTUNE( 0x1A, 0x0C ),
PLL_AUTOTUNE_VARIANT( 0x1A, 0x08 ),
AGC_CLOCK( 0x1A, 0x30 ),
RF_POLY_MUX( 0x1A, 0xC3 ),
TF_BAND( 0x1B, 0x0 ),
MIXER_TOP( 0x1C, 0xF8 ),
MIXER_TOP2( 0X1C, 0x04 ),
LNA_TOP( 0x1D, 0x38 ),
LNA_TOP2( 0x1D, 0xC7 ),
CHANNEL_FILTER_EXTENSION( 0x1E, 0x60 ),
LNA_DISCHARGE_CURRENT( 0x1E, 0x1F ),
LOOP_THROUGH_ATTENUATION( 0x1F, 0x80 );
private int mRegister;
private int mMask;
private Register( int register, int mask )
{
mRegister = register;
mMask = mask;
}
public int getRegister()
{
return mRegister;
}
public byte getMask()
{
return (byte)mMask;
}
public boolean isMasked()
{
return mMask != 0;
}
}
public enum FrequencyRange
{
RANGE_024( 24000000, 49999999, 0x08, 0x02, 0xDF, 0x02, 0x01 ),
RANGE_050( 50000000, 54999999, 0x08, 0x02, 0xBE, 0x02, 0x01 ),
RANGE_055( 55000000, 59999999, 0x08, 0x02, 0x8B, 0x02, 0x01 ),
RANGE_060( 60000000, 64999999, 0x08, 0x02, 0x7B, 0x02, 0x01 ),
RANGE_065( 65000000, 69999999, 0x08, 0x02, 0x69, 0x02, 0x01 ),
RANGE_070( 70000000, 74999999, 0x08, 0x02, 0x58, 0x02, 0x01 ),
RANGE_075( 75000000, 79999999, 0x00, 0x02, 0x44, 0x02, 0x01 ),
RANGE_080( 80000000, 89999999, 0x00, 0x02, 0x44, 0x02, 0x01 ),
RANGE_090( 90000000, 99999999, 0x00, 0x02, 0x34, 0x01, 0x01 ),
RANGE_100( 100000000, 109999999, 0x00, 0x02, 0x34, 0x01, 0x01 ),
RANGE_110( 110000000, 119999999, 0x00, 0x02, 0x24, 0x01, 0x01 ),
RANGE_120( 120000000, 139999999, 0x00, 0x02, 0x24, 0x01, 0x01 ),
RANGE_140( 140000000, 179999999, 0x00, 0x02, 0x14, 0x01, 0x01 ),
RANGE_180( 180000000, 219999999, 0x00, 0x02, 0x13, 0x00, 0x00 ),
RANGE_220( 220000000, 249999999, 0x00, 0x02, 0x13, 0x00, 0x00 ),
RANGE_250( 250000000, 279999999, 0x00, 0x02, 0x11, 0x00, 0x00 ),
RANGE_280( 280000000, 309999999, 0x00, 0x02, 0x00, 0x00, 0x00 ),
RANGE_310( 310000000, 449999999, 0x00, 0x41, 0x00, 0x00, 0x00 ),
RANGE_450( 450000000, 587999999, 0x00, 0x41, 0x00, 0x00, 0x00 ),
RANGE_588( 588000000, 649999999, 0x00, 0x40, 0x00, 0x00, 0x00 ),
RANGE_650( 650000000, 1766000000, 0x00, 0x40, 0x00, 0x00, 0x00 ),
RANGE_UNK( 0, 0, 0, 0, 0, 0, 0 );
private long mMinFrequency;
private long mMaxFrequency;
private int mOpenDrain;
private int mRFMux_PolyMux;
private int mTF_c;
private int mXtalCap20p;
private int mXtalCap10p;
private FrequencyRange( long minFrequency,
long maxFrequency,
int openDrain,
int rfMuxPloy,
int tf_c,
int xtalCap20p,
int xtalCap10p )
{
mMinFrequency = minFrequency;
mMaxFrequency = maxFrequency;
mOpenDrain = openDrain;
mRFMux_PolyMux = rfMuxPloy;
mTF_c = tf_c;
mXtalCap20p = xtalCap20p;
mXtalCap10p = xtalCap10p;
}
public boolean contains( long frequency )
{
return mMinFrequency <= frequency && frequency <= mMaxFrequency;
}
public static FrequencyRange getRangeForFrequency( long frequency )
{
for( FrequencyRange range: values() )
{
if( range.contains( frequency ) )
{
return range;
}
}
return RANGE_UNK;
}
public long getMinFrequency()
{
return mMinFrequency;
}
public long getMaxFrequency()
{
return mMaxFrequency;
}
public byte getOpenDrain()
{
return (byte)mOpenDrain;
}
public byte getRFMuxPolyMux()
{
return (byte)mRFMux_PolyMux;
}
public byte getTFC()
{
return (byte) mTF_c;
}
public byte getXTALCap20P()
{
return (byte)mXtalCap20p;
}
public byte getXTALCap10P()
{
return (byte)mXtalCap10p;
}
public byte getXTALLowCap0P()
{
return (byte)0x08;
}
public byte getXTALHighCap0P()
{
return (byte)0x00;
}
}
/**
* Frequency Divider Ranges
*
* Actual Tuned Frequency Ranges (after subtracting IF = 3.57 MHz )
*
* Divider 0: 860.43 to 1782.03 MHz
* Divider 1: 428.43 to 889.23 MHz
* Divider 2: 212.43 to 457.23 MHz
* Divider 3: 104.43 to 219.63 MHz
* Divider 4: 50.43 to 108.03 MHz
* Divider 5: 23.43 to 52.23 MHz
* Divider 6: 9.93 to 24.33 MHz
* Divider 7: 3.18 to 10.38 MHz
*/
public enum FrequencyDivider
{
DIVIDER_0( 0, 2, 864000000, 1785600000, 0x00, 28800000 ),
DIVIDER_1( 1, 4, 432000000, 892800000, 0x20, 14400000 ),
DIVIDER_2( 2, 8, 216000000, 460800000, 0x40, 7200000 ),
DIVIDER_3( 3, 16, 108000000, 223200000, 0x60, 3600000 ),
DIVIDER_4( 4, 32, 54000000, 111600000, 0x80, 1800000 ),
DIVIDER_5( 5, 64, 27000000, 55800000, 0xA0, 900000 ),
DIVIDER_6( 6, 128, 13500000, 27900000, 0xC0, 450000 ),
DIVIDER_7( 7, 256, 6750000, 13950000, 0xE0, 225000 );
private int mDividerNumber;
private int mMixerDivider;
private long mMinimumFrequency;
private long mMaximumFrequency;
private int mRegisterSetting;
private int mIntegralValue;
private static final int mVCOPowerReference = 2;
private FrequencyDivider( int dividerNumber,
int mixerDivider,
long minimumFrequency,
long maximumFrequency,
int registerSetting,
int integralValue )
{
mDividerNumber = dividerNumber;
mMixerDivider = mixerDivider;
mMinimumFrequency = minimumFrequency;
mMaximumFrequency = maximumFrequency;
mRegisterSetting = registerSetting;
mIntegralValue = integralValue;
}
public int getDividerNumber( int vcoFineTune )
{
if( vcoFineTune == mVCOPowerReference )
{
return mDividerNumber;
}
else if( vcoFineTune < mVCOPowerReference )
{
return mDividerNumber - 1;
}
else if( vcoFineTune > mVCOPowerReference )
{
return mDividerNumber + 1;
}
return mDividerNumber;
}
public int getMixerDivider()
{
return mMixerDivider;
}
public long getMinimumFrequency()
{
return mMinimumFrequency;
}
public long getMaximumFrequency()
{
return mMaximumFrequency;
}
public byte getDividerRegisterSetting()
{
return (byte)mRegisterSetting;
}
public boolean contains( long frequency )
{
return mMinimumFrequency <= frequency &&
frequency <= mMaximumFrequency;
}
/**
* Returns the correct frequency divider for the specified frequency,
* or returns divider #5, if the frequency is outside of the specified
* frequency ranges.
* @param frequency - desired frequency
* @return - FrequencyDivider to use for the specified frequency
*/
public static FrequencyDivider fromFrequency( long frequency )
{
for( FrequencyDivider divider: FrequencyDivider.values() )
{
if( divider.contains( frequency ) )
{
return divider;
}
}
return FrequencyDivider.DIVIDER_5;
}
/**
* Returns the integral to use for this frequency and divider
*/
public Integral getIntegral( long frequency )
{
if( contains( frequency ) )
{
int delta = (int)( frequency - mMinimumFrequency );
int integral = (int)( (double)delta / (double)mIntegralValue );
return Integral.fromValue( integral );
}
throw new IllegalArgumentException( "PLL frequency [" + frequency +
"] is not valid for this frequency divider " + this.toString() );
}
/**
* Calculates the 16-bit value of the sigma-delta modulator setting
* which represents the fractional portion of the requested frequency
* that is left over after subtracting the divider minimum frequency
* and the integral frequency units. That residual value is divided
* by the integral unit value to derive a 16-bit fractional value,
* returned as an integer
*/
public int getSDM( Integral integral, long frequency )
{
if( contains( frequency ) )
{
int delta = (int)( frequency - mMinimumFrequency -
( integral.getNumber() * mIntegralValue ) );
double fractional = (double)delta / (double)mIntegralValue;
//Left shift the double value 16 bits and truncate to an integer
return (int)( fractional * 0x10000 ) & 0xFFFF;
}
return 0;
}
}
/**
* PLL Integral values. Each value represents one unit of the divided
* crystal frequency as follows:
*
* Divider Value
* 64 I * 0.9 MHz
* 32 I * 1.8 MHz
* 16 I * 3.6 MHz
* 8 I * 7.2 MHz
* 4 I * 14.4 MHz
* 2 I * 28.8 MHz
*
*/
public enum Integral
{
I00( 0, 0x44 ),
I01( 1, 0x84 ),
I02( 2, 0xC4 ),
I03( 3, 0x05 ),
I04( 4, 0x45 ),
I05( 5, 0x85 ),
I06( 6, 0xC5 ),
I07( 7, 0x06 ),
I08( 8, 0x46 ),
I09( 9, 0x86 ),
I10( 10, 0xC6 ),
I11( 11, 0x07 ),
I12( 12, 0x47 ),
I13( 13, 0x87 ),
I14( 14, 0xC7 ),
I15( 15, 0x08 ),
I16( 16, 0x48 ),
I17( 17, 0x88 ),
I18( 18, 0xC8 ),
I19( 19, 0x09 ),
I20( 20, 0x49 ),
I21( 21, 0x89 ),
I22( 22, 0xC9 ),
I23( 23, 0x0A ),
I24( 24, 0x4A ),
I25( 25, 0x8A ),
I26( 26, 0xCA ),
I27( 27, 0x0B ),
I28( 28, 0x4B ),
I29( 29, 0x8B ),
I30( 30, 0xCB ),
I31( 31, 0x0C );
private int mNumber;
private int mRegister;
private Integral( int number, int register )
{
mNumber = number;
mRegister = register;
}
public int getNumber()
{
return mNumber;
}
public byte getRegisterValue()
{
return (byte)mRegister;
}
public static Integral fromValue( int value )
{
if( 0 <= value && value <= 31 )
{
return Integral.values()[ value ];
}
throw new IllegalArgumentException( "PLL integral value [" + value +
"] must be in the range 0 - 31");
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.mixer;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import sample.adapter.SampleAdapter;
import sample.complex.ComplexBuffer;
import sample.complex.ComplexSample;
import source.SourceException;
public class ComplexMixer
{
private final static Logger mLog =
LoggerFactory.getLogger( ComplexMixer.class );
private long mFrequency = 0;
private int mBufferSize = 16384;
private BufferReader mBufferReader = new BufferReader();
private TargetDataLine mTargetDataLine;
private AudioFormat mAudioFormat;
private String mName;
private int mBytesPerFrame = 0;
private SampleAdapter mSampleAdapter;
private Listener<ComplexBuffer> mListener;
/**
* Complex Mixer - constructs a reader on the mixer/sound card target
* data line using the specified audio format (sample size, sample rate )
* and broadcasts complex (I/Q) sample buffers to all registered listeners.
* Reads sample buffers sized to 10% of the sample rate specified in audio
* format.
*
* @param targetDataLine - mixer or sound card to be used
*
* @param format - audio format
*
* @param name - token name to use for this mixer
*
* @param sampleAdapter - adapter to convert byte array data read from the
* mixer into ComplexBuffer. The adapter can optionally invert the channel
* data if the left/right stereo channels are inverted.
*/
public ComplexMixer( TargetDataLine targetDataLine,
AudioFormat format,
String name,
SampleAdapter sampleAdapter,
Listener<ComplexBuffer> listener )
{
mTargetDataLine = targetDataLine;
mName = name;
mAudioFormat = format;
mSampleAdapter = sampleAdapter;
mListener = listener;
}
public TargetDataLine getTargetDataLine()
{
return mTargetDataLine;
}
public void start()
{
if( !mBufferReader.isRunning() )
{
Thread thread = new Thread( mBufferReader );
thread.setDaemon( true );
thread.setName( mName + " Complex Sample Reader" );
thread.start();
}
}
public void stop()
{
mBufferReader.stop();
}
private List<ComplexSample> convert( ComplexBuffer sampleBuffer )
{
float[] samples = sampleBuffer.getSamples();
ArrayList<ComplexSample> converted = new ArrayList<ComplexSample>();
for( int x = 0; x < samples.length; x += 2 )
{
converted.add( new ComplexSample( samples[ x ], samples[ x + 1 ] ) );
}
sampleBuffer.dispose();
return converted;
}
@Override
public String toString()
{
return mName;
}
public int getSampleRate()
{
if( mTargetDataLine != null )
{
return (int)mTargetDataLine.getFormat().getSampleRate();
}
else
{
return 0;
}
}
/**
* Returns the frequency of this source. Default is 0.
*/
public long getFrequency() throws SourceException
{
return mFrequency;
}
/**
* Specify the frequency that will be returned from this source. This may
* be useful if you are streaming an external audio source in through the
* sound card and you want to specify a frequency for that source
*/
public void setFrequency( long frequency )
{
mFrequency = frequency;
}
/**
* Reader thread. Performs blocking read against the mixer target data
* line, converts the samples to an array of floats using the specified
* adapter. Dispatches float arrays to all registered listeners.
*/
public class BufferReader implements Runnable
{
private AtomicBoolean mRunning = new AtomicBoolean();
@Override
public void run()
{
if( mRunning.compareAndSet( false, true ) )
{
if( mTargetDataLine == null )
{
mRunning.set( false );
mLog.error( "ComplexMixerSource - mixer target data line"
+ " is null" );
}
else
{
mBytesPerFrame = mAudioFormat.getSampleSizeInBits() / 8;
if( mBytesPerFrame == AudioSystem.NOT_SPECIFIED )
{
mBytesPerFrame = 2;
}
/* Set buffer size to 1/10 second of samples */
mBufferSize = (int)( mAudioFormat.getSampleRate()
* 0.05 ) * mBytesPerFrame;
/* We'll reuse the same buffer for each read */
byte[] buffer = new byte[ mBufferSize ];
try
{
mTargetDataLine.open( mAudioFormat );
mTargetDataLine.start();
}
catch ( LineUnavailableException e )
{
mLog.error( "ComplexMixerSource - mixer target data line"
+ "not available to read data from", e );
mRunning.set( false );
}
while( mRunning.get() )
{
try
{
/* Blocking read - waits until the buffer fills */
mTargetDataLine.read( buffer, 0, buffer.length );
/* Convert samples to float array */
float[] samples =
mSampleAdapter.convert( buffer );
/* Dispatch samples to registered listeners */
if( mListener != null )
{
mListener.receive( new ComplexBuffer( samples ) );
}
}
catch ( Exception e )
{
mLog.error( "error while reading"
+ "from the mixer target data line", e );
mRunning.set( false );
}
}
}
/* Close the data line if it is still open */
if( mTargetDataLine != null && mTargetDataLine.isOpen() )
{
mTargetDataLine.close();
}
}
}
/**
* Stops the reader thread
*/
public void stop()
{
if( mRunning.compareAndSet( true, false ) )
{
mTargetDataLine.stop();
mTargetDataLine.close();
}
}
/**
* Indicates if the reader thread is running
*/
public boolean isRunning()
{
return mRunning.get();
}
}
public void dispose()
{
if( mBufferReader != null )
{
mBufferReader.stop();
}
mListener = null;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.hackrf;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.JToggleButton;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.usb.UsbException;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.SourceException;
import source.tuner.TunerConfiguration;
import source.tuner.TunerConfigurationAssignment;
import source.tuner.TunerType;
import source.tuner.hackrf.HackRFTunerController.HackRFLNAGain;
import source.tuner.hackrf.HackRFTunerController.HackRFSampleRate;
import source.tuner.hackrf.HackRFTunerController.HackRFVGAGain;
import controller.ResourceManager;
public class HackRFTunerConfigurationPanel extends JPanel
{
private final static Logger mLog =
LoggerFactory.getLogger( HackRFTunerConfigurationPanel.class );
private static final long serialVersionUID = 1L;
private ResourceManager mResourceManager;
private HackRFTunerController mController;
private HackRFTunerConfiguration mSelectedConfig;
private JButton mNewConfiguration;
private JButton mDeleteConfiguration;
private JComboBox<HackRFTunerConfiguration> mComboConfigurations;
private JTextField mName;
private JSpinner mFrequencyCorrection;
private JToggleButton mAmplifier;
private JComboBox<HackRFLNAGain> mComboLNAGain;
private JComboBox<HackRFVGAGain> mComboVGAGain;
private JComboBox<HackRFSampleRate> mComboSampleRate;
public HackRFTunerConfigurationPanel( ResourceManager resourceManager,
HackRFTunerController controller )
{
mResourceManager = resourceManager;
mController = controller;
init();
}
/**
* Initializes the gui components
*/
private void init()
{
setLayout( new MigLayout( "fill,wrap 2", "[grow,right][grow]", "[][][][][][][grow]" ) );
/**
* Tuner configuration selector
*/
mComboConfigurations = new JComboBox<HackRFTunerConfiguration>();
mComboConfigurations.setModel( getModel() );
/* Determine which tuner configuration should be selected/displayed */
TunerConfigurationAssignment savedConfig = null;
String serial = null;
try
{
serial = mController.getSerial().getSerialNumber();
}
catch ( UsbException e2 )
{
mLog.error( "couldn't read hackrf serial number", e2 );
}
if( serial != null )
{
savedConfig = mResourceManager
.getSettingsManager().getSelectedTunerConfiguration(
TunerType.HACKRF, serial );
}
if( savedConfig != null )
{
mSelectedConfig = getNamedConfiguration(
savedConfig.getTunerConfigurationName() );
}
/* If we couldn't determine the saved/selected config, use the first one */
if( mSelectedConfig == null )
{
mSelectedConfig = mComboConfigurations.getItemAt( 0 );
//Store this config as the default for this tuner at this address
if( serial != null )
{
mResourceManager.getSettingsManager()
.setSelectedTunerConfiguration( TunerType.HACKRF,
serial, mSelectedConfig );
}
}
mComboConfigurations.setSelectedItem( mSelectedConfig );
mComboConfigurations.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
HackRFTunerConfiguration selected =
(HackRFTunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
update( selected );
}
}
});
add( new JLabel( "Config:" ) );
add( mComboConfigurations, "growx,push" );
/**
* Tuner Configuration Name
*/
mName = new JTextField();
mName.setText( mSelectedConfig.getName() );
mName.addFocusListener( new FocusListener()
{
@Override
public void focusLost( FocusEvent e )
{
mSelectedConfig.setName( mName.getText() );
save();
}
@Override
public void focusGained( FocusEvent e ) {}
} );
add( new JLabel( "Name:" ) );
add( mName, "growx,push" );
/**
* Frequency Correction
*/
SpinnerModel model =
new SpinnerNumberModel( 0.0, //initial value
-1000.0, //min
1000.0, //max
0.1 ); //step
mFrequencyCorrection = new JSpinner( model );
JSpinner.NumberEditor editor =
(JSpinner.NumberEditor)mFrequencyCorrection.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits( 1 );
editor.getTextField().setHorizontalAlignment( SwingConstants.CENTER );
mFrequencyCorrection.setValue( mSelectedConfig.getFrequencyCorrection() );
mFrequencyCorrection.addChangeListener( new ChangeListener()
{
@Override
public void stateChanged( ChangeEvent e )
{
final double value = ((SpinnerNumberModel)mFrequencyCorrection
.getModel()).getNumber().doubleValue();
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
mController.setFrequencyCorrection( value );
mSelectedConfig.setFrequencyCorrection( value );
save();
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
HackRFTunerConfigurationPanel.this,
"HackRF Tuner Controller - couldn't apply "
+ "frequency correction value: " + value +
e1.getLocalizedMessage() );
mLog.error( "HackRF Tuner Controller - couldn't apply "
+ "frequency correction value: " + value, e1 );
}
}
} );
}
} );
add( new JLabel( "Correction PPM:" ) );
add( mFrequencyCorrection, "growx,push" );
/**
* Sample Rate
*/
mComboSampleRate = new JComboBox<>( HackRFSampleRate.values() );
mComboSampleRate.setSelectedItem( mSelectedConfig.getSampleRate() );
mComboSampleRate.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
HackRFSampleRate sampleRate =
(HackRFSampleRate)mComboSampleRate.getSelectedItem();
try
{
mController.setSampleRate( sampleRate );
mSelectedConfig.setSampleRate( sampleRate );
save();
}
catch ( UsbException e2 )
{
JOptionPane.showMessageDialog(
HackRFTunerConfigurationPanel.this,
"HackRF Tuner Controller - couldn't apply the sample "
+ "rate setting [" + sampleRate.getLabel() + "] " +
e2.getLocalizedMessage() );
mLog.error( "HackRF Tuner Controller - couldn't apply sample "
+ "rate setting [" + sampleRate.getLabel() + "]", e );
}
}
} );
add( new JLabel( "Sample Rate:" ) );
add( mComboSampleRate, "growx,push" );
/**
* Gain Controls
*/
JPanel gainPanel = new JPanel();
gainPanel.setLayout( new MigLayout( "",
"[][right][grow,fill][right][grow,fill]", "[grow,fill]" ) );
gainPanel.setBorder( BorderFactory.createTitledBorder( "Gain" ) );
/* Amplifier */
mAmplifier = new JToggleButton( "Amp" );
mAmplifier.setSelected( mSelectedConfig.getAmplifierEnabled() );
mAmplifier.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
mController.setAmplifierEnabled( mAmplifier.isSelected() );
mSelectedConfig.setAmplifierEnabled( mAmplifier.isSelected() );
save();
}
catch ( UsbException e )
{
mLog.error( "couldn't enable/disable amplifier", e );
mAmplifier.setEnabled( !mAmplifier.isSelected() );
JOptionPane.showMessageDialog(
HackRFTunerConfigurationPanel.this,
"Couldn't change amplifier setting",
"Error changing amplifier setting",
JOptionPane.ERROR_MESSAGE );
}
}
} );
gainPanel.add( mAmplifier );
/* LNA Gain Control */
mComboLNAGain = new JComboBox<HackRFLNAGain>( HackRFLNAGain.values() );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
mComboLNAGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
HackRFLNAGain lnaGain =
(HackRFLNAGain)mComboLNAGain.getSelectedItem();
if ( lnaGain == null )
{
lnaGain = HackRFLNAGain.GAIN_0;
}
if( mComboLNAGain.isEnabled() )
{
mController.setLNAGain( lnaGain );
}
mSelectedConfig.setLNAGain( lnaGain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
HackRFTunerConfigurationPanel.this,
"HackRF Tuner Controller - couldn't apply the LNA "
+ "gain setting - " + e.getLocalizedMessage() );
mLog.error( "HackRF Tuner Controller - couldn't apply LNA "
+ "gain setting - ", e );
}
}
} );
mComboLNAGain.setToolTipText( "<html>LNA Gain. Adjust to set "
+ "the IF gain</html>" );
gainPanel.add( new JLabel( "LNA" ) );
gainPanel.add( mComboLNAGain );
/* VGA Gain Control */
mComboVGAGain = new JComboBox<HackRFVGAGain>( HackRFVGAGain.values() );
mComboVGAGain.setSelectedItem( mSelectedConfig.getVGAGain() );
mComboVGAGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
HackRFVGAGain vgaGain = (HackRFVGAGain)mComboVGAGain.getSelectedItem();
if( vgaGain == null )
{
vgaGain = HackRFVGAGain.GAIN_4;
}
if( mComboVGAGain.isEnabled() )
{
mController.setVGAGain( vgaGain );
}
mSelectedConfig.setVGAGain( vgaGain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
HackRFTunerConfigurationPanel.this,
"HackRF Tuner Controller - couldn't apply the VGA "
+ "gain setting - " + e.getLocalizedMessage() );
mLog.error( "HackRF Tuner Controller - couldn't apply VGA "
+ "gain setting", e );
}
}
} );
mComboVGAGain.setToolTipText( "<html>VGA Gain. Adjust to set the "
+ "baseband gain</html>" );
gainPanel.add( new JLabel( "VGA" ) );
gainPanel.add( mComboVGAGain, "wrap" );
add( gainPanel, "span,growx" );
/**
* Create a new configuration
*/
mNewConfiguration = new JButton( "New" );
mNewConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
TunerConfiguration config =
mResourceManager.getSettingsManager()
.addNewTunerConfiguration(
TunerType.HACKRF,
"New Configuration" );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedItem( config );
repaint();
}
} );
add( mNewConfiguration, "growx,push" );
/**
* Delete the currently selected configuration
*/
mDeleteConfiguration = new JButton( "Delete" );
mDeleteConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
HackRFTunerConfiguration selected =
(HackRFTunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
int n = JOptionPane.showConfirmDialog(
HackRFTunerConfigurationPanel.this,
"Are you sure you want to delete '"
+ selected.getName() + "'?",
"Are you sure?",
JOptionPane.YES_NO_OPTION );
if( n == JOptionPane.YES_OPTION )
{
mResourceManager.getSettingsManager()
.deleteTunerConfiguration( selected );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedIndex( 0 );
repaint();
}
}
}
} );
add( mDeleteConfiguration, "growx,push,wrap" );
}
/**
* Updates gui controls with the values from the tuner configuration
* @param config - tuner configuration
*/
private void update( HackRFTunerConfiguration config )
{
mSelectedConfig = config;
try
{
mController.apply( config );
mName.setText( config.getName() );
mFrequencyCorrection.setValue( config.getFrequencyCorrection() );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
mComboVGAGain.setSelectedItem( mSelectedConfig.getVGAGain() );
mComboSampleRate.setSelectedItem( mSelectedConfig.getSampleRate() );
mResourceManager.getSettingsManager().setSelectedTunerConfiguration(
TunerType.HACKRF, mController.getSerial().getSerialNumber(), config );
}
catch ( UsbException | SourceException e1 )
{
JOptionPane.showMessageDialog(
HackRFTunerConfigurationPanel.this,
"HackRF Tuner Controller - couldn't "
+ "apply the tuner configuration settings - " +
e1.getLocalizedMessage() );
mLog.error( "HackRF Tuner Controller - couldn't apply "
+ "config [" + config.getName() + "]", e1 );
}
}
/**
* Constructs a combo box model for the tuner configuration combo component
* by assembling a list of the tuner configurations appropriate for this
* specific tuner
*/
private ComboBoxModel<HackRFTunerConfiguration> getModel()
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.HACKRF );
DefaultComboBoxModel<HackRFTunerConfiguration> model =
new DefaultComboBoxModel<HackRFTunerConfiguration>();
for( TunerConfiguration config: configs )
{
model.addElement( (HackRFTunerConfiguration)config );
}
return model;
}
/**
* Retrieves a specific (named) tuner configuration
*/
private HackRFTunerConfiguration getNamedConfiguration( String name )
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.HACKRF );
for( TunerConfiguration config: configs )
{
if( config.getName().contentEquals( name ) )
{
return (HackRFTunerConfiguration)config;
}
}
return null;
}
/**
* Saves current tuner configuration settings
*/
private void save()
{
mResourceManager.getSettingsManager().save();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.ltrnet;
import instrument.Instrumentable;
import instrument.tap.Tap;
import java.util.ArrayList;
import java.util.List;
import message.MessageDirection;
import sample.real.RealSampleListener;
import source.Source.SampleType;
import alias.AliasList;
import audio.AudioOutputImpl;
import audio.IAudioOutput;
import bits.MessageFramer;
import bits.SyncPattern;
import decode.Decoder;
import decode.DecoderType;
import decode.config.DecodeConfiguration;
import dsp.filter.DCRemovalFilter2;
import dsp.fsk.LTRFSKDecoder;
import dsp.nbfm.FilteringNBFMDemodulator;
public class LTRNetDecoder extends Decoder implements Instrumentable
{
/**
* This value determines how quickly the DC remove filter responds to
* changes in frequency.
*/
private static final double sDC_REMOVAL_RATIO = 0.000003;
public static final int sLTR_STANDARD_MESSAGE_LENGTH = 40;
private FilteringNBFMDemodulator mDemodulator;
private DCRemovalFilter2 mDCRemovalFilter;
private LTRFSKDecoder mLTRFSKDecoder;
private MessageFramer mLTRMessageFramer;
private LTRNetMessageProcessor mLTRMessageProcessor;
private AudioOutputImpl mAudioOutput = new AudioOutputImpl( "LTRNet Decoder Audio Output" );
private List<Tap> mAvailableTaps;
public LTRNetDecoder( DecodeConfiguration config,
SampleType sampleType,
AliasList aliasList,
MessageDirection direction )
{
super( config, sampleType );
/**
* Only setup a demod chain if we're receiving complex samples. If
* we're receiving demodulated samples, they'll be handled the same
* was as we handle the output of the demodulator.
*/
if( mSourceSampleType == SampleType.COMPLEX )
{
/**
* The Decoder super class is both a Complex listener and a Float
* listener. So, we add the demod to listen to the incoming
* quadrature samples, and we wire the output of the demod right
* back to this class, so we can receive the demodulated output
* to process
*/
mDemodulator = new FilteringNBFMDemodulator();
this.addComplexListener( mDemodulator );
/**
* Remove the DC component that is present when we're mistuned
*/
mDCRemovalFilter = new DCRemovalFilter2( sDC_REMOVAL_RATIO );
mDemodulator.addListener( mDCRemovalFilter );
mDCRemovalFilter.setListener( this.getRealReceiver() );
}
addRealSampleListener( mAudioOutput );
mLTRFSKDecoder = new LTRFSKDecoder();
/**
* The DC removal filter will impact performance of the LTRFSKDemod,
* so we get the samples straight from the NBFM demod
*/
if( mSourceSampleType == SampleType.COMPLEX )
{
mDemodulator.addListener( mLTRFSKDecoder );
}
else
{
this.addRealSampleListener( mLTRFSKDecoder );
}
if( direction == MessageDirection.OSW )
{
mLTRMessageFramer =
new MessageFramer( SyncPattern.LTR_STANDARD_OSW.getPattern(),
sLTR_STANDARD_MESSAGE_LENGTH );
}
else
{
mLTRMessageFramer =
new MessageFramer( SyncPattern.LTR_STANDARD_ISW.getPattern(),
sLTR_STANDARD_MESSAGE_LENGTH );
}
mLTRFSKDecoder.addListener( mLTRMessageFramer );
mLTRMessageProcessor = new LTRNetMessageProcessor( direction, aliasList );
mLTRMessageFramer.addMessageListener( mLTRMessageProcessor );
mLTRMessageProcessor.addMessageListener( this );
}
@Override
public DecoderType getType()
{
return DecoderType.LTR_NET;
}
@Override
public List<Tap> getTaps()
{
if( mAvailableTaps == null )
{
mAvailableTaps = new ArrayList<Tap>();
mAvailableTaps.addAll( mLTRFSKDecoder.getTaps() );
}
return mAvailableTaps;
}
@Override
public void addTap( Tap tap )
{
mLTRFSKDecoder.addTap( tap );
}
@Override
public void removeTap( Tap tap )
{
mLTRFSKDecoder.removeTap( tap );
}
@Override
public void addUnfilteredRealSampleListener( RealSampleListener listener )
{
if( mDemodulator != null )
{
mDemodulator.addListener( listener );
}
// TODO Auto-generated method stub
}
@Override
public IAudioOutput getAudioOutput()
{
return mAudioOutput;
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
public abstract class IdentifierUpdate extends TSBKMessage
implements IBandIdentifier
{
public static final int[] IDENTIFIER = { 80,81,82,83 };
public static final int[] CHANNEL_SPACING = { 102,103,104,105,106,107,108,
109,110,111 };
public static final int[] BASE_FREQUENCY = { 112,113,114,115,116,117,118,
119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135,136,
137,138,139,140,141,142,143 };
public IdentifierUpdate( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public int getIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
@Override
public long getChannelSpacing()
{
return mMessage.getLong( CHANNEL_SPACING ) * 125l;
}
@Override
public long getBaseFrequency()
{
return mMessage.getLong( BASE_FREQUENCY ) * 5l;
}
@Override
public abstract long getTransmitOffset();
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.RejectedExecutionException;
import javax.swing.JPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import sample.complex.ComplexBuffer;
import source.SourceException;
import source.tuner.frequency.FrequencyChangeBroadcaster;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.FrequencyChangeListener;
import source.tuner.frequency.FrequencyChangeEvent.Attribute;
import controller.ResourceManager;
import controller.ThreadPoolManager;
/**
* Tuner - provides tuner channel sources, representing a channel frequency
*/
public abstract class Tuner implements FrequencyChangeBroadcaster,
FrequencyChangeListener,
TunerChannelProvider
{
private final static Logger mLog = LoggerFactory.getLogger( Tuner.class );
private String mName;
/**
* Sample Listeners - these will typically be the DFT processor for spectral
* display, or it will be one or more tuner channel sources
*/
protected CopyOnWriteArrayList<Listener<ComplexBuffer>>
mSampleListeners = new CopyOnWriteArrayList<Listener<ComplexBuffer>>();
protected CopyOnWriteArrayList<FrequencyChangeListener>
mFrequencyChangeListeners = new CopyOnWriteArrayList<FrequencyChangeListener>();
public Tuner( String name )
{
mName = name;
}
public String toString()
{
return mName;
}
public void dispose()
{
mSampleListeners.clear();
mFrequencyChangeListeners.clear();
}
public void setName( String name )
{
mName = name;
}
/**
* Return an editor panel for the tuner
*/
public abstract JPanel getEditor( ResourceManager resourceManager );
/**
* Applies the settings from a saved tuner configuration setting object
*/
public abstract void apply( TunerConfiguration config )
throws SourceException;
/**
* Unique identifier for this tuner, used to lookup a tuner configuration
* from the settings manager.
*
* @return - unique identifier like a serial number, or a usb bus location
* or ip address and port. Return some form of unique identification that
* allows this tuner to be identified from among several of the same types
* of tuners.
*/
public abstract String getUniqueID();
/**
* @return - tuner class enum entry
*/
public abstract TunerClass getTunerClass();
/**
* @return - tuner type enum entry
*/
public abstract TunerType getTunerType();
/**
* Name of this tuner object
* @return - string name of this tuner object
*/
public String getName()
{
return mName;
}
/**
* Sample rate of complex data coming from the Tuner
* @return
*/
public abstract int getSampleRate();
/**
* Tuner Local Oscillator Frequency
* @return - frequency in Hertz
*/
public abstract long getFrequency() throws SourceException;
/**
* Returns a tuner frequency channel source, tuned to the correct frequency
*
* Note: ensure the concrete implementation registers the returned
* tuner channel source as a listener on the tuner, to receive frequency
* change events.
*
* @param frequency - desired frequency
*
* @return - source for 48k sample rate
*/
public abstract TunerChannelSource getChannel( ThreadPoolManager threadPoolManager,
TunerChannel channel ) throws RejectedExecutionException, SourceException;
/**
* Releases the tuned channel resources
*
* Note: ensure the concrete implementation unregisters the tuner channel
* source from the tuner as a frequency change listener
*
* @param channel - previously obtained tuner channel
*/
public abstract void releaseChannel( TunerChannelSource source );
/**
* Registers the listener to receive complex float sample arrays
*/
public void addListener( Listener<ComplexBuffer> listener )
{
mSampleListeners.add( listener );
}
/**
* Removes the registered listener
*/
public void removeListener( Listener<ComplexBuffer> listener )
{
mSampleListeners.remove( listener );
}
/**
* Broadcasts the samples to all registered listeners
*/
public void broadcast( ComplexBuffer sampleBuffer )
{
for( Listener<ComplexBuffer> listener: mSampleListeners )
{
listener.receive( sampleBuffer );
}
}
/**
* Adds the frequency change listener to receive frequency and/or bandwidth
* change events
*/
public void addListener( FrequencyChangeListener listener )
{
mFrequencyChangeListeners.add( listener );
}
/**
* Removes the frequency change listener
*/
public void removeListener( FrequencyChangeListener listener )
{
mFrequencyChangeListeners.remove( listener );
}
/**
* Broadcasts a frequency change event to all registered listeners
*/
public void broadcastFrequencyChange( long frequency )
{
broadcastFrequencyChangeEvent(
new FrequencyChangeEvent( Attribute.FREQUENCY, frequency ) );
}
/**
* Broadcasts a sample rate change event to all registered listeners
*/
public void broadcastSampleRateChange( int sampleRate )
{
broadcastFrequencyChangeEvent(
new FrequencyChangeEvent( Attribute.SAMPLE_RATE, sampleRate ) );
}
/**
* Broadcasts actual sample rate change event to all registered listeners
*/
public void broadcastActualSampleRateChange( int actualSampleRate )
{
broadcastFrequencyChangeEvent(
new FrequencyChangeEvent( Attribute.SAMPLE_RATE, actualSampleRate ) );
}
/**
* Broadcasts a frequency change event to all registered listeners
*/
public void broadcastFrequencyChangeEvent( FrequencyChangeEvent event )
{
for( FrequencyChangeListener listener: mFrequencyChangeListeners )
{
listener.frequencyChanged( event );
}
}
/**
* Frequency change listener method. We receive change events from the
* controller and rebroadcast them to all registered listeners.
*/
public void frequencyChanged( FrequencyChangeEvent event )
{
broadcastFrequencyChangeEvent( event );
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.reference.LinkControlOpcode;
import decode.p25.reference.Service;
public class NetworkStatusBroadcastExplicit extends TDULinkControlMessage
implements IdentifierReceiver
{
private final static Logger mLog =
LoggerFactory.getLogger( NetworkStatusBroadcastExplicit.class );
public static final int[] WACN = { 72,73,74,75,88,89,90,91,92,93,94,95,96,
97,98,99,112,113,114,115 };
public static final int[] SYSTEM = { 116,117,118,119,120,121,122,123,136,
137,138,139 };
public static final int[] TRANSMIT_IDENTIFIER = { 140,141,142,143 };
public static final int[] TRANSMIT_CHANNEL = { 144,145,146,147,160,161,162,
163,164,165,166,167 };
public static final int[] RECEIVE_IDENTIFIER = { 168,169,170,171 };
public static final int[] RECEIVE_CHANNEL = { 184,185,186,187,188,189,190,
191,192,193,194,195 };
private IBandIdentifier mTransmitIdentifierUpdate;
private IBandIdentifier mReceiveIdentifierUpdate;
public NetworkStatusBroadcastExplicit( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.NETWORK_STATUS_BROADCAST_EXPLICIT.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " NETWORK:" + getWACN() );
sb.append( " SYS:" + getSystem() );
sb.append( " TRANSMIT:" + getTransmitChannel() );
sb.append( " RECEIVE:" + getReceiveChannel() );
return sb.toString();
}
public String getWACN()
{
return mMessage.getHex( WACN, 5 );
}
public String getSystem()
{
return mMessage.getHex( SYSTEM, 3 );
}
public int getTransmitIdentifier()
{
return mMessage.getInt( TRANSMIT_IDENTIFIER );
}
public int getTransmitChannelNumber()
{
return mMessage.getInt( TRANSMIT_CHANNEL );
}
public String getTransmitChannel()
{
return getTransmitIdentifier() + "-" + getTransmitChannelNumber();
}
public int getReceiveIdentifier()
{
return mMessage.getInt( RECEIVE_IDENTIFIER );
}
public int getReceiveChannelNumber()
{
return mMessage.getInt( RECEIVE_CHANNEL );
}
public String getReceiveChannel()
{
return getReceiveIdentifier() + "-" + getReceiveChannelNumber();
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
if( identifier == getTransmitIdentifier() )
{
mTransmitIdentifierUpdate = message;
}
if( identifier == getReceiveIdentifier() )
{
mReceiveIdentifierUpdate = message;
}
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 2 ];
identifiers[ 0 ] = getTransmitIdentifier();
identifiers[ 1 ] = getReceiveIdentifier();
return identifiers;
}
public long getDownlinkFrequency()
{
return calculateDownlink( mTransmitIdentifierUpdate,
getTransmitChannelNumber() );
}
public long getUplinkFrequency()
{
return calculateUplink( mReceiveIdentifierUpdate,
getReceiveChannelNumber() );
}
}
<file_sep>package dsp.psk;
import sample.Broadcaster;
import sample.Listener;
import sample.complex.ComplexSample;
import dsp.symbol.Dibit;
public class QPSKPolarSlicer implements Listener<ComplexSample>
{
private Broadcaster<Dibit> mBroadcaster = new Broadcaster<Dibit>();
/**
* Slices a ComplexSample representing a phase shifted symbol according to
* the following constellation pattern:
*
* \ 00 /
* \ /
* 11 \/ 10
* /\
* / \
* / 11 \
*/
public QPSKPolarSlicer()
{
}
public void dispose()
{
mBroadcaster.dispose();
mBroadcaster = null;
}
public void addListener( Listener<Dibit> listener )
{
mBroadcaster.addListener( listener );
}
public void removeListener( Listener<Dibit> listener )
{
mBroadcaster.removeListener( listener );
}
@Override
public void receive( ComplexSample sample )
{
mBroadcaster.broadcast( decide( sample ) );
}
public static Dibit decide( ComplexSample sample )
{
if( sample.inPhaseAbsolute() > sample.quadratureAbsolute() )
{
if( sample.inphase() > 0 )
{
return Dibit.D10_MINUS_1;
}
else
{
return Dibit.D01_PLUS_3;
}
}
else
{
if( sample.quadrature() > 0 )
{
return Dibit.D00_PLUS_1;
}
else
{
return Dibit.D11_MINUS_3;
}
}
}
}
<file_sep>package settings;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import org.jdesktop.swingx.mapviewer.GeoPosition;
public class MapViewSetting extends Setting
{
private double mLatitude;
private double mLongitude;
private int mZoom;
public MapViewSetting()
{
/* Empty constructor for JAXB */
}
public MapViewSetting( String name, double latitude, double longitude, int zoom )
{
super( name );
mLatitude = latitude;
mLongitude = longitude;
mZoom = zoom;
}
public MapViewSetting( String name, GeoPosition position, int zoom )
{
super( name );
mLatitude = position.getLatitude();
mLongitude = position.getLongitude();
mZoom = zoom;
}
@XmlAttribute
public double getLatitude()
{
return mLatitude;
}
public void setLatitude( double latitude )
{
mLatitude = latitude;
}
@XmlAttribute
public double getLongitude()
{
return mLongitude;
}
public void setLongitude( double longitude )
{
mLongitude = longitude;
}
@XmlAttribute
public int getZoom()
{
return mZoom;
}
public void setZoom( int zoom )
{
mZoom = zoom;
}
@XmlTransient
public GeoPosition getGeoPosition()
{
return new GeoPosition( mLatitude, mLongitude );
}
public void setGeoPosition( GeoPosition position )
{
mLatitude = position.getLatitude();
mLongitude = position.getLongitude();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 dsp.filter;
import java.util.Arrays;
/**
* Window creator
*
* Blackman, Hamming and Hanning windows
* based on windowing methods described at:
* http://www.mstarlabs.com/dsp/goertzel/goertzel.html
* and
* Understanding Digital Signal Processing 3e, Lyons, p.91
* and
* Digital Filters for Everyone, Allred, p. 132
*
*/
public class Window
{
public static double[] getWindow( WindowType type, int length )
{
switch( type )
{
case BLACKMAN:
return getBlackmanWindow( length );
case COSINE:
return getCosineWindow( length );
case HAMMING:
return getHammingWindow( length );
case HANNING:
return getHanningWindow( length );
case NONE:
default:
return getRectangularWindow( length );
}
}
public static double[] getRectangularWindow( int length )
{
double[] coefficients = new double[ length ];
Arrays.fill( coefficients, 1.0d );
return coefficients;
}
public static double[] getCosineWindow( int length )
{
double[] coefficients = new double[ length ];
if( length % 2 == 0 ) //Even length
{
int half = (int)( ( length - 1 ) / 2 );
for( int x = -half; x < length / 2 + 1; x++ )
{
coefficients[ x + half ] = Math.cos(
( (double)x * Math.PI ) / ( (double)length + 1.0d ) );
}
}
else //Odd length
{
int half = (int) length / 2;
for( int x = -half; x < half + 1; x++ )
{
coefficients[ x + half ] = Math.cos(
( (double)x * Math.PI ) / ( (double)length + 1.0d ) );
}
}
return coefficients;
}
public static double[] getBlackmanWindow( int length )
{
double[] coefficients = new double[ length ];
for( int x = 0; x < length; x++ )
{
coefficients[ x ] = .426591D -
( .496561D * Math.cos( ( Math.PI * 2.0D * (double)x ) / (double)( length - 1 ) ) +
( .076848D * Math.cos( ( Math.PI * 4.0D * (double)x ) / (double)( length - 1 ) ) ) );
}
return coefficients;
}
public static double[] getHammingWindow( int length )
{
double[] coefficients = new double[ length ];
if( length % 2 == 0 ) //Even length
{
for( int x = 0; x < length; x++ )
{
coefficients[ x ] = .54D - ( .46D *
Math.cos( ( Math.PI * ( 2.0D * (double)x + 1.0d ) ) / (double)( length - 1 ) ) );
}
}
else //Odd length
{
for( int x = 0; x < length; x++ )
{
coefficients[ x ] = .54D - ( .46D *
Math.cos( ( 2.0D * Math.PI * (double)x ) / (double)( length - 1 ) ) );
}
}
return coefficients;
}
public static double[] getHanningWindow( int length )
{
double[] coefficients = new double[ length ];
if( length % 2 == 0 ) //Even length
{
for( int x = 0; x < length; x++ )
{
coefficients[ x ] = .5D - ( .5D *
Math.cos( ( Math.PI * ( 2.0D * (double)x + 1 ) ) / (double)( length - 1 ) ) );
}
}
else //Odd length
{
for( int x = 0; x < length; x++ )
{
coefficients[ x ] = .5D - ( .5D *
Math.cos( ( 2.0D * Math.PI * (double)x ) / (double)( length - 1 ) ) );
}
}
return coefficients;
}
/**
* Apply the window against an array of float-type samples
*/
public static float[] apply( double[] coefficients, float[] samples )
{
for( int x = 0; x < coefficients.length; x++ )
{
samples[ x ] = (float)( samples[ x ] * coefficients[ x ] );
}
return samples;
}
public static float[] apply( WindowType type, float[] samples )
{
double[] coefficients = getWindow( type, samples.length );
return apply( coefficients, samples );
}
/**
* Apply the window against an array of float-type samples
*/
public static double[] apply( double[] coefficients, double[] samples )
{
for( int x = 0; x < coefficients.length; x++ )
{
samples[ x ] = samples[ x ] * coefficients[ x ];
}
return samples;
}
public static double[] apply( WindowType type, double[] samples )
{
double[] coefficients = getWindow( type, samples.length );
return apply( coefficients, samples );
}
/**
* Window types
*/
public enum WindowType
{
BLACKMAN, COSINE, HAMMING, HANNING, NONE;
}
/**
* Utility to log the double arrays
*/
public static String arrayToString( double[] array, boolean breaks )
{
StringBuilder sb = new StringBuilder();
for( int x = 0; x < array.length; x++ )
{
sb.append( x + ":" + array[ x ] );
if( breaks )
{
sb.append( "\n" );
}
else
{
if( x % 8 == 7 )
{
sb.append( "\n" );
}
else
{
sb.append( "\t" );
}
}
}
return sb.toString();
}
}
<file_sep>package decode.p25.message.pdu;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.pdu.osp.control.AdjacentStatusBroadcastExtended;
import decode.p25.message.pdu.osp.control.CallAlertExtended;
import decode.p25.message.pdu.osp.control.GroupAffiliationQueryExtended;
import decode.p25.message.pdu.osp.control.GroupAffiliationResponseExtended;
import decode.p25.message.pdu.osp.control.MessageUpdateExtended;
import decode.p25.message.pdu.osp.control.NetworkStatusBroadcastExtended;
import decode.p25.message.pdu.osp.control.ProtectionParameterBroadcast;
import decode.p25.message.pdu.osp.control.RFSSStatusBroadcastExtended;
import decode.p25.message.pdu.osp.control.RoamingAddressUpdateExtended;
import decode.p25.message.pdu.osp.control.StatusQueryExtended;
import decode.p25.message.pdu.osp.control.StatusUpdateExtended;
import decode.p25.message.pdu.osp.control.UnitRegistrationResponseExtended;
import decode.p25.message.pdu.osp.data.GroupDataChannelGrantExtended;
import decode.p25.message.pdu.osp.data.IndividualDataChannelGrantExtended;
import decode.p25.message.pdu.osp.voice.GroupVoiceChannelGrantExplicit;
import decode.p25.message.pdu.osp.voice.TelephoneInterconnectChannelGrantExplicit;
import decode.p25.message.pdu.osp.voice.TelephoneInterconnectChannelGrantUpdateExplicit;
import decode.p25.message.pdu.osp.voice.UnitToUnitAnswerRequestExplicit;
import decode.p25.message.pdu.osp.voice.UnitToUnitVoiceChannelGrantExtended;
import decode.p25.message.pdu.osp.voice.UnitToUnitVoiceChannelGrantUpdateExtended;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import decode.p25.reference.PDUFormat;
import decode.p25.reference.Vendor;
public class PDUMessageFactory
{
public static PDUMessage getMessage( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
PDUFormat format = PDUFormat.fromValue(
message.getInt( PDUMessage.FORMAT ) );
switch( format )
{
case ALTERNATE_MULTI_BLOCK_TRUNKING_CONTROL:
Vendor vendor = Vendor.fromValue(
message.getInt( PDUMessage.VENDOR_ID ) );
switch( vendor )
{
case STANDARD:
Opcode opcode = Opcode.fromValue(
message.getInt( PDUMessage.OPCODE ) );
switch( opcode )
{
case ADJACENT_STATUS_BROADCAST:
return new AdjacentStatusBroadcastExtended(
message, duid, aliasList );
case CALL_ALERT:
return new CallAlertExtended( message, duid,
aliasList );
case GROUP_AFFILIATION_QUERY:
return new GroupAffiliationQueryExtended(
message, duid, aliasList );
case GROUP_AFFILIATION_RESPONSE:
return new GroupAffiliationResponseExtended(
message, duid, aliasList );
case GROUP_DATA_CHANNEL_GRANT:
return new GroupDataChannelGrantExtended(
message, duid, aliasList );
case GROUP_VOICE_CHANNEL_GRANT:
return new GroupVoiceChannelGrantExplicit(
message, duid, aliasList );
case INDIVIDUAL_DATA_CHANNEL_GRANT:
return new IndividualDataChannelGrantExtended(
message, duid, aliasList );
case MESSAGE_UPDATE:
return new MessageUpdateExtended( message, duid,
aliasList );
case NETWORK_STATUS_BROADCAST:
return new NetworkStatusBroadcastExtended(
message, duid, aliasList );
case PROTECTION_PARAMETER_BROADCAST:
return new ProtectionParameterBroadcast(
message, duid, aliasList );
case RFSS_STATUS_BROADCAST:
return new RFSSStatusBroadcastExtended( message,
duid, aliasList );
case ROAMING_ADDRESS_UPDATE:
return new RoamingAddressUpdateExtended(
message, duid, aliasList );
case STATUS_QUERY:
return new StatusQueryExtended( message, duid,
aliasList );
case STATUS_UPDATE:
return new StatusUpdateExtended( message, duid,
aliasList );
case TELEPHONE_INTERCONNECT_VOICE_CHANNEL_GRANT:
return new TelephoneInterconnectChannelGrantExplicit(
message, duid, aliasList );
case TELEPHONE_INTERCONNECT_VOICE_CHANNEL_GRANT_UPDATE:
return new TelephoneInterconnectChannelGrantUpdateExplicit(
message, duid, aliasList );
case UNIT_REGISTRATION_RESPONSE:
return new UnitRegistrationResponseExtended(
message, duid, aliasList );
case UNIT_TO_UNIT_ANSWER_REQUEST:
return new UnitToUnitAnswerRequestExplicit(
message, duid, aliasList );
case UNIT_TO_UNIT_VOICE_CHANNEL_GRANT:
return new UnitToUnitVoiceChannelGrantExtended(
message, duid, aliasList );
case UNIT_TO_UNIT_VOICE_CHANNEL_GRANT_UPDATE:
return new UnitToUnitVoiceChannelGrantUpdateExtended(
message, duid, aliasList );
default:
break;
}
case MOTOROLA:
break;
default:
break;
}
return new PDUMessage( message, duid, aliasList );
case UNCONFIRMED_MULTI_BLOCK_TRUNKING_CONTROL:
return new PDUMessage( message, duid, aliasList );
default:
return new PDUMessage( message, duid, aliasList );
}
}
}
<file_sep>package alias.action;
import java.awt.EventQueue;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.swing.JOptionPane;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlTransient;
import message.Message;
import alias.Alias;
import controller.ThreadPoolManager;
import controller.ThreadPoolManager.ThreadType;
public abstract class RecurringAction extends AliasAction
{
@XmlTransient
protected AtomicBoolean mRunning = new AtomicBoolean( false );
@XmlTransient
private ScheduledFuture<?> mPerpetualAction;
protected Interval mInterval = Interval.ONCE;
protected int mPeriod = 5;
protected ThreadPoolManager mThreadPoolManager;
public abstract void performAction( Alias alias, Message message );
@Override
public void execute( ThreadPoolManager threadPoolManager,
Alias alias,
Message message )
{
mThreadPoolManager = threadPoolManager;
if( mRunning.compareAndSet( false, true ) )
{
switch( mInterval )
{
case ONCE:
performThreadedAction( alias, message );
/* Don't reset */
break;
case DELAYED_RESET:
performThreadedAction( alias, message );
mThreadPoolManager.scheduleOnce( new ResetTask(),
mPeriod, TimeUnit.SECONDS );
break;
case UNTIL_DISMISSED:
mPerpetualAction = mThreadPoolManager
.scheduleFixedRate( ThreadType.DECODER,
new PerformActionTask( alias, message ),
mPeriod, TimeUnit.SECONDS );
StringBuilder sb = new StringBuilder();
sb.append( "<html><div width='250'>Alias [" );
sb.append( alias.getName() );
sb.append( "] is active in message [" );
sb.append( message.toString() );
sb.append( "]</div></html>" );
final String text = sb.toString();
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
JOptionPane.showMessageDialog( null, text,
"Alias Alert", JOptionPane.INFORMATION_MESSAGE );
dismiss( false );
mThreadPoolManager.scheduleOnce( new ResetTask(),
15, TimeUnit.SECONDS );
}
} );
break;
default:
}
}
}
/**
* Spawns the performAction() event into a new thread so that it doesn't
* delay any decoder actions.
*/
private void performThreadedAction( final Alias alias, final Message message )
{
mThreadPoolManager.scheduleOnce( new Runnable() {
@Override
public void run()
{
performAction( alias, message );
}}, 0, TimeUnit.SECONDS );
}
@Override
public void dismiss( boolean reset )
{
if( mPerpetualAction != null )
{
mPerpetualAction.cancel( true );
mPerpetualAction = null;
}
if( reset )
{
mRunning.set( false );
}
}
@XmlAttribute
public int getPeriod()
{
return mPeriod;
}
public void setPeriod( int period )
{
mPeriod = period;
}
@XmlAttribute
public Interval getInterval()
{
return mInterval;
}
public void setInterval( Interval interval )
{
mInterval = interval;
mRunning.set( false );
}
public enum Interval
{
ONCE( "Once" ),
DELAYED_RESET( "Once, Reset After Delay" ),
UNTIL_DISMISSED( "Until Dismissed" );
private String mLabel;
private Interval( String label )
{
mLabel = label;
}
public String toString()
{
return mLabel;
}
}
public class PerformActionTask implements Runnable
{
private Alias mAlias;
private Message mMessage;
public PerformActionTask( Alias alias, Message message )
{
mAlias = alias;
mMessage = message;
}
@Override
public void run()
{
/* Don't use the performThreadedAction() method, since this is
* already running in a separate thread */
performAction( mAlias, mMessage );
}
}
public class ResetTask implements Runnable
{
@Override
public void run()
{
mRunning.set( false );
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.channel;
import java.awt.Color;
import java.text.DecimalFormat;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import source.tuner.TunerChannel;
import controller.ConfigurableNode;
import controller.site.SiteNode;
import controller.system.SystemNode;
/**
* A channel has all of the pieces needed to wire together a source, decoder,
* event logger and recorder and be started and stopped.
*/
public class ChannelNode extends ConfigurableNode implements ChannelEventListener
{
private static final long serialVersionUID = 1L;
private static DecimalFormat sFORMAT = new DecimalFormat( "0.0000" );
public ChannelNode( Channel channel )
{
super( channel );
}
public void init()
{
/* Set the owning system and site names for the channel */
SiteNode siteNode = (SiteNode)getParent();
if( siteNode != null )
{
getChannel().setSite( siteNode.getSite(), false );
SystemNode systemNode = (SystemNode)siteNode.getParent();
if( systemNode != null )
{
getChannel().setSystem( systemNode.getSystem(), false );
}
}
/* Add this node as listener to receive changes from underlying channel */
getChannel().addListener( this );
/* Add the resource manager to the channel so that the channel
* can provide channel change events to all system resources */
getChannel().setResourceManager( getModel().getResourceManager() );
}
/**
* Listener method to receive channel changes from the underlying chnannel
*/
@Override
public void channelChanged( ChannelEvent event )
{
switch( event.getEvent() )
{
/* Refresh the node for each of these events */
case CHANGE_DECODER:
case CHANGE_ENABLED:
case CHANGE_NAME:
case CHANGE_SELECTED:
case CHANGE_SITE:
case CHANGE_SYSTEM:
case PROCESSING_STARTED:
case PROCESSING_STOPPED:
this.refresh();
break;
/* We're being deleted, so cleanup */
case CHANNEL_DELETED:
delete();
break;
default:
break;
}
}
@Override
public String getIconPath()
{
return getChannel().getDecodeConfiguration().getDecoderType()
.getIconFilename();
}
@Override
public Color getBackgroundColor()
{
if( getChannel().getEnabled() )
{
if( getChannel().isProcessing() )
{
return Color.GREEN;
}
else
{
return Color.RED;
}
}
return null;
}
@Override
public JPanel getEditor()
{
return new ChannelEditor( this );
}
public Channel getChannel()
{
return (Channel)this.getUserObject();
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( getChannel().getName() );
TunerChannel channel = getChannel().getTunerChannel();
if( channel != null )
{
sb.append( " (" );
sb.append( sFORMAT.format( (double)channel.getFrequency() / 1000000.0d ) + " MHz" );
sb.append( ")" );
}
return sb.toString();
}
public JPopupMenu getContextMenu()
{
JPopupMenu popupMenu = new JPopupMenu( "Channel Menu" );
popupMenu.add( getChannel().getContextMenu() );
return popupMenu;
}
public void delete()
{
((SiteNode)getParent()).getSite().removeChannel( getChannel() );
save();
getModel().removeNodeFromParent( ChannelNode.this );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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.jdesktop.swingx.input;
import java.awt.Cursor;
import java.awt.Point;
import java.awt.event.MouseEvent;
import java.awt.geom.Point2D;
import javax.swing.SwingUtilities;
import javax.swing.event.MouseInputAdapter;
import org.jdesktop.swingx.JXMapViewer;
/**
* Used to pan using press and drag mouse gestures
* @author joshy
*/
public class PanMouseInputListener extends MouseInputAdapter
{
private Point prev;
private JXMapViewer viewer;
/**
* @param viewer the jxmapviewer
*/
public PanMouseInputListener(JXMapViewer viewer)
{
this.viewer = viewer;
}
@Override
public void mousePressed(MouseEvent evt)
{
prev = evt.getPoint();
}
@Override
public void mouseDragged(MouseEvent evt)
{
if (!SwingUtilities.isLeftMouseButton(evt))
return;
Point current = evt.getPoint();
double x = viewer.getCenter().getX() - (current.x - prev.x);
double y = viewer.getCenter().getY() - (current.y - prev.y);
if (!viewer.isNegativeYAllowed())
{
if (y < 0)
{
y = 0;
}
}
int maxHeight = (int) (viewer.getTileFactory().getMapSize(viewer.getZoom()).getHeight() * viewer
.getTileFactory().getTileSize(viewer.getZoom()));
if (y > maxHeight)
{
y = maxHeight;
}
prev = current;
viewer.setCenter(new Point2D.Double(x, y));
viewer.repaint();
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
@Override
public void mouseReleased(MouseEvent evt)
{
if (!SwingUtilities.isLeftMouseButton(evt))
return;
prev = null;
viewer.setCursor(Cursor.getPredefinedCursor(Cursor.DEFAULT_CURSOR));
}
@Override
public void mouseEntered(MouseEvent e)
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
viewer.requestFocusInWindow();
}
});
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 instrument.gui;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.io.IOException;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDesktopPane;
import javax.swing.JInternalFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import message.MessageDirection;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.wave.WaveSource;
import source.wave.WaveSource.PositionListener;
import controller.ResourceManager;
import decode.Decoder;
import decode.DecoderType;
import decode.config.DecodeConfigLTRNet;
import decode.config.DecodeConfigMPT1327;
import decode.config.DecodeConfigPassport;
import decode.fleetsync2.Fleetsync2Decoder;
import decode.lj1200.LJ1200Decoder;
import decode.ltrnet.LTRNetDecoder;
import decode.mdc1200.MDCDecoder;
import decode.mpt1327.MPT1327Decoder;
import decode.mpt1327.MPT1327Decoder.Sync;
import decode.p25.P25Decoder;
import decode.p25.P25Decoder.Modulation;
import decode.passport.PassportDecoder;
import decode.tait.Tait1200Decoder;
public class AudioSourceFrame extends JInternalFrame implements PositionListener
{
private static final long serialVersionUID = 1L;
private final static Logger mLog =
LoggerFactory.getLogger( AudioSourceFrame.class );
private WaveSource mSource;
private JDesktopPane mDesktop;
private JLabel mCurrentPosition = new JLabel( "0" );
private JComboBox<DecoderType> mComboDecoders;
private JComboBox<Modulation> mComboModulations;
private JLabel mModulationLabel = new JLabel( "Modulation:" );
public AudioSourceFrame( WaveSource source, JDesktopPane desktop )
{
mSource = source;
mSource.addListener( this );
mDesktop = desktop;
initGui();
}
private void initGui()
{
setTitle( "Audio Source [" + mSource.getSampleType().toString() + "]" );
setPreferredSize( new Dimension( 700, 150 ) );
setSize( 700, 150 );
setResizable( true );
setClosable( true );
setIconifiable( true );
setMaximizable( false );
JPanel panel = new JPanel();
panel.setLayout( new MigLayout() );
JLabel fileLabel = new JLabel( "File: " + mSource.getFile().getName() );
fileLabel.setToolTipText( mSource.getFile().getName() );
panel.add( fileLabel, "span,wrap" );
panel.add( new JLabel( "Jump:" ) );
panel.add( new JumpToField( mSource ) );
panel.add( new NextSampleButton( mSource, ">", 1 ) );
panel.add( new NextSampleButton( mSource, "> 10 >", 10 ) );
panel.add( new NextSampleButton( mSource, "> 100 >", 100 ) );
panel.add( new NextSampleButton( mSource, "> 1000 >", 1000 ) );
panel.add( new JLabel( "Posn:" ) );
panel.add( mCurrentPosition, "wrap" );
/* ComboBox: Decoders */
mComboDecoders = new JComboBox<DecoderType>();
DefaultComboBoxModel<DecoderType> model =
new DefaultComboBoxModel<DecoderType>();
for( DecoderType type: DecoderType.getInstrumentableDecoders() )
{
model.addElement( type );
}
mComboDecoders.setModel( model );
mComboDecoders.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
DecoderType selected = (DecoderType)mComboDecoders.getSelectedItem();
if( selected == DecoderType.P25_PHASE1 )
{
mComboModulations.setVisible( true );
mModulationLabel.setVisible( true );
}
else
{
mComboModulations.setVisible( false );
mModulationLabel.setVisible( false );
}
}
});
panel.add( new JLabel( "Decoders:" ) );
panel.add( mComboDecoders, "span 3,grow" );
panel.add( new AddDecoderButton(), "grow,wrap" );
mComboModulations = new JComboBox<Modulation>(
new DefaultComboBoxModel<Modulation>( Modulation.values() ) );
mComboModulations.setVisible( false );
mModulationLabel.setVisible( false );
panel.add( mModulationLabel );
panel.add( mComboModulations );
add( panel );
}
public class AddDecoderButton extends JButton
{
private static final long serialVersionUID = 1L;
public AddDecoderButton()
{
super( "Add" );
addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
DecoderType selected =
(DecoderType)mComboDecoders.getSelectedItem();
mLog.info( "Selected:" + selected.getDisplayString() );
Decoder decoder = null;
switch( selected )
{
case FLEETSYNC2:
decoder = new Fleetsync2Decoder( null );
break;
case LJ_1200:
decoder = new LJ1200Decoder( null );
break;
case LTR_NET:
decoder = new LTRNetDecoder( new DecodeConfigLTRNet(),
mSource.getSampleType(), null, MessageDirection.OSW );
break;
case MDC1200:
decoder = new MDCDecoder( null );
break;
case MPT1327:
decoder = new MPT1327Decoder( new DecodeConfigMPT1327(),
mSource.getSampleType(), null, Sync.NORMAL );
break;
case PASSPORT:
decoder = new PassportDecoder( new DecodeConfigPassport(),
mSource.getSampleType(), null );
break;
case P25_PHASE1:
ResourceManager rm = new ResourceManager();
decoder = new P25Decoder( rm, mSource.getSampleType(),
(Modulation)mComboModulations.getSelectedItem(), null );
break;
case TAIT_1200:
decoder = new Tait1200Decoder( null );
break;
default:
break;
}
if( decoder != null )
{
DecoderViewFrame decoderFrame =
new DecoderViewFrame( decoder, mSource );
decoderFrame.setVisible( true );
mDesktop.add( decoderFrame );
}
}
} );
}
}
public class NextSampleButton extends JButton
{
private static final long serialVersionUID = 1L;
private WaveSource mSource;
private int mCount;
public NextSampleButton( WaveSource source, String label, int count )
{
super( label );
mSource = source;
mCount = count;
addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
mSource.next( mCount );
}
catch ( IOException e )
{
mLog.error( "Viewer - error trying to fetch next [" +
mCount + "] samples", e );
JOptionPane.showMessageDialog( AudioSourceFrame.this,
"Cannot read " + mCount + " more samples [" +
e.getLocalizedMessage() + "]",
"Wave File Error",
JOptionPane.ERROR_MESSAGE );
}
}
} );
}
}
public class JumpToField extends JTextField
{
private static final long serialVersionUID = 1L;
private WaveSource mSource;
public JumpToField( WaveSource source )
{
super( "0" );
mSource = source;
setMinimumSize( new Dimension( 100, getHeight() ) );
addFocusListener( new FocusListener()
{
@Override
public void focusGained( FocusEvent arg0 ) {}
@Override
public void focusLost( FocusEvent arg0 )
{
try
{
long position = Long.parseLong( getText() );
mSource.jumpTo( position );
}
catch( Exception e )
{
mLog.error( "WaveSourceFrame - exception during jump "
+ "to", e );
JOptionPane.showMessageDialog( AudioSourceFrame.this,
"Can't jump to position [" + getText() + "]",
"Error",
JOptionPane.ERROR_MESSAGE );
}
}
} );
}
}
@Override
public void positionUpdated( long position, boolean reset )
{
mCurrentPosition.setText( String.valueOf( position ) );
if( reset )
{
}
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.TimeZone;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class TimeAndDateAnnouncement extends TSBKMessage
{
public static final int VALID_DATE_INDICATOR = 80;
public static final int VALID_TIME_INDICATOR = 81;
public static final int VALID_LOCAL_TIME_OFFSET_INDICATOR = 82;
public static final int LOCAL_TIME_OFFSET_SIGN = 84;
public static final int[] LOCAL_TIME_OFFSET = { 85,86,87,88,89,90,91,92,
93,94,95 };
public static final int[] MONTH = { 96,97,98,99 };
public static final int[] DAY = { 100,101,102,103 };
public static final int[] YEAR = { 105,106,107,108,109,110,111,112,113,114,
115,116,117 };
public static final int[] HOURS = { 120,121,122,123,124 };
public static final int[] MINUTES = { 125,126,127,128,129,130 };
public static final int[] SECONDS = { 131,132,133,134,135,136 };
private SimpleDateFormat mTimeFormatter =
new SimpleDateFormat( "EEE, d MMM yyyy HH:mm:ss Z" );
public TimeAndDateAnnouncement( BinaryMessage message, DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.TIME_DATE_ANNOUNCEMENT.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
if( hasValidDate() )
{
sb.append( " DATE-TIME:" );
}
sb.append( " " );
sb.append( mTimeFormatter.format( new Date( getDateTimestamp() ) ) );
return sb.toString();
}
public long getDateTimestamp()
{
Calendar cal = new GregorianCalendar( getTimeZone() );
if( hasValidDate() )
{
cal.set( Calendar.YEAR, getYear() );
cal.set( Calendar.MONTH, getMonth() );
cal.set( Calendar.DAY_OF_MONTH, getDay() );
}
if( hasValidTime() )
{
cal.set( Calendar.HOUR, getHour() );
cal.set( Calendar.MINUTE, getMinute() );
cal.set( Calendar.SECOND, getSecond() );
}
return cal.getTimeInMillis();
}
public boolean hasValidDate()
{
return mMessage.get( VALID_DATE_INDICATOR );
}
public boolean hasValidTime()
{
return mMessage.get( VALID_TIME_INDICATOR );
}
public TimeZone getTimeZone()
{
StringBuilder sb = new StringBuilder();
sb.append( "GMT " );
sb.append( mMessage.get( LOCAL_TIME_OFFSET_SIGN ) ? "-" : "+" );
int offsetMinutes = getLocalTimeOffset();
sb.append( (int)( offsetMinutes / 60 ) );
sb.append( " : " );
sb.append( offsetMinutes % 60 );
return TimeZone.getTimeZone( sb.toString() );
}
public boolean hasValidLocalTimeOffset()
{
return mMessage.get( VALID_LOCAL_TIME_OFFSET_INDICATOR );
}
/**
* Local Time Offset in minutes
*/
public int getLocalTimeOffset()
{
return mMessage.getInt( LOCAL_TIME_OFFSET );
}
public int getMonth()
{
return mMessage.getInt( MONTH );
}
public int getDay()
{
return mMessage.getInt( DAY );
}
public int getYear()
{
return mMessage.getInt( YEAR );
}
public int getHour()
{
return mMessage.getInt( HOURS );
}
public int getMinute()
{
return mMessage.getInt( MINUTES );
}
public int getSecond()
{
return mMessage.getInt( SECONDS );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.recording;
import gui.control.JFrequencyControl;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;
import source.SourceEditor;
import source.config.SourceConfigRecording;
import source.config.SourceConfigTuner;
import source.config.SourceConfiguration;
import controller.ResourceManager;
public class RecordingEditor extends SourceEditor
{
private static final long serialVersionUID = 1L;
private JComboBox<Recording> mComboRecordings;
private JFrequencyControl mFrequencyControl;
public RecordingEditor( ResourceManager resourceManager,
SourceConfiguration config )
{
super( resourceManager, config );
initGUI();
}
public void reset()
{
mFrequencyControl.setFrequency(
((SourceConfigTuner)mConfig).getFrequency(), false );
}
public void save()
{
SourceConfigRecording config = (SourceConfigRecording)mConfig;
Recording selected = (Recording)mComboRecordings.getSelectedItem();
if( selected != null )
{
config.setRecordingAlias( selected
.getRecordingConfiguration().getAlias() );
}
config.setFrequency( mFrequencyControl.getFrequency() );
}
private void initGUI()
{
add( new JLabel( "Recording" ) );
mComboRecordings = new JComboBox<Recording>();
add( mComboRecordings, "wrap" );
mFrequencyControl = new JFrequencyControl();
mFrequencyControl.setFrequency(
((SourceConfigRecording)mConfig).getFrequency(), false );
add( mFrequencyControl, "span" );
resetRecordings();
}
private void resetRecordings()
{
SwingUtilities.invokeLater( new Runnable()
{
@Override
public void run()
{
List<Recording> recordings = getResourceManager()
.getRecordingSourceManager().getRecordings();
mComboRecordings.setModel(
new DefaultComboBoxModel<Recording>(
recordings.toArray( new Recording[ recordings.size()] ) ) );
SourceConfigRecording config = (SourceConfigRecording)mConfig;
String recordingAlias = config.getRecordingAlias();
if( recordingAlias != null )
{
Recording selected = mResourceManager
.getRecordingSourceManager()
.getRecordingFromAlias( recordingAlias );
if( selected != null )
{
mComboRecordings.setSelectedItem( selected );
}
}
}
});
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.p25;
import java.awt.EventQueue;
import javax.swing.JLabel;
import settings.ColorSetting;
import settings.Setting;
import alias.Alias;
import controller.channel.Channel;
import controller.state.ChannelState.ChangedAttribute;
import controller.state.ChannelState.State;
import controller.state.ChannelStatePanel;
import decode.config.DecodeConfigP25Phase1;
public class P25Panel extends ChannelStatePanel
{
private static final long serialVersionUID = 1L;
private JLabel mStateLabel;
private JLabel mSourceLabel;
private JLabel mChannelLabel;
private JLabel mProtocol;
private JLabel mFrom = new JLabel( " " );
private JLabel mFromAlias = new JLabel( " " );
private JLabel mNAC = new JLabel( "NAC:" );
private JLabel mTo = new JLabel( " " );
private JLabel mToAlias = new JLabel( " " );
private JLabel mSystem = new JLabel( "SYS:" );
private JLabel mSite = new JLabel( "Site:" );
private JLabel mSiteAlias = new JLabel( "" );
public P25Panel( Channel channel )
{
super( channel );
DecodeConfigP25Phase1 p25Config =
(DecodeConfigP25Phase1)channel.getDecodeConfiguration();
mProtocol = new JLabel( "P25-1 " +
p25Config.getModulation().getShortLabel() );
init();
}
public void init()
{
mStateLabel = new JLabel( mChannel.getProcessingChain().
getChannelState().getState().getDisplayValue() );
mStateLabel.setFont( mFontDecoder );
mStateLabel.setForeground( mColorLabelDecoder );
mSourceLabel = new JLabel( mChannel.getSourceConfiguration().getDescription() );
mSourceLabel.setFont( mFontDetails );
mSourceLabel.setForeground( mColorLabelDetails );
mChannelLabel = new JLabel( mChannel.getChannelDisplayName() );
mChannelLabel.setFont( mFontDetails );
mChannelLabel.setForeground( mColorLabelDetails );
mProtocol.setFont( mFontDecoder );
mProtocol.setForeground( mColorLabelDecoder );
mFrom.setFont( mFontDecoder );
mFrom.setForeground( mColorLabelDecoder );
mFromAlias.setFont( mFontDecoder );
mFromAlias.setForeground( mColorLabelDecoder );
mNAC.setFont( mFontDetails );
mNAC.setForeground( mColorLabelDecoder );
mTo.setFont( mFontDecoder );
mTo.setForeground( mColorLabelDecoder );
mToAlias.setFont( mFontDecoder );
mToAlias.setForeground( mColorLabelDecoder );
mSystem.setFont( mFontDetails );
mSystem.setForeground( mColorLabelDecoder );
mSiteAlias.setFont( mFontDecoder );
mSiteAlias.setForeground( mColorLabelDecoder );
mSite.setFont( mFontDetails );
mSite.setForeground( mColorLabelDecoder );
add( mStateLabel );
add( mSourceLabel );
add( mChannelLabel, "wrap" );
add( mProtocol );
add( mFrom );
add( mFromAlias, "wrap" );
add( mNAC );
add( mTo );
add( mToAlias, "wrap" );
add( mSystem );
add( mSite );
add( mSiteAlias, "wrap" );
}
@Override
public void receive( final ChangedAttribute changedAttribute )
{
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
final P25ChannelState channelState = (P25ChannelState)mChannel.
getProcessingChain().getChannelState();
switch( changedAttribute )
{
case CHANNEL_STATE:
State state = channelState.getState();
mStateLabel.setText( state.getDisplayValue() );
if( state == State.IDLE )
{
mFrom.setText( null );
mFromAlias.setText( null );
mFromAlias.setIcon( null );
mTo.setText( null );
mToAlias.setText( null );
mToAlias.setIcon( null );
}
break;
case SOURCE:
mSourceLabel.setText( mChannel.getSourceConfiguration()
.getDescription() );
break;
case CHANNEL_NAME:
case SITE_NAME:
case SYSTEM_NAME:
mChannelLabel.setText( mChannel.getChannelDisplayName() );
break;
case NAC:
mNAC.setText( "NAC:" + channelState.getNAC() );
break;
case SYSTEM:
mSystem.setText( "SYS:" + channelState.getSystem() );
break;
case SITE:
mSite.setText( "SITE:" + channelState.getSite() );
break;
case SITE_ALIAS:
mSiteAlias.setText( channelState.getSiteAlias() );
break;
case FROM_TALKGROUP:
mFrom.setText( channelState.getFromTalkgroup() );
break;
case FROM_TALKGROUP_ALIAS:
Alias from = channelState.getFromAlias();
if( from != null )
{
mFromAlias.setText( from.getName() );
mFromAlias.setIcon( getSettingsManager()
.getImageIcon( from.getIconName(), 12 ) );
}
else
{
mFromAlias.setText( null );
mFromAlias.setIcon( null );
}
break;
case TO_TALKGROUP:
mTo.setText( channelState.getToTalkgroup() );
break;
case TO_TALKGROUP_ALIAS:
Alias to = channelState.getToAlias();
if( to != null )
{
mToAlias.setText( to.getName() );
mToAlias.setIcon( getSettingsManager()
.getImageIcon( to.getIconName(), 12 ) );
}
else
{
mToAlias.setText( null );
mToAlias.setIcon( null );
}
break;
}
repaint();
}
});
}
@Override
public void settingChanged( Setting setting )
{
super.settingChanged( setting );
if( setting instanceof ColorSetting )
{
ColorSetting colorSetting = (ColorSetting)setting;
switch( colorSetting.getColorSettingName() )
{
case CHANNEL_STATE_LABEL_DECODER:
if( mStateLabel != null )
{
mStateLabel.setForeground( mColorLabelDecoder );
}
if( mProtocol != null )
{
mProtocol.setForeground( mColorLabelDecoder );
}
break;
case CHANNEL_STATE_LABEL_DETAILS:
if( mSourceLabel != null )
{
mSourceLabel.setForeground( mColorLabelDetails );
}
if( mChannelLabel != null )
{
mChannelLabel.setForeground( mColorLabelDetails );
}
break;
}
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
public class ConfigurationEditor extends JPanel
implements TreeSelectionListener
{
private static final long serialVersionUID = 1L;
/**
* Host for configuration editor display panels
*/
public ConfigurationEditor()
{
init();
}
public void init()
{
setPanel( new EmptyEditor() );
}
public void setPanel( JPanel display )
{
removeAll();
setLayout( new BorderLayout() );
JScrollPane scroll = new JScrollPane( display );
add( scroll, BorderLayout.CENTER );
revalidate();
repaint();
}
@Override
public void valueChanged( TreeSelectionEvent e )
{
JTree tree = (JTree)e.getSource();
BaseNode node =
(BaseNode)tree.getLastSelectedPathComponent();
if( node != null )
{
setPanel( node.getEditor() );
}
}
}
<file_sep>package decode.p25.message;
import java.text.SimpleDateFormat;
import map.Plottable;
import message.Message;
import alias.Alias;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.reference.DataUnitID;
import edac.CRC;
public class P25Message extends Message
{
public enum DuplexMode { HALF, FULL };
public enum SessionMode { PACKET, CIRCUIT };
public static final int[] NAC = { 0,1,2,3,4,5,6,7,8,9,10,11 };
public static final int[] DUID = { 12,13,14,15 };
public static final int[] BCH = { 16,17,18,19,20,21,22,23,24,25,26,27,28,29,
30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,
54,55,56,57,58,59,60,61,62,63 };
protected SimpleDateFormat mTimeDurationFormat =
new SimpleDateFormat( "HH:mm:ss.SSS");
protected BinaryMessage mMessage;
protected DataUnitID mDUID;
protected AliasList mAliasList;
protected CRC[] mCRC;
public P25Message( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super();
mMessage = message;
mDUID = duid;
mAliasList = aliasList;
}
public CRC[] getCRCResults()
{
return mCRC;
}
public BinaryMessage getSourceMessage()
{
return mMessage;
}
public AliasList getAliasList()
{
return mAliasList;
}
public String getNAC()
{
return mMessage.getHex( NAC, 3 );
}
public DataUnitID getDUID()
{
return mDUID;
}
@Override
public String getErrorStatus()
{
if( mCRC == null )
{
return "UNKNOWN";
}
return CRC.format( mCRC );
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( "NAC:" );
sb.append( getNAC() );
sb.append( " " );
sb.append( getDUID().getLabel() );
return sb.toString();
}
@Override
public String getBinaryMessage()
{
return mMessage.toString();
}
@Override
public String getProtocol()
{
return "P25 Phase 1";
}
@Override
public String getEventType()
{
return mDUID.name();
}
@Override
public String getFromID()
{
return null;
}
@Override
public Alias getFromIDAlias()
{
if( mAliasList != null )
{
return mAliasList.getTalkgroupAlias( getFromID() );
}
return null;
}
@Override
public String getToID()
{
return null;
}
@Override
public Alias getToIDAlias()
{
if( mAliasList != null )
{
return mAliasList.getTalkgroupAlias( getToID() );
}
return null;
}
@Override
public Plottable getPlottable()
{
return null;
}
@Override
public String toString()
{
return getMessage();
}
@Override
public boolean isValid()
{
if( mCRC != null )
{
for( CRC crc: mCRC )
{
if( crc == CRC.FAILED_CRC )
{
return false;
}
}
}
return true;
}
/**
* Calculates the frequency of the uplink channel using the channel number
* and the IdentifierUpdate message.
*
* @param iden - Identifier Update message
* @param channel - channel number
* @return - frequency in Hertz
*/
protected static long calculateUplink( IBandIdentifier iden, int channel )
{
long downlink = calculateDownlink( iden, channel );
if( downlink > 0 && iden != null )
{
return downlink + iden.getTransmitOffset();
}
return 0;
}
/**
* Calculates the frequency of the downlink channel using the channel number
* and the IdentifierUpdate message.
*
* @param iden - Identifier Update message
* @param channel - channel number
* @return - frequency in Hertz
*/
protected static long calculateDownlink( IBandIdentifier iden, int channel )
{
if( iden != null )
{
return iden.getBaseFrequency() +
( channel * iden.getChannelSpacing() );
}
return 0;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.rtl.r820t;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.BorderFactory;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.usb.UsbException;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.LibUsbException;
import source.SourceException;
import source.tuner.TunerConfiguration;
import source.tuner.TunerConfigurationAssignment;
import source.tuner.TunerType;
import source.tuner.rtl.RTL2832TunerController.SampleRate;
import source.tuner.rtl.r820t.R820TTunerController.R820TGain;
import source.tuner.rtl.r820t.R820TTunerController.R820TLNAGain;
import source.tuner.rtl.r820t.R820TTunerController.R820TMixerGain;
import source.tuner.rtl.r820t.R820TTunerController.R820TVGAGain;
import controller.ResourceManager;
public class R820TTunerConfigurationPanel extends JPanel
{
private final static Logger mLog =
LoggerFactory.getLogger( R820TTunerConfigurationPanel.class );
private static final long serialVersionUID = 1L;
private static final R820TGain DEFAULT_GAIN = R820TGain.GAIN_279;
private ResourceManager mResourceManager;
private R820TTunerController mController;
private R820TTunerConfiguration mSelectedConfig;
private JButton mNewConfiguration;
private JButton mDeleteConfiguration;
private JComboBox<R820TTunerConfiguration> mComboConfigurations;
private JTextField mName;
private JSpinner mFrequencyCorrection;
private JSpinner mSampleRateCorrection;
private JComboBox<R820TGain> mComboMasterGain;
private JComboBox<R820TMixerGain> mComboMixerGain;
private JComboBox<R820TLNAGain> mComboLNAGain;
private JComboBox<R820TVGAGain> mComboVGAGain;
private JComboBox<SampleRate> mComboSampleRate;
public R820TTunerConfigurationPanel( ResourceManager resourceManager,
R820TTunerController controller )
{
mResourceManager = resourceManager;
mController = controller;
init();
}
/**
* Initializes the gui components
*/
private void init()
{
setLayout( new MigLayout( "fill,wrap 2", "[grow,right][grow]", "[][][][][][][grow]" ) );
/**
* Tuner configuration selector
*/
mComboConfigurations = new JComboBox<R820TTunerConfiguration>();
mComboConfigurations.setModel( getModel() );
/* Determine which tuner configuration should be selected/displayed */
TunerConfigurationAssignment savedConfig = mResourceManager
.getSettingsManager().getSelectedTunerConfiguration(
TunerType.RAFAELMICRO_R820T, mController.getUniqueID() );
if( savedConfig != null )
{
mSelectedConfig = getNamedConfiguration(
savedConfig.getTunerConfigurationName() );
}
/* If we couldn't determine the saved/selected config, use the first one */
if( mSelectedConfig == null )
{
mSelectedConfig = mComboConfigurations.getItemAt( 0 );
//Store this config as the default for this tuner at this address
mResourceManager.getSettingsManager()
.setSelectedTunerConfiguration(
TunerType.RAFAELMICRO_R820T,
mController.getUniqueID(), mSelectedConfig );
}
mComboConfigurations.setSelectedItem( mSelectedConfig );
mComboConfigurations.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
R820TTunerConfiguration selected =
(R820TTunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
update( selected );
}
}
});
add( new JLabel( "Config:" ) );
add( mComboConfigurations, "growx,push" );
/**
* Tuner Configuration Name
*/
mName = new JTextField();
mName.setText( mSelectedConfig.getName() );
mName.addFocusListener( new FocusListener()
{
@Override
public void focusLost( FocusEvent e )
{
mSelectedConfig.setName( mName.getText() );
save();
}
@Override
public void focusGained( FocusEvent e ) {}
} );
add( new JLabel( "Name:" ) );
add( mName, "growx,push" );
/**
* Frequency Correction
*/
SpinnerModel model =
new SpinnerNumberModel( 0.0, //initial value
-1000.0, //min
1000.0, //max
0.1 ); //step
mFrequencyCorrection = new JSpinner( model );
JSpinner.NumberEditor editor =
(JSpinner.NumberEditor)mFrequencyCorrection.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits( 1 );
editor.getTextField().setHorizontalAlignment( SwingConstants.CENTER );
mFrequencyCorrection.setValue( mSelectedConfig.getFrequencyCorrection() );
mFrequencyCorrection.addChangeListener( new ChangeListener()
{
@Override
public void stateChanged( ChangeEvent e )
{
final double value = ((SpinnerNumberModel)mFrequencyCorrection
.getModel()).getNumber().doubleValue();
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
mController.setFrequencyCorrection( value );
mSelectedConfig.setFrequencyCorrection( value );
save();
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this,
"R820T Tuner Controller - couldn't apply "
+ "frequency correction value: " + value +
e1.getLocalizedMessage() );
mLog.error( "R820T Tuner Controller - couldn't apply "
+ "frequency correction value: " + value, e1 );
}
}
} );
}
} );
add( new JLabel( "Correction PPM:" ) );
add( mFrequencyCorrection, "growx,push" );
/**
* Sample Rate
*/
mComboSampleRate = new JComboBox<>( SampleRate.values() );
mComboSampleRate.setSelectedItem( mSelectedConfig.getSampleRate() );
mComboSampleRate.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
SampleRate sampleRate =
(SampleRate)mComboSampleRate.getSelectedItem();
try
{
mController.setSampleRate( sampleRate );
mSelectedConfig.setSampleRate( sampleRate );
save();
}
catch ( SourceException | LibUsbException eSampleRate )
{
JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this,
"R820T Tuner Controller - couldn't apply the sample "
+ "rate setting [" + sampleRate.getLabel() + "] " +
eSampleRate.getLocalizedMessage() );
mLog.error( "R820T Tuner Controller - couldn't apply sample "
+ "rate setting [" + sampleRate.getLabel() + "]",
eSampleRate );
}
}
} );
add( new JLabel( "Sample Rate:" ) );
add( mComboSampleRate, "growx,push" );
/**
* Sample Rate Correction
*/
SpinnerModel sampleRateCorrectionModel =
new SpinnerNumberModel( 0, //initial value
-32768, //min
32767, //max
1 ); //step
mSampleRateCorrection = new JSpinner( sampleRateCorrectionModel );
JSpinner.NumberEditor sampleRateCorrectionEditor =
(JSpinner.NumberEditor)mSampleRateCorrection.getEditor();
DecimalFormat sampleRateCorrectionFormat =
sampleRateCorrectionEditor.getFormat();
sampleRateCorrectionFormat.setMinimumFractionDigits( 0 );
sampleRateCorrectionEditor.getTextField()
.setHorizontalAlignment( SwingConstants.CENTER );
mSampleRateCorrection.addChangeListener( new ChangeListener()
{
@Override
public void stateChanged( ChangeEvent e )
{
final int value = ((SpinnerNumberModel)mSampleRateCorrection
.getModel()).getNumber().intValue();
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
mController.setSampleRateFrequencyCorrection( value );
}
catch ( SourceException | LibUsbException e1 )
{
JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this,
"E4K Tuner Controller - couldn't apply "
+ "sample rate correction value: " + value +
e1.getLocalizedMessage() );
mLog.error( "E4K Tuner Controller - couldn't apply "
+ "sample rate correction value: " + value +
e1.getLocalizedMessage() );
}
}
} );
}
} );
add( mSampleRateCorrection );
add( new JLabel( "Sample Rate Correction (ppm)" ), "grow,push" );
/**
* Gain Controls
*/
JPanel gainPanel = new JPanel();
gainPanel.setLayout( new MigLayout( "", "[grow,fill]", "[grow,fill]" ) );
gainPanel.setBorder( BorderFactory.createTitledBorder( "Gain" ) );
/* Master Gain Control */
mComboMasterGain = new JComboBox<R820TGain>( R820TGain.values() );
mComboMasterGain.setSelectedItem( mSelectedConfig.getMasterGain() );
mComboMasterGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
R820TGain gain = (R820TGain)mComboMasterGain.getSelectedItem();
mController.setGain( (R820TGain)mComboMasterGain.getSelectedItem(), true );
if( gain == R820TGain.MANUAL )
{
mComboMixerGain.setSelectedItem( gain.getMixerGain() );
mComboMixerGain.setEnabled( true );
mComboLNAGain.setSelectedItem( gain.getLNAGain() );
mComboLNAGain.setEnabled( true );
mComboVGAGain.setSelectedItem( gain.getVGAGain() );
mComboVGAGain.setEnabled( true );
}
else
{
mComboMixerGain.setEnabled( false );
mComboMixerGain.setSelectedItem( gain.getMixerGain() );
mComboLNAGain.setEnabled( false );
mComboLNAGain.setSelectedItem( gain.getLNAGain() );
mComboVGAGain.setEnabled( false );
mComboVGAGain.setSelectedItem( gain.getVGAGain() );
}
mSelectedConfig.setMasterGain( gain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this,
"R820T Tuner Controller - couldn't apply the gain "
+ "setting - " + e.getLocalizedMessage() );
mLog.error( "R820T Tuner Controller - couldn't apply "
+ "gain setting - ", e );
}
}
} );
mComboMasterGain.setToolTipText( "<html>Select <b>AUTOMATIC</b> for auto "
+ "gain, <b>MANUAL</b> to enable<br> independent control of "
+ "<i>Mixer</i>, <i>LNA</i> and <i>Enhance</i> gain<br>"
+ "settings, or one of the individual gain settings for<br>"
+ "semi-manual gain control</html>" );
gainPanel.add( new JLabel( "Master" ) );
gainPanel.add( mComboMasterGain );
/* Mixer Gain Control */
mComboMixerGain = new JComboBox<R820TMixerGain>( R820TMixerGain.values() );
mComboMixerGain.setSelectedItem( mSelectedConfig.getMixerGain() );
mComboMixerGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
R820TMixerGain mixerGain =
(R820TMixerGain)mComboMixerGain.getSelectedItem();
if( mixerGain == null )
{
mixerGain = DEFAULT_GAIN.getMixerGain();
}
if( mComboMixerGain.isEnabled() )
{
mController.setMixerGain( mixerGain, true );
}
mSelectedConfig.setMixerGain( mixerGain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this,
"R820T Tuner Controller - couldn't apply the mixer "
+ "gain setting - " + e.getLocalizedMessage() );
mLog.error( "R820T Tuner Controller - couldn't apply mixer "
+ "gain setting - ", e );
}
}
} );
}
} );
mComboMixerGain.setToolTipText( "<html>Mixer Gain. Set master gain "
+ "to <b>MASTER</b> to enable adjustment</html>" );
mComboMixerGain.setEnabled( false );
gainPanel.add( new JLabel( "Mixer" ) );
gainPanel.add( mComboMixerGain, "wrap" );
/* LNA Gain Control */
mComboLNAGain = new JComboBox<R820TLNAGain>( R820TLNAGain.values() );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
mComboLNAGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
R820TLNAGain lnaGain =
(R820TLNAGain)mComboLNAGain.getSelectedItem();
if ( lnaGain == null )
{
lnaGain = DEFAULT_GAIN.getLNAGain();
}
if( mComboLNAGain.isEnabled() )
{
mController.setLNAGain( lnaGain, true );
}
mSelectedConfig.setLNAGain( lnaGain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this,
"R820T Tuner Controller - couldn't apply the LNA "
+ "gain setting - " + e.getLocalizedMessage() );
mLog.error( "R820T Tuner Controller - couldn't apply LNA "
+ "gain setting - ", e );
}
}
} );
mComboLNAGain.setToolTipText( "<html>LNA Gain. Set master gain "
+ "to <b>MANUAL</b> to enable adjustment</html>" );
mComboLNAGain.setEnabled( false );
gainPanel.add( new JLabel( "LNA" ) );
gainPanel.add( mComboLNAGain );
/* VGA Gain Control */
mComboVGAGain = new JComboBox<R820TVGAGain>( R820TVGAGain.values() );
mComboVGAGain.setSelectedItem( mSelectedConfig.getVGAGain() );
mComboVGAGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
try
{
R820TVGAGain vgaGain =
(R820TVGAGain)mComboVGAGain.getSelectedItem();
if( vgaGain == null )
{
vgaGain = DEFAULT_GAIN.getVGAGain();
}
if( mComboVGAGain.isEnabled() )
{
mController.setVGAGain( vgaGain, true );
}
mSelectedConfig.setVGAGain( vgaGain );
save();
}
catch ( UsbException e )
{
JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this,
"R820T Tuner Controller - couldn't apply the VGA "
+ "gain setting - " + e.getLocalizedMessage() );
mLog.error( "R820T Tuner Controller - couldn't apply VGA "
+ "gain setting", e );
}
}
} );
mComboVGAGain.setToolTipText( "<html>VGA Gain. Set master gain "
+ "to <b>MANUAL</b> to enable adjustment</html>" );
mComboVGAGain.setEnabled( false );
gainPanel.add( new JLabel( "VGA" ) );
gainPanel.add( mComboVGAGain, "wrap" );
add( gainPanel, "span" );
/**
* Create a new configuration
*/
mNewConfiguration = new JButton( "New" );
mNewConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
TunerConfiguration config =
mResourceManager.getSettingsManager()
.addNewTunerConfiguration(
TunerType.RAFAELMICRO_R820T,
"New Configuration" );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedItem( config );
repaint();
}
} );
add( mNewConfiguration, "growx,push" );
/**
* Delete the currently selected configuration
*/
mDeleteConfiguration = new JButton( "Delete" );
mDeleteConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
R820TTunerConfiguration selected =
(R820TTunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
int n = JOptionPane.showConfirmDialog(
R820TTunerConfigurationPanel.this,
"Are you sure you want to delete '"
+ selected.getName() + "'?",
"Are you sure?",
JOptionPane.YES_NO_OPTION );
if( n == JOptionPane.YES_OPTION )
{
mResourceManager.getSettingsManager()
.deleteTunerConfiguration( selected );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedIndex( 0 );
repaint();
}
}
}
} );
add( mDeleteConfiguration, "growx,push,wrap" );
}
/**
* Updates gui controls with the values from the tuner configuration
* @param config - tuner configuration
*/
private void update( R820TTunerConfiguration config )
{
mSelectedConfig = config;
try
{
mController.apply( config );
mName.setText( config.getName() );
mFrequencyCorrection.setValue( config.getFrequencyCorrection() );
mComboMixerGain.setSelectedItem( mSelectedConfig.getMixerGain() );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
mComboVGAGain.setSelectedItem( mSelectedConfig.getVGAGain() );
/* Apply master gain last so that the Mixer, LNA, and VGA gain
* settings are updated with the master setting where necessary */
mComboMasterGain.setSelectedItem( mSelectedConfig.getMasterGain() );
mComboSampleRate.setSelectedItem( mSelectedConfig.getSampleRate() );
mResourceManager.getSettingsManager().setSelectedTunerConfiguration(
TunerType.RAFAELMICRO_R820T, mController.getUniqueID(), config );
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
R820TTunerConfigurationPanel.this,
"R820T Tuner Controller - couldn't "
+ "apply the tuner configuration settings - " +
e1.getLocalizedMessage() );
mLog.error( "R820T Tuner Controller - couldn't apply "
+ "config [" + config.getName() + "]", e1 );
}
}
/**
* Constructs a combo box model for the tuner configuration combo component
* by assembling a list of the tuner configurations appropriate for this
* specific tuner
*/
private ComboBoxModel<R820TTunerConfiguration> getModel()
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.RAFAELMICRO_R820T );
DefaultComboBoxModel<R820TTunerConfiguration> model =
new DefaultComboBoxModel<R820TTunerConfiguration>();
for( TunerConfiguration config: configs )
{
model.addElement( (R820TTunerConfiguration)config );
}
return model;
}
/**
* Retrieves a specific (named) tuner configuration
*/
private R820TTunerConfiguration getNamedConfiguration( String name )
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.RAFAELMICRO_R820T );
for( TunerConfiguration config: configs )
{
if( config.getName().contentEquals( name ) )
{
return (R820TTunerConfiguration)config;
}
}
return null;
}
/**
* Saves current tuner configuration settings
*/
private void save()
{
mResourceManager.getSettingsManager().save();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 settings;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import settings.ColorSetting.ColorSettingName;
/**
* JMenuItem for selecting a color and automatically setting (saving) the
* color selection in the settings manager
*/
public class ColorSettingResetAllMenuItem extends JMenuItem
{
private static final long serialVersionUID = 1L;
private ColorSettingName mColorSettingName;
private SettingsManager mSettingsManager;
private Color mCurrentColor;
public ColorSettingResetAllMenuItem( SettingsManager settingsManager,
ColorSettingName colorSettingName )
{
super( "Reset - " + colorSettingName.getLabel() );
mSettingsManager = settingsManager;
mColorSettingName = colorSettingName;
addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
mSettingsManager.resetAllColorSettings();
}
} );
}
}
<file_sep>package decode.p25.message.ldu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.ldu.LDU1Message;
import decode.p25.message.tsbk.osp.control.SystemService;
import decode.p25.reference.LinkControlOpcode;
public class RFSSStatusBroadcast extends LDU1Message
implements IdentifierReceiver
{
private final static Logger mLog =
LoggerFactory.getLogger( RFSSStatusBroadcast.class );
public static final int[] LRA = { 364,365,366,367,372,373,374,375 };
public static final int[] SYSTEM_ID = { 384,385,386,387,536,537,538,539,540,
541,546,547 };
public static final int[] RFSS_ID = { 548,549,550,551,556,557,558,559 };
public static final int[] SITE_ID = { 560,561,566,567,568,569,570,571 };
public static final int[] IDENTIFIER = { 720,721,722,723 };
public static final int[] CHANNEL = { 724,725,730,731,732,733,734,735,740,
741,742,743 };
public static final int[] SYSTEM_SERVICE_CLASS = { 744,745,750,751,752,753,
754,755 };
private IBandIdentifier mIdentifierUpdate;
public RFSSStatusBroadcast( LDU1Message message )
{
super( message );
}
@Override
public String getEventType()
{
return LinkControlOpcode.RFSS_STATUS_BROADCAST.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " LRA:" + getLocationRegistrationArea() );
sb.append( " SYS:" + getSystem() );
sb.append( " SITE:" + getRFSubsystemID() + "-" + getSiteID() );
sb.append( " CHAN:" + getChannelNumber() );
sb.append( " " + SystemService.toString( getSystemServiceClass() ) );
sb.append( " " + mMessage.toString() );
return sb.toString();
}
public String getLocationRegistrationArea()
{
return mMessage.getHex( LRA, 2 );
}
public String getSystem()
{
return mMessage.getHex( SYSTEM_ID, 3 );
}
public String getRFSubsystemID()
{
return mMessage.getHex( RFSS_ID, 2 );
}
public String getSiteID()
{
return mMessage.getHex( SITE_ID, 2 );
}
public int getIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
public String getChannel()
{
return getIdentifier() + "-" + getChannelNumber();
}
public int getChannelNumber()
{
return mMessage.getInt( CHANNEL );
}
public int getSystemServiceClass()
{
return mMessage.getInt( SYSTEM_SERVICE_CLASS );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
mIdentifierUpdate = message;
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 1 ];
identifiers[ 0 ] = getIdentifier();
return identifiers;
}
public long getDownlinkFrequency()
{
return calculateDownlink( mIdentifierUpdate, getChannelNumber() );
}
public long getUplinkFrequency()
{
return calculateUplink( mIdentifierUpdate, getChannelNumber() );
}
}
<file_sep>package decode.p25.reference;
public enum Response
{
ACCEPT,
FAIL,
DENY,
REFUSED,
UNKNOWN;
public static Response fromValue( int value )
{
if( 0 <= value && value <= 4 )
{
return values()[ value ];
}
return UNKNOWN;
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.IBandIdentifier;
import decode.p25.reference.LinkControlOpcode;
public class ChannelIdentifierUpdateExplicit extends TDULinkControlMessage
implements IBandIdentifier
{
private final static Logger mLog =
LoggerFactory.getLogger( ChannelIdentifierUpdateExplicit.class );
public static final int[] IDENTIFIER = { 72,73,74,75 };
public static final int[] BANDWIDTH = { 88,89,90,91 };
public static final int[] TRANSMIT_OFFSET = { 92,93,94,95,96,97,98,99,112,
113,114,115,116,117 };
public static final int[] CHANNEL_SPACING = { 118,119,120,121,122,
123,136,137,138,139 };
public static final int[] BASE_FREQUENCY = { 140,141,142,143,144,145,146,
147,160,161,162,163,164,165,166,167,168,169,170,171,184,185,186,
187,188,189,190,191,192,193,194,195 };
public ChannelIdentifierUpdateExplicit( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.CHANNEL_IDENTIFIER_UPDATE_EXPLICIT.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " IDEN:" + getIdentifier() );
sb.append( " BASE:" + getBaseFrequency() );
sb.append( " BW:" + getBandwidth() );
sb.append( " SPACING:" + getChannelSpacing() );
sb.append( " OFFSET:" + getTransmitOffset() );
return sb.toString();
}
@Override
public int getIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
/**
* Channel bandwidth in hertz
*/
@Override
public int getBandwidth()
{
return mMessage.getInt( BANDWIDTH ) * 125;
}
@Override
public long getChannelSpacing()
{
return mMessage.getLong( CHANNEL_SPACING ) * 125l;
}
@Override
public long getBaseFrequency()
{
return mMessage.getLong( BASE_FREQUENCY ) * 5l;
}
@Override
public long getTransmitOffset()
{
return -1 * mMessage.getLong( TRANSMIT_OFFSET ) * 250000l;
}
}
<file_sep>package controller.channel;
public class ChannelValidationException extends Exception
{
private static final long serialVersionUID = 1L;
public ChannelValidationException( String validationMessage )
{
super( validationMessage );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.Arrays;
import sample.complex.ComplexSample;
public class ComplexSampleBufferAssembler
{
private ByteBuffer mByteBuffer;
private int mSizeInBytes;
public ComplexSampleBufferAssembler( int size )
{
mSizeInBytes = size * 4;
//Allocate a byte buffer with 4 bytes per sample (ie 2 x 16-bit samples)
mByteBuffer = ByteBuffer.allocate( mSizeInBytes );
mByteBuffer.order( ByteOrder.LITTLE_ENDIAN );
}
/**
* Load the sample's bytes, left then right, little endian, into the
* backing byte array
*/
public void put( ComplexSample sample )
{
mByteBuffer.putShort( (short)( sample.left() * Short.MAX_VALUE ) );
mByteBuffer.putShort( (short)( sample.right() * Short.MAX_VALUE ) );
}
/**
* Indicates if there is room for more samples in the buffer, or if it is full
*/
public boolean hasRemaining()
{
return mByteBuffer.hasRemaining();
}
/**
* Returns a copy of the byte array backing this buffer
*/
public ByteBuffer get()
{
return ByteBuffer.wrap( Arrays.copyOf( mByteBuffer.array(), mSizeInBytes ) );
}
/**
* Clear the bytes from the underlying buffer and reset the pointer to 0.
*/
public void clear()
{
mByteBuffer.clear();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner;
import gui.control.JFrequencyControl;
import source.SourceEditor;
import source.config.SourceConfigTuner;
import source.config.SourceConfiguration;
import controller.ResourceManager;
public class TunerEditor extends SourceEditor
{
private static final long serialVersionUID = 1L;
private JFrequencyControl mFrequencyControl;
public TunerEditor( ResourceManager resourceManager,
SourceConfiguration config )
{
super( resourceManager, config );
initGUI();
}
public void reset()
{
mFrequencyControl.setFrequency(
((SourceConfigTuner)mConfig).getFrequency(), false );
}
public void save()
{
((SourceConfigTuner)mConfig).setFrequency( mFrequencyControl.getFrequency() );
}
private void initGUI()
{
mFrequencyControl = new JFrequencyControl();
mFrequencyControl.setFrequency(
((SourceConfigTuner)mConfig).getFrequency(), false );
add( mFrequencyControl );
}
}
<file_sep>package decode.p25.message.tdu;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.P25Message;
import decode.p25.reference.DataUnitID;
import edac.CRC;
public class TDUMessage extends P25Message
{
public TDUMessage( BinaryMessage message, DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
/* NID CRC is checked in the message framer, thus a constructed message
* means it passed the CRC */
mCRC = new CRC[ 1 ];
mCRC[ 0 ] = CRC.PASSED;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 spectrum;
import java.awt.Color;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.RenderingHints;
import java.awt.event.ComponentEvent;
import java.awt.event.ComponentListener;
import java.awt.geom.Line2D;
import java.awt.geom.Rectangle2D;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.swing.JPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import settings.ColorSetting;
import settings.ColorSetting.ColorSettingName;
import settings.Setting;
import settings.SettingChangeListener;
import source.tuner.TunerChannel;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.FrequencyChangeListener;
import controller.ResourceManager;
import controller.channel.Channel;
import controller.channel.Channel.ChannelType;
import controller.channel.ChannelEvent;
import controller.channel.ChannelEventListener;
public class OverlayPanel extends JPanel
implements ChannelEventListener,
FrequencyChangeListener,
SettingChangeListener
{
private static final long serialVersionUID = 1L;
private final static Logger mLog =
LoggerFactory.getLogger( OverlayPanel.class );
private static DecimalFormat CURSOR_FORMAT = new DecimalFormat( "000.00000" );
private DecimalFormat mFrequencyFormat = new DecimalFormat( "0.0" );
private long mFrequency = 0;
private int mBandwidth = 0;
private Point mCursorLocation = new Point( 0, 0 );
private boolean mCursorVisible = false;
/**
* Colors used by this component
*/
private Color mColorChannelConfig;
private Color mColorChannelConfigProcessing;
private Color mColorChannelConfigSelected;
private Color mColorSpectrumBackground;
private Color mColorSpectrumCursor;
private Color mColorSpectrumLine;
//All channels
private ArrayList<Channel> mChannels = new ArrayList<Channel>();
//Currently visible/displayable channels
private CopyOnWriteArrayList<Channel> mVisibleChannels =
new CopyOnWriteArrayList<Channel>();
private ChannelDisplay mChannelDisplay = ChannelDisplay.ALL;
//Defines the offset at the bottom of the spectral display to account for
//the frequency labels
private double mSpectrumInset = 20.0d;
private LabelSizeMonitor mLabelSizeMonitor = new LabelSizeMonitor();
private ResourceManager mResourceManager;
/**
* Translucent overlay panel for displaying channel configurations,
* processing channels, selected channels, frequency labels and lines, and
* a cursor with a frequency readout.
*/
public OverlayPanel( ResourceManager resourceManager )
{
mResourceManager = resourceManager;
addComponentListener( mLabelSizeMonitor );
//Set the background transparent, so the spectrum display can be seen
setOpaque( false );
//Fetch color settings from settings manager
setColors();
}
public void dispose()
{
mChannels.clear();
mVisibleChannels.clear();
mResourceManager = null;
}
public ChannelDisplay getChannelDisplay()
{
return mChannelDisplay;
}
public void setChannelDisplay( ChannelDisplay display )
{
mChannelDisplay = display;
}
public void setCursorLocation( Point point )
{
mCursorLocation = point;
repaint();
}
public void setCursorVisible( boolean visible )
{
mCursorVisible = visible;
repaint();
}
/**
* Fetches the color settings from the settings manager
*/
private void setColors()
{
mColorChannelConfig = getColor( ColorSettingName.CHANNEL_CONFIG );
mColorChannelConfigProcessing =
getColor( ColorSettingName.CHANNEL_CONFIG_PROCESSING );
mColorChannelConfigSelected =
getColor( ColorSettingName.CHANNEL_CONFIG_SELECTED );
mColorSpectrumCursor = getColor( ColorSettingName.SPECTRUM_CURSOR );
mColorSpectrumLine = getColor( ColorSettingName.SPECTRUM_LINE );
mColorSpectrumBackground =
getColor( ColorSettingName.SPECTRUM_BACKGROUND );
}
/**
* Fetches a named color setting from the settings manager. If the setting
* doesn't exist, creates the setting using the defaultColor
*/
private Color getColor( ColorSettingName name )
{
ColorSetting setting =
mResourceManager.getSettingsManager()
.getColorSetting( name );
return setting.getColor();
}
/**
* Monitors for setting changes. Colors can be changed by external actions
* and will automatically update in this class
*/
@Override
public void settingChanged( Setting setting )
{
if( setting instanceof ColorSetting )
{
ColorSetting colorSetting = (ColorSetting)setting;
switch( colorSetting.getColorSettingName() )
{
case CHANNEL_CONFIG:
mColorChannelConfig = colorSetting.getColor();
break;
case CHANNEL_CONFIG_PROCESSING:
mColorChannelConfigProcessing = colorSetting.getColor();
break;
case CHANNEL_CONFIG_SELECTED:
mColorChannelConfigSelected = colorSetting.getColor();
break;
case SPECTRUM_BACKGROUND:
mColorSpectrumBackground = colorSetting.getColor();
break;
case SPECTRUM_CURSOR:
mColorSpectrumCursor = colorSetting.getColor();
break;
case SPECTRUM_LINE:
mColorSpectrumLine = colorSetting.getColor();
break;
default:
break;
}
}
}
/**
* Renders the channel configs, lines, labels, and cursor
*/
@Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Graphics2D graphics = (Graphics2D) g;
graphics.setBackground( mColorSpectrumBackground );
RenderingHints renderHints =
new RenderingHints( RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON );
renderHints.put( RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY );
graphics.setRenderingHints( renderHints );
drawFrequencies( graphics );
drawChannels( graphics );
drawCursor( graphics );
}
/**
* Draws a cursor on the panel, whenever the mouse is hovering over the
* panel
*/
private void drawCursor( Graphics2D graphics )
{
if( mCursorVisible )
{
drawFrequencyLine( graphics,
mCursorLocation.x,
mColorSpectrumCursor );
String frequency = CURSOR_FORMAT.format(
getFrequencyFromAxis( mCursorLocation.getX() ) / 1000000.0D );
graphics.drawString( frequency ,
mCursorLocation.x + 5,
mCursorLocation.y );
}
}
/**
* Draws the frequency lines and labels every 10kHz
*/
private void drawFrequencies( Graphics2D graphics )
{
long minFrequency = getMinFrequency();
long maxFrequency = getMaxFrequency();
int major = mLabelSizeMonitor.getMajorTickIncrement( graphics );
int minor = mLabelSizeMonitor.getMinorTickIncrement( graphics );
int label = mLabelSizeMonitor.getLabelIncrement( graphics );
long start = minFrequency - ( minFrequency % label );
long frequency = start;
while( frequency < maxFrequency )
{
int offset = (int)( frequency - start );
if( offset % label == 0 )
{
drawFrequencyLineAndLabel( graphics, frequency );
}
else if( offset % major == 0 )
{
drawTickLine( graphics, frequency, true );
}
else
{
drawTickLine( graphics, frequency, false );
}
frequency += minor;
}
}
/**
* Draws a vertical line and a corresponding frequency label at the bottom
*/
private void drawFrequencyLineAndLabel( Graphics2D graphics, long frequency )
{
double xAxis = getAxisFromFrequency( frequency );
drawFrequencyLine( graphics, xAxis, mColorSpectrumLine );
drawTickLine( graphics, frequency, false );
graphics.setColor( mColorSpectrumLine );
drawFrequencyLabel( graphics, xAxis, frequency );
}
/**
* Draws a vertical line at the xaxis
*/
private void drawTickLine( Graphics2D graphics, long frequency, boolean major )
{
graphics.setColor( mColorSpectrumLine );
double xAxis = getAxisFromFrequency( frequency );
double start = getSize().getHeight() - mSpectrumInset;
double end = start + ( major ? 6.0d : 3.0d );
graphics.draw( new Line2D.Double( xAxis, start, xAxis, end ) );
}
/**
* Draws a vertical line at the xaxis
*/
private void drawFrequencyLine( Graphics2D graphics, double xaxis, Color color )
{
graphics.setColor( color );
graphics.draw( new Line2D.Double( xaxis, 0.0d,
xaxis, getSize().getHeight() - mSpectrumInset ) );
}
/**
* Draws a vertical line at the xaxis
*/
private void drawAFC( Graphics2D graphics, double xaxis, boolean isError )
{
double height = getSize().getHeight() - mSpectrumInset;
if( isError )
{
graphics.setColor( Color.YELLOW );
graphics.draw( new Line2D.Double( xaxis, height * 0.75d,
xaxis, height - 1.0d ) );
}
else
{
graphics.setColor( Color.LIGHT_GRAY );
graphics.draw( new Line2D.Double( xaxis, height * 0.65d,
xaxis, height - 1.0d ) );
}
}
/**
* Returns the x-axis value corresponding to the frequency
*/
public double getAxisFromFrequency( long frequency )
{
double canvasMiddle = getSize().getWidth() / 2.0d;
//Determine frequency offset from middle
double frequencyOffset = mFrequency - frequency;
//Determine ratio of offset to bandwidth
double ratio = frequencyOffset / (double)mBandwidth;
//Calculate offset against the total width
double xOffset = getSize().getWidth() * ratio;
//Apply the offset against the canvas middle
return canvasMiddle - xOffset;
}
/**
* Returns the frequency corresponding to the x-axis value
*/
public long getFrequencyFromAxis( double xAxis )
{
double width = getSize().getWidth();
double offset = xAxis / width;
return getMinFrequency() + Math.round( (double)mBandwidth * offset );
}
/**
* Draws a frequency label at the x-axis position, at the bottom of the panel
*/
private void drawFrequencyLabel( Graphics2D graphics,
double xaxis,
long frequency )
{
String label = mFrequencyFormat.format( (float)frequency / 1000000.0f );
FontMetrics fontMetrics = graphics.getFontMetrics( this.getFont() );
Rectangle2D rect = fontMetrics.getStringBounds( label, graphics );
float xOffset = (float)rect.getWidth() / 2;
// graphics.drawString( label, (float)( xaxis - xOffset ),
// (float)( getSize().getHeight() - ( mSpectrumInset * 0.2d ) ) );
graphics.drawString( label, (float)( xaxis - xOffset ),
(float)( getSize().getHeight() - 2.0f ) );
}
/**
* Draws visible channel configs as translucent shaded frequency regions
*/
private void drawChannels( Graphics2D graphics )
{
for( Channel channel: mVisibleChannels )
{
if( mChannelDisplay == ChannelDisplay.ALL ||
( mChannelDisplay == ChannelDisplay.ENABLED &&
channel.isProcessing() ) )
{
//Choose the correct background color to use
if( channel.isSelected() )
{
graphics.setColor( mColorChannelConfigSelected );
}
else if( channel.isProcessing() )
{
graphics.setColor( mColorChannelConfigProcessing );
}
else
{
graphics.setColor( mColorChannelConfig );
}
TunerChannel tunerChannel = channel.getTunerChannel();
if( tunerChannel != null )
{
double xAxis = getAxisFromFrequency( tunerChannel.getFrequency() );
double width = (double)( tunerChannel.getBandwidth() ) /
(double)mBandwidth * getSize().getWidth();
Rectangle2D.Double box =
new Rectangle2D.Double( xAxis - ( width / 2.0d ),
0.0d, width, getSize().getHeight() - mSpectrumInset );
//Fill the box with the correct color
graphics.fill( box );
graphics.draw( box );
//Change to the line color to render the channel name, etc.
graphics.setColor( mColorSpectrumLine );
//Draw the labels starting at yAxis position 0
double yAxis = 0;
//Draw the system label and adjust the y-axis position
yAxis += drawLabel( graphics,
channel.getSystem().getName(),
this.getFont(),
xAxis,
yAxis,
width );
//Draw the site label and adjust the y-axis position
yAxis += drawLabel( graphics,
channel.getSite().getName(),
this.getFont(),
xAxis,
yAxis,
width );
//Draw the channel label and adjust the y-axis position
yAxis += drawLabel( graphics,
channel.getName(),
this.getFont(),
xAxis,
yAxis,
width );
//Draw the decoder label
drawLabel( graphics,
channel.getDecodeConfiguration().getDecoderType()
.getShortDisplayString(),
this.getFont(),
xAxis,
yAxis,
width );
}
/* Draw Automatic Frequency Control line */
if( channel.hasFrequencyControl() )
{
long frequency = tunerChannel.getFrequency();
long error = frequency + channel.getFrequencyCorrection();
drawAFC( graphics, getAxisFromFrequency( frequency ), false );
drawAFC( graphics, getAxisFromFrequency( error ), true );
}
}
}
}
/**
* Draws a textual label at the x/y position, clipping the end of the text
* to fit within the maxwidth value.
*
* @return height of the drawn label
*/
private double drawLabel( Graphics2D graphics, String text, Font font,
double x, double baseY, double maxWidth )
{
FontMetrics fontMetrics = graphics.getFontMetrics( font );
Rectangle2D label = fontMetrics.getStringBounds( text, graphics );
double offset = label.getWidth() / 2.0d;
double y = baseY + label.getHeight();
/**
* If the label is wider than the max width, left justify the text and
* clip the end of it
*/
if( offset > ( maxWidth / 2.0d ) )
{
label.setRect( x - ( maxWidth / 2.0d ),
y - label.getHeight(),
maxWidth,
label.getHeight() );
graphics.setClip( label );
graphics.drawString( text,
(float)( x - ( maxWidth / 2.0d ) ), (float)y );
graphics.setClip( null );
}
else
{
graphics.drawString( text, (float)( x - offset ), (float)y );
}
return label.getHeight();
}
/**
* Frequency change event handler
*/
@Override
public void frequencyChanged( FrequencyChangeEvent event )
{
mLabelSizeMonitor.frequencyChanged( event );
switch( event.getAttribute() )
{
case SAMPLE_RATE:
mBandwidth = event.getValue().intValue();
if( mBandwidth < 200000 )
{
mFrequencyFormat = new DecimalFormat( "0.00" );
}
else
{
mFrequencyFormat = new DecimalFormat( "0.0" );
}
break;
case FREQUENCY:
mFrequency = event.getValue().longValue();
break;
default:
break;
}
/**
* Reset the visible channel configs list
*/
mVisibleChannels.clear();
long minimum = getMinFrequency();
long maximum = getMaxFrequency();
for( Channel channel: mChannels )
{
if( channel.isWithin( minimum, maximum ) )
{
mVisibleChannels.add( channel );
}
}
}
/**
* Channel change event handler
*/
@Override
@SuppressWarnings( "incomplete-switch" )
public void channelChanged( ChannelEvent event )
{
Channel channel = event.getChannel();
switch( event.getEvent() )
{
case CHANNEL_ADDED:
if( !mChannels.contains( channel ) )
{
mChannels.add( channel );
}
if( channel.isWithin( getMinFrequency(), getMaxFrequency() ) &&
!mVisibleChannels.contains( channel ) )
{
mVisibleChannels.add( channel );
}
break;
case CHANNEL_DELETED:
mChannels.remove( channel );
mVisibleChannels.remove( channel );
break;
case PROCESSING_STOPPED:
if( channel.getChannelType() == ChannelType.TRAFFIC )
{
mChannels.remove( channel );
mVisibleChannels.remove( channel );
}
break;
}
repaint();
}
/**
* Currently displayed minimum frequency
*/
private long getMinFrequency()
{
return mFrequency - ( mBandwidth / 2 );
}
/**
* Currently displayed maximum frequency
*/
private long getMaxFrequency()
{
return mFrequency + ( mBandwidth / 2 );
}
/**
* Returns a list of channel configs that contain the frequency within their
* min/max frequency settings.
*/
public ArrayList<Channel> getChannelsAtFrequency( long frequency )
{
ArrayList<Channel> configs = new ArrayList<Channel>();
for( Channel config: mVisibleChannels )
{
TunerChannel channel = config.getTunerChannel();
if( channel != null &&
channel.getMinFrequency() <= frequency &&
channel.getMaxFrequency() >= frequency )
{
configs.add( config );
}
}
return configs;
}
@Override
public void settingDeleted( Setting setting )
{
// TODO Auto-generated method stub
}
/**
* Monitors the display for resize events so that we can calculate how many
* frequency labels will fit within the current screen real estate
*/
public class LabelSizeMonitor implements ComponentListener,
FrequencyChangeListener
{
private static final int MAJOR_TICK_MINIMUM = 10000; //10 kHz
private static final int MINOR_TICK_MINIMUM = 1000; //1 kHz
private static final int TICK_SPACING_MINIMUM = 10; //pixels
private boolean mUpdateRequired = true;
private LabelDisplay mLabelDisplay = LabelDisplay.DIGIT_3;
private int mMajorTickIncrement;
private int mMinorTickIncrement;
private int mLabelIncrement;
private void update( Graphics2D graphics )
{
if( mUpdateRequired )
{
double width = OverlayPanel.this.getSize().getWidth();
int major = MAJOR_TICK_MINIMUM;
while( width / ( (double)mBandwidth /
(double)major ) < TICK_SPACING_MINIMUM )
{
major *= 10;
}
mMajorTickIncrement = major;
int minor = MINOR_TICK_MINIMUM;
while( width / ( (double)mBandwidth /
(double)minor ) < TICK_SPACING_MINIMUM )
{
minor *= 10;
}
if( minor == major )
{
minor = (int)( major / 2 );
}
mMinorTickIncrement = minor;
FontMetrics fontMetrics =
graphics.getFontMetrics( OverlayPanel.this.getFont() );
Rectangle2D labelDimension = fontMetrics.getStringBounds(
mLabelDisplay.getExample(), graphics );
int maxLabelCount = (int)( width / labelDimension.getWidth() );
int label = major;
while( ( (double)mBandwidth / (double)label ) > maxLabelCount )
{
label += major;
}
mLabelIncrement = label;
mUpdateRequired = false;
}
}
public int getMajorTickIncrement( Graphics2D graphics )
{
update( graphics );
return mMajorTickIncrement;
}
public int getMinorTickIncrement( Graphics2D graphics )
{
update( graphics );
return mMinorTickIncrement;
}
public int getLabelIncrement( Graphics2D graphics )
{
update( graphics );
return mLabelIncrement;
}
public LabelDisplay getLabelDisplay()
{
return mLabelDisplay;
}
@Override
public void componentResized( ComponentEvent arg0 )
{
mUpdateRequired = true;
}
public void componentHidden( ComponentEvent arg0 ) {}
public void componentMoved( ComponentEvent arg0 ) {}
public void componentShown( ComponentEvent arg0 ) {}
@Override
public void frequencyChanged( FrequencyChangeEvent event )
{
switch( event.getAttribute() )
{
case FREQUENCY:
LabelDisplay display = LabelDisplay
.fromFrequency( event.getValue().longValue() );
if( mLabelDisplay != display )
{
mLabelDisplay = display;
mUpdateRequired = true;
}
break;
case SAMPLE_RATE:
mUpdateRequired = true;
break;
default:
break;
}
}
}
/**
* Frequency display formats for determining label sizing and value formatting
*/
public enum LabelDisplay
{
DIGIT_1( " 9.9 " ),
DIGIT_2( " 99.9 " ),
DIGIT_3( " 999.9 " ),
DIGIT_4( " 9999.9 " ),
DIGIT_5( " 99999.9 " );
private String mExample;
private LabelDisplay( String example )
{
mExample = example;
}
public String getExample()
{
return mExample;
}
public static LabelDisplay fromFrequency( long frequency )
{
if( frequency < 10000000l ) //10 MHz
{
return LabelDisplay.DIGIT_1;
}
else if( frequency < 100000000l ) //100 MHz
{
return LabelDisplay.DIGIT_2;
}
else if( frequency < 1000000000l ) //1,000 MHz
{
return LabelDisplay.DIGIT_3;
}
else if( frequency < 10000000000l ) //10,000 MHz
{
return LabelDisplay.DIGIT_4;
}
return LabelDisplay.DIGIT_5;
}
}
public enum ChannelDisplay
{
ALL, ENABLED, NONE;
}
}
<file_sep>package decode.p25.message.tdu.lc;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.reference.LinkControlOpcode;
import decode.p25.reference.Service;
public class SystemServiceBroadcast extends TDULinkControlMessage
{
private final static Logger mLog =
LoggerFactory.getLogger( SystemServiceBroadcast.class );
public static final int[] REQUEST_PRIORITY_LEVEL = { 96,97,98,99 };
public static final int[] AVAILABLE_SERVICES = { 112,113,114,115,116,117,118,
119,120,121,122,123,136,137,138,139,140,141,142,143,144,145,146,147 };
public static final int[] SUPPORTED_SERVICES = { 160,161,162,163,164,165,
166,167,168,169,170,171,184,185,186,187,188,189,190,191,192,193,194,195 };
public SystemServiceBroadcast( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.SYSTEM_SERVICE_BROADCAST.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " SERVICES AVAILABLE " );
sb.append( getAvailableServices() );
sb.append( " SUPPORTED " );
sb.append( getSupportedServices() );
return sb.toString();
}
public List<Service> getAvailableServices()
{
long bitmap = mMessage.getLong( AVAILABLE_SERVICES );
return Service.getServices( bitmap );
}
public List<Service> getSupportedServices()
{
long bitmap = mMessage.getLong( SUPPORTED_SERVICES );
return Service.getServices( bitmap );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 util;
import sample.complex.ComplexSample;
public class Oscillator
{
private double mFrequency;
private double mSampleRate;
private ComplexSample mAnglePerSample;
private ComplexSample mCurrentAngle = new ComplexSample( 0.0f, -1.0f );
/**
* Oscillator produces complex or float samples corresponding to a sine wave
* oscillating at the specified frequency and sample rate
*
* @param frequency - positive or negative frequency in hertz
* @param sampleRate - in hertz
*/
public Oscillator( long frequency, int sampleRate )
{
mSampleRate = (double)sampleRate;
mFrequency = (double)frequency;
update();
}
public ComplexSample getCurrentAngle()
{
return mCurrentAngle;
}
private void update()
{
float anglePerSample =
(float)( 2.0d * Math.PI * mFrequency / mSampleRate );
mAnglePerSample = ComplexSample.fromAngle( anglePerSample );
}
/**
* Sets or changes the frequency of this oscillator
*/
public void setFrequency( long frequency )
{
mFrequency = (double)frequency;
update();
}
/**
* Sets or changes the sample rate of this oscillator
*/
public void setSampleRate( int sampleRate )
{
mSampleRate = (double)sampleRate;
update();
}
/**
* Steps the current angle by the angle per sample amount
*/
private void rotate()
{
mCurrentAngle.multiply( mAnglePerSample );
mCurrentAngle.fastNormalize();
}
/**
* Get next complex sample
*/
public ComplexSample nextComplex()
{
rotate();
return mCurrentAngle.copy();
}
/**
* Get the next float sample
*/
public float nextFloat()
{
rotate();
return mCurrentAngle.real();
}
public static void main( String[] args )
{
Oscillator o = new Oscillator( 1200, 2400 );
for( int x = 0; x < 20; x++ )
{
System.out.println( o.nextComplex().toString() );
}
}
}
<file_sep>package decode.p25.reference;
public enum LinkControlOpcode
{
GROUP_VOICE_CHANNEL_USER( "GRP_VCH_USER ", "Group Voice Channel User", 0 ),
RESERVED_01( "RESERVED_01 ", "Reserved", 1 ),
GROUP_VOICE_CHANNEL_UPDATE( "GRP_VCH_UPDATE ", "Group Voice Channel Grant Update", 2 ),
UNIT_TO_UNIT_VOICE_CHANNEL_USER( "UU_VCH_USER ", "Unit-to-Unit Voice Channel User", 3 ),
GROUP_VOICE_CHANNEL_UPDATE_EXPLICIT( "GRP_VCH_UPD_EXPL", "Group Voice Channel Update Explicit", 4 ),
UNIT_TO_UNIT_ANSWER_REQUEST( "UU_ANS_REQ ", "Unit-to-Unit Answer Request", 5 ),
TELEPHONE_INTERCONNECT_VOICE_CHANNEL_USER( "TEL_INT_VCH_USER", "Telephone Interconnect Voice Channel User", 6 ),
TELEPHONE_INTERCONNECT_ANSWER_REQUEST( "TEL_INT_ANS_RQST", "Telephone Interconnect Answer Request", 7 ),
RESERVED_08( "RESERVED_08 ", "Reserved", 8 ),
RESERVED_09( "RESERVED_09 ", "Reserved", 9 ),
RESERVED_0A( "RESERVED_0A ", "Reserved", 10 ),
RESERVED_0B( "RESERVED_0B ", "Reserved", 11 ),
RESERVED_0C( "RESERVED_0C ", "Reserved", 12 ),
RESERVED_0D( "RESERVED_0D ", "Reserved", 13 ),
RESERVED_0E( "RESERVED_0E ", "Reserved", 14 ),
CALL_TERMINATION_OR_CANCELLATION( "CALL TERMINATION", "Call Termination Cancellation", 15 ),
GROUP_AFFILIATION_QUERY( "GRP_AFFIL_QUERY ", "Group Affiliation Query", 16 ),
UNIT_REGISTRATION_COMMAND( "UNIT_REG_COMMAND", "Unit Registration Command", 17 ),
UNIT_AUTHENTICATION_COMMAND( "UNIT_AUTHEN_CMD ", "Unit Authentication Command", 18 ),
STATUS_QUERY( "STATUS QUERY ", "Status Query", 19 ),
STATUS_UPDATE( "STATUS_UPDATE ", "Status Update", 20 ),
MESSAGE_UPDATE( "MESSAGE UPDATE ", "Message Update", 21 ),
CALL_ALERT( "CALL ALERT", "Call Alert", 22 ),
EXTENDED_FUNCTION_COMMAND( "EXT FUNC COMMAND", "Extended Function Command", 23 ),
CHANNEL_IDENTIFIER_UPDATE( "CHAN IDEN UPDATE", "Channel Identifier Update", 24 ),
CHANNEL_IDENTIFIER_UPDATE_EXPLICIT( "CHAN IDEN UPD EX", "Channel Identifier Update Explicit", 25 ),
RESERVED_1A( "RESERVED_1A ", "Reserved", 26 ),
RESERVED_1B( "RESERVED_1B ", "Reserved", 27 ),
RESERVED_1C( "RESERVED_1C ", "Reserved", 28 ),
RESERVED_1D( "RESERVED_1D ", "Reserved", 29 ),
RESERVED_1E( "RESERVED_1E ", "Reserved", 30 ),
RESERVED_1F( "RESERVED_1F ", "Reserved", 31 ),
SYSTEM_SERVICE_BROADCAST( "SYS_SVC_BCAST ", "System Service Broadcast", 32 ),
SECONDARY_CONTROL_CHANNEL_BROADCAST( "SEC_CCH_BROADCST", "Secondary Control Channel Broadcast", 33 ),
ADJACENT_SITE_STATUS_BROADCAST( "ADJ SITE STATUS ", "Adjacent Site Status Broadcast", 34 ),
RFSS_STATUS_BROADCAST( "RFSS_STATUS_BCST", "RFSS Status Broadcast", 35 ),
NETWORK_STATUS_BROADCAST( "NET_STATUS_BCAST", "Network Status Broadcast", 36 ),
PROTECTION_PARAMETER_BROADCAST( "ENCRYPT_PAR_BCST", "Protection Parameter Broadcast", 37 ),
SECONDARY_CONTROL_CHANNEL_BROADCAST_EXPLICIT( "SCCB_CCH_BCST_EX", "Secondary Control Channel Broadcast-Explicit", 38 ),
ADJACENT_SITE_STATUS_BROADCAST_EXPLICIT( "ADJ SITE STAT EX", "Adjacent Site Status Broadcast Explicit", 39 ),
RFSS_STATUS_BROADCAST_EXPLICIT( "RFSS STAT BCST E", "RFSS Status Broadcast Explicit", 40 ),
NETWORK_STATUS_BROADCAST_EXPLICIT( "NET STAT BCAST E", "Network Status Broadcast", 41 ),
RESERVED_2A( "RESERVED_2A ", "Reserved", 42 ),
RESERVED_2B( "RESERVED_2B ", "Reserved", 43 ),
RESERVED_2C( "RESERVED_2C ", "Reserved", 44 ),
RESERVED_2D( "RESERVED_2D ", "Reserved", 45 ),
RESERVED_2E( "RESERVED_2E ", "Reserved", 46 ),
RESERVED_2F( "RESERVED_2F ", "Reserved", 47 ),
RESERVED_30( "RESERVED_30 ", "Reserved", 48 ),
RESERVED_31( "RESERVED_31 ", "Reserved", 49 ),
RESERVED_32( "RESERVED_32 ", "Reserved", 50 ),
RESERVED_33( "RESERVED_33 ", "Reserved", 51 ),
RESERVED_34( "RESERVED_34 ", "Reserved", 52 ),
RESERVED_35( "RESERVED_35 ", "Reserved", 53 ),
RESERVED_36( "RESERVED_36 ", "Reserved", 54 ),
RESERVED_37( "RESERVED_37 ", "Reserved", 55 ),
RESERVED_38( "RESERVED_38 ", "Reserved", 56 ),
RESERVED_39( "RESERVED_39 ", "Reserved", 57 ),
RESERVED_3A( "RESERVED_3A ", "Reserved", 58 ),
RESERVED_3B( "RESERVED_3B ", "Reserved", 59 ),
RESERVED_3C( "RESERVED_3C ", "Reserved", 60 ),
RESERVED_3D( "RESERVED_3D ", "Reserved", 61 ),
RESERVED_3E( "RESERVED_3E ", "Reserved", 62 ),
RESERVED_3F( "RESERVED_3F ", "Reserved", 63 ),
UNKNOWN( "UNKNOWN ", "Unknown", -1 );
private String mLabel;
private String mDescription;
private int mCode;
private LinkControlOpcode( String label, String description, int code )
{
mLabel = label;
mDescription = description;
mCode = code;
}
public String getLabel()
{
return mLabel;
}
public String getDescription()
{
return mDescription;
}
public int getCode()
{
return mCode;
}
public static LinkControlOpcode fromValue( int value )
{
if( 0 <= value && value <= 63 )
{
return values()[ value ];
}
return UNKNOWN;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 map;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.Point2D;
import java.util.Set;
import javax.swing.ImageIcon;
import org.jdesktop.swingx.JXMapViewer;
import settings.SettingsManager;
public class PlottableEntityRenderer
{
private SettingsManager mSettingsManager;
public PlottableEntityRenderer( SettingsManager settingsManager )
{
mSettingsManager = settingsManager;
}
public void paintPlottableEntity( Graphics2D g,
JXMapViewer viewer,
PlottableEntity entity,
boolean antiAliasing )
{
Graphics2D graphics = (Graphics2D)g.create();
if( antiAliasing )
{
graphics.setRenderingHint( RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON );
}
/**
* Use the entity's preferred color for lines and labels
*/
graphics.setColor( entity.getColor() );
/**
* Convert the lat/long geoposition to an x/y point on the viewer
*/
Point2D point = viewer.getTileFactory().geoToPixel(
entity.getCurrentGeoPosition(), viewer.getZoom() );
/**
* Paint the route first, so the icon and label overlay it
*/
paintRoute( graphics, viewer, entity );
/**
* Paint the icon at the current location
*/
ImageIcon icon = getIcon( entity ).getImageIcon();
paintIcon( graphics, point, icon );
/**
* Paint the label offset to the right of the icon
*/
paintLabel( graphics, point, entity, (int)( icon.getIconWidth() / 2 ), 0 );
/**
* Cleanup
*/
graphics.dispose();
}
private MapIcon getIcon( PlottableEntity entity )
{
return mSettingsManager.getMapIcon( entity.getMapIconName() );
}
private void paintIcon( Graphics2D graphics,
Point2D point,
ImageIcon icon )
{
graphics.drawImage( icon.getImage(),
(int)point.getX() - ( icon.getIconWidth() / 2 ),
(int)point.getY() - ( icon.getIconHeight() / 2 ),
null );
}
private void paintLabel( Graphics2D graphics,
Point2D point,
PlottableEntity entity,
int xOffset,
int yOffset )
{
graphics.drawString( entity.getLabel(),
(int)point.getX() + xOffset,
(int)point.getY() + yOffset );
}
/**
* Paints a two-tone route from the entity's list of plottables (locations).
* using black as a wider background route, and the entity's preferred color
* as a narrower foreground route.
*/
private void paintRoute( Graphics2D graphics,
JXMapViewer viewer,
PlottableEntity entity )
{
Set<Plottable> plottables = entity.getPlottables();
if( plottables.size() > 1 )
{
// Draw the route with a black background line
graphics.setColor( Color.BLACK );
graphics.setStroke( new BasicStroke( 3 ) );
drawRoute( plottables, graphics, viewer );
// Draw the route again, in the entity's preferred color
graphics.setColor( entity.getColor() );
graphics.setStroke( new BasicStroke( 1 ) );
drawRoute( plottables, graphics, viewer );
}
}
/**
* Draws a route from a list of plottables
*/
private void drawRoute( Set<Plottable> plottables,
Graphics2D g,
JXMapViewer viewer )
{
Point2D lastPoint = null;
for (Plottable plottable: plottables )
{
// convert geo-coordinate to world bitmap pixel
Point2D currentPoint = viewer.getTileFactory()
.geoToPixel( plottable.getGeoPosition(), viewer.getZoom() );
if( lastPoint != null )
{
g.drawLine( (int)lastPoint.getX(), (int)lastPoint.getY(),
(int)currentPoint.getX(), (int)currentPoint.getY() );
}
lastPoint = currentPoint;
}
}
}
<file_sep>package decode.p25.audio;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Control;
import javax.sound.sampled.Control.Type;
import javax.sound.sampled.DataLine;
import javax.sound.sampled.LineListener;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.TargetDataLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import audio.AudioFormats;
public class IMBETargetDataLine implements TargetDataLine
{
private final static Logger mLog =
LoggerFactory.getLogger( IMBETargetDataLine.class );
public static final int BUFFER_SIZE = 18;
public byte[] mFrame;
/**
* IMBE target dataline provides a java audio system compatible interface to
* ingest and buffer raw IMBE audio frames and expose a standard audio
* system interface for follow-on audio processors to consume the output audio
* stream provided by this interface.
*/
public IMBETargetDataLine()
{
}
@Override
public void open( AudioFormat format, int bufferSize )
throws LineUnavailableException
{
if( format != AudioFormats.IMBE_AUDIO_FORMAT )
{
throw new LineUnavailableException( "Unsupported format" );
}
}
@Override
public void open() throws LineUnavailableException
{
open( AudioFormats.IMBE_AUDIO_FORMAT, BUFFER_SIZE );
}
@Override
public void close()
{
}
@Override
public boolean isOpen()
{
return true;
}
@Override
public void open( AudioFormat format ) throws LineUnavailableException
{
open( format, BUFFER_SIZE );
}
@Override
public int read( byte[] buffer, int offset, int length )
{
if( mFrame != null )
{
System.arraycopy( mFrame, 0, buffer, 0, mFrame.length );
return mFrame.length;
}
return 0;
}
// private int getBytesAvailable()
// {
// return 1920;
// return mFrame.length;
// }
/**
* Primary inject point for submitting IMBE frame data into the audio
* system via this data line
*/
public void receive( byte[] data )
{
mFrame = data;
}
/**
* Not implemented
*/
@Override
public void drain()
{
}
/**
* Flushes (deletes) any buffered audio frames. If a frame is currently
* being processed it will continue and a stop event will be broadcast
* after the current frame has been dispatched.
*/
@Override
public void flush()
{
mFrame = null;
}
/**
* If the line is open, sets the running state to true and attempts to
* retrieve a frame from the buffer. If successful, a line start event is
* broadcast. If no frames are currently buffered, then a line start event
* will be broadcast once the first frame is received.
*
* If the line is closed, or if the running state is already set to true,
* then the start() is ignored.
*/
@Override
public void start()
{
}
/**
* Stops this data line, sets running and active states to false and purges
* any currently buffered data frames. Note: the line will remain open
* until close() is invoked and incoming frame data will continue to buffer.
*/
@Override
public void stop()
{
}
/**
* Indicates if this line us currently opened, but does not reflect if the
* line is currently streaming data. Use the isActive() method to determine
* streaming status.
*/
@Override
public boolean isRunning()
{
return true;
}
/**
* Indicates if this line is currently streaming data
*/
@Override
public boolean isActive()
{
return true;
}
/**
* IMBE AudioFormat produced by this target data line.
*/
@Override
public AudioFormat getFormat()
{
return AudioFormats.IMBE_AUDIO_FORMAT;
}
/**
* Size of the internal buffer in bytes. This method will not return the
* true size of the buffer if this data line was constructed with a buffer
* size other than the default (250 frames) buffer size.
*/
@Override
public int getBufferSize()
{
return 18;
}
/**
* Number of bytes of imbe frame data available. Value will be the number
* of buffered frames times 18 bytes.
*/
@Override
public int available()
{
return 18;
}
/**
* Current number of frames provided by this data line since it was opened.
* Counter rolls over once it exceeds the max integer value.
*/
@Override
public int getFramePosition()
{
return 0;
}
/**
* Current number of frames provided by this data line since it was opened
*/
@Override
public long getLongFramePosition()
{
return 0;
}
/**
* Number of microseconds worth of data that has been sourced by this
* target data line. Returns the frame counter times 20,000 microseconds.
*/
@Override
public long getMicrosecondPosition()
{
return 0;
}
/**
* Not implemented
*/
@Override
public float getLevel()
{
return AudioSystem.NOT_SPECIFIED;
}
@Override
public javax.sound.sampled.Line.Info getLineInfo()
{
return new DataLine.Info( IMBETargetDataLine.class,
AudioFormats.IMBE_AUDIO_FORMAT );
}
/**
* No controls are implemented for this data line
*/
@Override
public Control[] getControls()
{
return null;
}
/**
* No controls are implemented for this data line
*/
@Override
public boolean isControlSupported( Type control )
{
return false;
}
/**
* No controls are implemented for this data line
*/
@Override
public Control getControl( Type control )
{
return null;
}
@Override
public void addLineListener( LineListener listener )
{
// TODO Auto-generated method stub
}
@Override
public void removeLineListener( LineListener listener )
{
// TODO Auto-generated method stub
}
}
<file_sep>package sample.real;
public interface RealSampleListener
{
public void receive( float sample );
}
<file_sep>package decode.p25.message.tsbk.osp.data;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.reference.DataUnitID;
public class SNDCPDataChannelGrant extends SNDCPData implements IdentifierReceiver
{
public static final int[] TRANSMIT_IDENTIFIER = { 88,89,90,91 };
public static final int[] TRANSMIT_NUMBER = { 92,93,94,95,96,97,98,99,100,
101,102,103 };
public static final int[] RECEIVE_IDENTIFIER = { 104,105,106,107 };
public static final int[] RECEIVE_NUMBER = { 108,109,110,111,112,113,114,
115,116,117,118,119 };
public static final int[] TARGET_ADDRESS = { 120,121,122,123,124,125,126,
127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 };
private IBandIdentifier mIdentifierUpdateTransmit;
private IBandIdentifier mIdentifierUpdateReceive;
public SNDCPDataChannelGrant( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
if( isEmergency() )
{
sb.append( " EMERGENCY" );
}
sb.append( " UPLINK:" );
sb.append( getTransmitChannelIdentifier() + "-" + getTransmitChannelNumber() );
sb.append( " " + getUplinkFrequency() );
sb.append( " DOWNLINK:" );
sb.append( getReceiveChannelIdentifier() + "-" + getReceiveChannelNumber() );
sb.append( " " + getDownlinkFrequency() );
sb.append( " TGT:" );
sb.append( getTargetAddress() );
return sb.toString();
}
public int getTransmitChannelIdentifier()
{
return mMessage.getInt( TRANSMIT_IDENTIFIER );
}
public int getTransmitChannelNumber()
{
return mMessage.getInt( TRANSMIT_NUMBER );
}
public String getTransmitChannel()
{
return getTransmitChannelIdentifier() + "-" + getTransmitChannelNumber();
}
public int getReceiveChannelIdentifier()
{
return mMessage.getInt( RECEIVE_IDENTIFIER );
}
public int getReceiveChannelNumber()
{
return mMessage.getInt( RECEIVE_NUMBER );
}
public String getReceiveChannel()
{
return getReceiveChannelIdentifier() + "-" + getReceiveChannelNumber();
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
if( identifier == getTransmitChannelIdentifier() )
{
mIdentifierUpdateTransmit = message;
}
else if( identifier == getReceiveChannelIdentifier() )
{
mIdentifierUpdateReceive = message;
}
else
{
throw new IllegalArgumentException( "unexpected channel band "
+ "identifier [" + identifier + "]" );
}
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 2 ];
identifiers[ 0 ] = getTransmitChannelIdentifier();
identifiers[ 1 ] = getReceiveChannelIdentifier();
return identifiers;
}
public long getDownlinkFrequency()
{
return calculateDownlink( mIdentifierUpdateTransmit, getTransmitChannelNumber() );
}
public long getUplinkFrequency()
{
return calculateUplink( mIdentifierUpdateReceive, getReceiveChannelNumber() );
}
}
<file_sep>package decode.p25.message.tsbk.motorola;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.reference.DataUnitID;
public class PatchGroupDelete extends PatchGroup
{
public PatchGroupDelete( BinaryMessage message, DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return MotorolaOpcode.PATCH_GROUP_DELETE.getLabel();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.fcd.proplusV2;
import java.awt.ComponentOrientation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.SourceException;
import source.tuner.TunerConfiguration;
import source.tuner.TunerConfigurationAssignment;
import source.tuner.TunerType;
import controller.ResourceManager;
public class FCD2TunerConfigurationPanel extends JPanel
{
private final static Logger mLog =
LoggerFactory.getLogger( FCD2TunerConfigurationPanel.class );
private static final long serialVersionUID = 1L;
private ResourceManager mResourceManager;
private FCD2TunerController mController;
private FCD2TunerConfiguration mSelectedConfig;
private JButton mNewConfiguration;
private JButton mDeleteConfiguration;
private JComboBox<FCD2TunerConfiguration> mComboConfigurations;
private JTextField mName;
private JCheckBox mLNAGain;
private JCheckBox mMixerGain;
private JSpinner mFrequencyCorrection;
public FCD2TunerConfigurationPanel( ResourceManager resourceManager,
FCD2TunerController controller )
{
mResourceManager = resourceManager;
mController = controller;
init();
}
private void init()
{
setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][][][grow]" ) );
mComboConfigurations = new JComboBox<FCD2TunerConfiguration>();
mComboConfigurations.setModel( getModel() );
mComboConfigurations.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
FCD2TunerConfiguration selected =
(FCD2TunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
update( selected );
}
}
});
add( new JLabel( "Config:" ) );
add( mComboConfigurations, "growx,push" );
mName = new JTextField();
mName.addFocusListener( new FocusListener()
{
@Override
public void focusLost( FocusEvent e )
{
mSelectedConfig.setName( mName.getText() );
save();
}
@Override
public void focusGained( FocusEvent e ) {}
} );
add( new JLabel( "Name" ) );
add( mName, "growx,push" );
/**
* Frequency Correction
*/
SpinnerModel model =
new SpinnerNumberModel( 0.0, //initial value
-1000.0, //min
1000.0, //max
0.1 ); //step
mFrequencyCorrection = new JSpinner( model );
JSpinner.NumberEditor editor =
(JSpinner.NumberEditor)mFrequencyCorrection.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits( 1 );
editor.getTextField().setHorizontalAlignment( SwingConstants.CENTER );
mFrequencyCorrection.addChangeListener( new ChangeListener()
{
@Override
public void stateChanged( ChangeEvent e )
{
double value = ((SpinnerNumberModel)mFrequencyCorrection
.getModel()).getNumber().doubleValue();
try
{
mController.setFrequencyCorrection( value );
mSelectedConfig.setFrequencyCorrection( value );
save();
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
FCD2TunerConfigurationPanel.this,
"FCD Pro Plus Tuner Controller - couldn't "
+ "apply frequency correction value: " + value +
e1.getLocalizedMessage() );
mLog.error( "FuncubeDongleProPlus Controller - couldn't apply "
+ "frequency correction value: " + value, e1 );
}
}
} );
add( new JLabel( "Correction PPM:" ) );
add( mFrequencyCorrection, "growx,push" );
/**
* LNA Gain
*/
mLNAGain = new JCheckBox( "LNA Gain:" );
mLNAGain.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT );
mLNAGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
mSelectedConfig.setGainLNA( mLNAGain.isSelected() );
save();
update( mSelectedConfig );
}
} );
add( mLNAGain );
/**
* Mixer Gain
*/
mMixerGain = new JCheckBox( "Mixer Gain:" );
mMixerGain.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT );
mMixerGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
mSelectedConfig.setGainMixer( mMixerGain.isSelected() );
save();
update( mSelectedConfig );
}
} );
add( mMixerGain );
/**
* Lookup the save config and apply that config to update all of the
* controls
*/
TunerConfigurationAssignment savedConfig = mResourceManager
.getSettingsManager().getSelectedTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO_PLUS,
mController.getUSBAddress() );
if( savedConfig != null )
{
mSelectedConfig = getNamedConfiguration(
savedConfig.getTunerConfigurationName() );
}
if( mSelectedConfig == null )
{
mSelectedConfig = mComboConfigurations.getItemAt( 0 );
//Store this config as the default for this tuner at this address
mResourceManager.getSettingsManager()
.setSelectedTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO_PLUS,
mController.getUSBAddress(), mSelectedConfig );
}
mComboConfigurations.setSelectedItem( mSelectedConfig );
/**
* Create a new configuration
*/
mNewConfiguration = new JButton( "New" );
mNewConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
TunerConfiguration config =
mResourceManager.getSettingsManager()
.addNewTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO_PLUS,
"New Configuration" );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedItem( config );
repaint();
}
} );
add( mNewConfiguration, "growx,push" );
/**
* Delete the currently selected configuration
*/
mDeleteConfiguration = new JButton( "Delete" );
mDeleteConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
FCD2TunerConfiguration selected =
(FCD2TunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
int n = JOptionPane.showConfirmDialog(
FCD2TunerConfigurationPanel.this,
"Are you sure you want to delete '"
+ selected.getName() + "'?",
"Are you sure?",
JOptionPane.YES_NO_OPTION );
if( n == JOptionPane.YES_OPTION )
{
mResourceManager.getSettingsManager()
.deleteTunerConfiguration( selected );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedIndex( 0 );
repaint();
}
}
}
} );
add( mDeleteConfiguration, "growx,push" );
}
private void update( FCD2TunerConfiguration config )
{
mSelectedConfig = config;
try
{
mController.apply( config );
mName.setText( config.getName() );
mLNAGain.setSelected( config.getGainLNA() );
mMixerGain.setSelected( config.getGainMixer() );
mFrequencyCorrection.setValue( config.getFrequencyCorrection() );
mResourceManager.getSettingsManager().setSelectedTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO_PLUS,
mController.getUSBAddress(), config );
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
FCD2TunerConfigurationPanel.this,
"FCD Pro Plus Tuner Controller - couldn't "
+ "apply the tuner configuration settings - " +
e1.getLocalizedMessage() );
mLog.error( "FuncubeDongleProPlus Controller - couldn't apply "
+ "config [" + config.getName() + "]", e1 );
}
}
private ComboBoxModel<FCD2TunerConfiguration> getModel()
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.FUNCUBE_DONGLE_PRO_PLUS );
DefaultComboBoxModel<FCD2TunerConfiguration> model =
new DefaultComboBoxModel<FCD2TunerConfiguration>();
for( TunerConfiguration config: configs )
{
model.addElement( (FCD2TunerConfiguration)config );
}
return model;
}
private FCD2TunerConfiguration getNamedConfiguration( String name )
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.FUNCUBE_DONGLE_PRO_PLUS );
for( TunerConfiguration config: configs )
{
if( config.getName().contentEquals( name ) )
{
return (FCD2TunerConfiguration)config;
}
}
return null;
}
private void save()
{
mResourceManager.getSettingsManager().save();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.frequency;
import java.util.ArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.SourceException;
import source.tuner.frequency.FrequencyChangeEvent.Attribute;
public class FrequencyController
{
private final static Logger mLog = LoggerFactory.getLogger( FrequencyController.class );
private Tunable mTunable;
private long mFrequency = 101100000;
private long mTunedFrequency = 101100000;
private long mMinimumFrequency;
private long mMaximumFrequency;
private double mFrequencyCorrection = 0d;
private int mSampleRate = 0;
private ArrayList<FrequencyChangeListener> mListeners =
new ArrayList<FrequencyChangeListener>();
public FrequencyController( Tunable tunable,
long minFrequency,
long maxFrequency,
double frequencyCorrection )
{
mTunable = tunable;
mMinimumFrequency = minFrequency;
mMaximumFrequency = maxFrequency;
mFrequencyCorrection = frequencyCorrection;
}
/**
* Get bandwidth/sample rate in hertz
*/
public int getBandwidth()
{
return mSampleRate;
}
/**
* Set sample rate in hertz
*/
public void setSampleRate( int sampleRate )
{
mSampleRate = sampleRate;
broadcastSampleRateChange();
}
/**
* Get frequency in hertz
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Set frequency
* @param frequency in hertz
* @throws SourceException if tunable doesn't support tuning a corrected
* version of the requested frequency
*/
public void setFrequency( long frequency ) throws SourceException
{
setFrequency( frequency, true );
}
/**
* Set frequency with optional broadcast of frequency change event. This
* method supports changing the frequency correction value without
* broadcasting a frequency change event.
*/
private void setFrequency( long frequency, boolean broadcastChange )
throws SourceException
{
long tunedFrequency = getTunedFrequency( frequency );
if( tunedFrequency < mMinimumFrequency ||
tunedFrequency > mMaximumFrequency )
{
throw new SourceException( "Cannot tune frequency ( requested: " +
frequency + " actual:" + tunedFrequency + "]" );
}
mFrequency = frequency;
mTunedFrequency = tunedFrequency;
if( mTunable != null )
{
mTunable.setTunedFrequency( mTunedFrequency );
}
/* Broadcast to all listeners that the frequency has changed */
if( broadcastChange )
{
broadcastFrequencyChange();
}
}
public long getTunedFrequency()
{
return mTunedFrequency;
}
public long getMinimumFrequency()
{
return mMinimumFrequency;
}
public long getMaximumFrequency()
{
return mMaximumFrequency;
}
/**
* Calculate the tuned frequency by adding frequency correction to the
* corrected frequency.
* @param correctedFrequency
*/
private long getTunedFrequency( long correctedFrequency )
{
return (long)( (double)correctedFrequency /
( 1.0 + ( mFrequencyCorrection / 1000000.0 ) ) );
}
/**
* Calculate the corrected frequency by subtracting frequency correction
* from the tuned frequency.
* @param tunedFrequency
*/
private long getCorrectedFrequency( long tunedFrequency )
{
return (long)( (double)tunedFrequency /
( 1.0 - ( mFrequencyCorrection / 1000000.0 ) ) );
}
public double getFrequencyCorrection()
{
return mFrequencyCorrection;
}
public void setFrequencyCorrection( double correction )
throws SourceException
{
mFrequencyCorrection = correction;
if( mFrequency > 0 )
{
/* Reset the frequency, but don't broadcast a change */
setFrequency( mFrequency, false );
}
broadcastFrequencyChangeEvent( new FrequencyChangeEvent(
Attribute.SAMPLE_RATE_ERROR, mFrequencyCorrection ) );
}
/**
* Adds listener to receive frequency change events
*/
public void addListener( FrequencyChangeListener listener )
{
if( !mListeners.contains( listener ) )
{
mListeners.add( listener );
}
}
/**
* Removes listener from receiving frequency change events
*/
public void removeListener( FrequencyChangeListener listener )
{
mListeners.remove( listener );
}
/**
* Broadcasts a change/update to the current (uncorrected) frequency or the
* bandwidth/sample rate value.
*/
protected void broadcastFrequencyChange()
{
broadcastFrequencyChangeEvent(
new FrequencyChangeEvent( Attribute.FREQUENCY, mFrequency ) );
}
/**
* Broadcasts a sample rate change
*/
protected void broadcastSampleRateChange()
{
broadcastFrequencyChangeEvent(
new FrequencyChangeEvent( Attribute.SAMPLE_RATE, mSampleRate ) );
}
public void broadcastFrequencyChangeEvent( FrequencyChangeEvent event )
{
for( FrequencyChangeListener listener: mListeners )
{
listener.frequencyChanged( event );
}
}
public interface Tunable
{
/**
* Gets the tuned frequency of the device
*/
public long getTunedFrequency() throws SourceException;
/**
* Sets the tuned frequency of the device
*/
public void setTunedFrequency( long frequency ) throws SourceException;
/**
* Gets the current bandwidth setting of the device
*/
public int getCurrentSampleRate() throws SourceException;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 bits;
import java.util.ArrayList;
import java.util.Iterator;
import sample.Broadcaster;
import sample.Listener;
import dsp.symbol.SyncDetectListener;
import dsp.symbol.SyncDetectProvider;
/**
* MessageFramer - processes bitsets looking for a sync pattern within
* the bits, and then extracts the message, including the sync
* pattern, for a total bit length of messageLength.
*
* Will extract multiple messages simultaneously, for each sync pattern that is
* encountered within the bitset bit stream.
*/
public class MessageFramer implements Listener<Boolean>,
SyncDetectProvider
{
private boolean[] mSyncPattern;
private int mMessageLength;
private SyncDetectListener mSyncDetectListener;
private Broadcaster<BinaryMessage> mBroadcaster =
new Broadcaster<BinaryMessage>();
private ArrayList<MessageAssembler> mMessageAssemblers =
new ArrayList<MessageAssembler>();
private ArrayList<MessageAssembler> mCompletedMessageAssemblers =
new ArrayList<MessageAssembler>();
private BinaryMessage mPreviousBuffer = null;
private SyncPatternMatcher mMatcher;
public MessageFramer( boolean[] syncPattern, int messageLength )
{
mSyncPattern = syncPattern;
mMatcher = new SyncPatternMatcher( syncPattern );
mMessageLength = messageLength;
}
public void dispose()
{
mBroadcaster.dispose();
mCompletedMessageAssemblers.clear();
mMessageAssemblers.clear();
}
@Override
public void receive( Boolean bit )
{
mMatcher.receive( bit );
Iterator<MessageAssembler> it = mMessageAssemblers.iterator();
MessageAssembler assembler;
while( it.hasNext() )
{
assembler = it.next();
/* Dispose and remove any completed assemblers */
if( assembler.complete() )
{
assembler.dispose();
it.remove();
}
/* Otherwise, send them the bit */
else
{
assembler.receive( bit );
}
}
/* Check for sync match and add new message assembler */
if( mMatcher.matches() )
{
addMessageAssembler( new MessageAssembler( mMessageLength, mSyncPattern ) );
/* Notify any sync detect listener(s) */
if( mSyncDetectListener != null )
{
mSyncDetectListener.syncDetected();
}
}
}
/**
* Causes all messages currently under assembly to be forcibly
* sent (ie flushed) to all registered message listeners, and
* subsequently, all assemblers to be deleted
*/
public void flush()
{
for( MessageAssembler assembler: mMessageAssemblers )
{
assembler.flush();
}
}
@Override
public void setSyncDetectListener( SyncDetectListener listener )
{
mSyncDetectListener = listener;
}
/**
* Allow a message listener to register with this framer to receive
* all framed messages
*/
public void addMessageListener( Listener<BinaryMessage> listener )
{
mBroadcaster.addListener( listener );
}
public void removeMessageListener( Listener<BinaryMessage> listener )
{
mBroadcaster.removeListener( listener );
}
/*
* Adds a message assembler to receive bits from the bit stream
*/
private void addMessageAssembler( MessageAssembler assembler )
{
mMessageAssemblers.add( assembler );
}
private void removeMessageAssembler( MessageAssembler assembler )
{
mMessageAssemblers.remove( assembler );
}
/**
* Assembles a binary message, starting with the initial fill of the
* identified sync pattern, and every bit thereafter. Once the accumulated
* bits equal the message length, the message is sent and the assembler
* flags itself as complete.
*
* By design, multiple message assemblers can exist at the same time, each
* assembling different, overlapping potential messages
*/
private class MessageAssembler implements Listener<Boolean>
{
BinaryMessage mMessage;
boolean mComplete = false;
MessageAssembler( int messageLength )
{
mMessage = new BinaryMessage( messageLength );
}
MessageAssembler( int messageLength, boolean[] initialFill )
{
this( messageLength );
/* Pre-load the message with the sync pattern */
for( int x = 0; x < initialFill.length; x++ )
{
receive( initialFill[ x ] );
}
}
public void dispose()
{
mMessage = null;
}
@Override
/**
* Receives one bit at a time, and assembles them into a message
*/
public void receive( Boolean bit )
{
try
{
mMessage.add( bit );
}
catch( BitSetFullException e )
{
e.printStackTrace();
}
/* Once our message is complete (ie full), send it to all registered
* message listeners, and set complete flag so for auto-removal */
if( mMessage.isFull() )
{
mComplete = true;
flush();
}
}
/**
* Flushes/Sends the current message, or partial message, and sets
* complete flag to true, so that we can be auto-removed
*/
public void flush()
{
mBroadcaster.receive( mMessage );
mComplete = true;
}
/**
* Flag to indicate when this assembler has received all of the bits it
* is looking for (ie message length), and should then be removed from
* receiving any more bits
*/
public boolean complete()
{
return mComplete;
}
}
}
<file_sep>package decode.p25.message.tsbk.motorola;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.reference.DataUnitID;
public class TrafficChannelBaseStationIdentification extends MotorolaTSBKMessage
{
public static final int[] CHARACTER_1 = { 80,81,82,83,84,85 };
public static final int[] CHARACTER_2 = { 86,87,88,89,90,91 };
public static final int[] CHARACTER_3 = { 92,93,94,95,96,97 };
public static final int[] CHARACTER_4 = { 98,99,100,101,102,103 };
public static final int[] CHARACTER_5 = { 104,105,106,107,108,109 };
public static final int[] CHARACTER_6 = { 110,111,112,113,114,115 };
public static final int[] CHARACTER_7 = { 116,117,118,119,120,121 };
public static final int[] CHARACTER_8 = { 122,123,124,125,126,127 };
public TrafficChannelBaseStationIdentification( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return MotorolaOpcode.TRAFFIC_CHANNEL_ID.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " ID:" + getID() );
return sb.toString();
}
public String getID()
{
StringBuilder sb = new StringBuilder();
sb.append( getCharacter( CHARACTER_1 ) );
sb.append( getCharacter( CHARACTER_2 ) );
sb.append( getCharacter( CHARACTER_3 ) );
sb.append( getCharacter( CHARACTER_4 ) );
sb.append( getCharacter( CHARACTER_5 ) );
sb.append( getCharacter( CHARACTER_6 ) );
sb.append( getCharacter( CHARACTER_7 ) );
sb.append( getCharacter( CHARACTER_8 ) );
return sb.toString();
}
private String getCharacter( int[] field )
{
int value = mMessage.getInt( field );
return String.valueOf( (char)( value + 43 ) );
}
}
<file_sep>package decode.p25.message.tdu.lc;
import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.reference.Digit;
import decode.p25.reference.LinkControlOpcode;
public class TelephoneInterconnectAnswerRequest extends TDULinkControlMessage
{
private final static Logger mLog = LoggerFactory.getLogger( TelephoneInterconnectAnswerRequest.class );
public static final int[] DIGIT_1 = { 72,73,74,75 };
public static final int[] DIGIT_2 = { 88,89,90,91 };
public static final int[] DIGIT_3 = { 92,93,94,95 };
public static final int[] DIGIT_4 = { 96,97,98,99 };
public static final int[] DIGIT_5 = { 112,113,114,115 };
public static final int[] DIGIT_6 = { 116,117,118,119 };
public static final int[] DIGIT_7 = { 120,121,122,123 };
public static final int[] DIGIT_8 = { 136,137,138,139 };
public static final int[] DIGIT_9 = { 140,141,142,143 };
public static final int[] DIGIT_10 = { 144,145,146,147 };
public static final int[] TARGET_ADDRESS = { 160,161,162,163,164,165,166,
167,168,169,170,171,184,185,186,187,188,189,190,191,192,193,194,195 };
public TelephoneInterconnectAnswerRequest( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.TELEPHONE_INTERCONNECT_ANSWER_REQUEST.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " TO:" );
sb.append( getTargetAddress() );
sb.append( " TEL:" );
sb.append( getTelephoneNumber() );
return sb.toString();
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
public String getTelephoneNumber()
{
List<Integer> digits = new ArrayList<Integer>();
digits.add( mMessage.getInt( DIGIT_1 ) );
digits.add( mMessage.getInt( DIGIT_2 ) );
digits.add( mMessage.getInt( DIGIT_3 ) );
digits.add( mMessage.getInt( DIGIT_4 ) );
digits.add( mMessage.getInt( DIGIT_5 ) );
digits.add( mMessage.getInt( DIGIT_6 ) );
digits.add( mMessage.getInt( DIGIT_7 ) );
digits.add( mMessage.getInt( DIGIT_8 ) );
digits.add( mMessage.getInt( DIGIT_9 ) );
digits.add( mMessage.getInt( DIGIT_10 ) );
return Digit.decode( digits );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.fcd.proV1;
import javax.xml.bind.annotation.XmlAttribute;
import source.tuner.TunerConfiguration;
import source.tuner.TunerType;
import source.tuner.fcd.proV1.FCD1TunerController.LNAEnhance;
import source.tuner.fcd.proV1.FCD1TunerController.LNAGain;
import source.tuner.fcd.proV1.FCD1TunerController.MixerGain;
public class FCD1TunerConfiguration extends TunerConfiguration
{
private double mFrequencyCorrection = 22.0d;
private double mInphaseDCCorrection = 0.0d;
private double mQuadratureDCCorrection = 0.0d;
private double mPhaseCorrection = 0.0d;
private double mGainCorrection = 0.0d;
private LNAGain mLNAGain = LNAGain.LNA_GAIN_PLUS_20_0;
private LNAEnhance mLNAEnhance = LNAEnhance.LNA_ENHANCE_OFF;
private MixerGain mMixerGain = MixerGain.MIXER_GAIN_PLUS_12_0;
/**
* Default constructor for JAXB
*/
public FCD1TunerConfiguration()
{
this( "Default" );
}
public FCD1TunerConfiguration( String name )
{
super( name );
}
@Override
public TunerType getTunerType()
{
return TunerType.FUNCUBE_DONGLE_PRO;
}
public LNAGain getLNAGain()
{
return mLNAGain;
}
public void setLNAGain( LNAGain gain )
{
mLNAGain = gain;
}
@XmlAttribute( name = "lna_gain" )
public LNAEnhance getLNAEnhance()
{
return mLNAEnhance;
}
public void setLNAEnhance( LNAEnhance enhance )
{
mLNAEnhance = enhance;
}
@XmlAttribute( name = "mixer_gain" )
public MixerGain getMixerGain()
{
return mMixerGain;
}
public void setMixerGain( MixerGain gain )
{
mMixerGain = gain;
}
@XmlAttribute( name = "frequency_correction" )
public double getFrequencyCorrection()
{
return mFrequencyCorrection;
}
public void setFrequencyCorrection( double value )
{
mFrequencyCorrection = value;
}
@XmlAttribute( name = "inphase_dc_correction" )
public double getInphaseDCCorrection()
{
return mInphaseDCCorrection;
}
public void setInphaseDCCorrection( double value )
{
mInphaseDCCorrection = value;
}
@XmlAttribute( name = "quadrature_dc_correction" )
public double getQuadratureDCCorrection()
{
return mQuadratureDCCorrection;
}
public void setQuadratureDCCorrection( double value )
{
mQuadratureDCCorrection = value;
}
@XmlAttribute( name = "phase_correction" )
public double getPhaseCorrection()
{
return mPhaseCorrection;
}
public void setPhaseCorrection( double value )
{
mPhaseCorrection = value;
}
@XmlAttribute( name = "gain_correction" )
public double getGainCorrection()
{
return mGainCorrection;
}
public void setGainCorrection( double value )
{
mGainCorrection = value;
}
}
<file_sep>package decode.p25;
import bits.BinaryMessage;
public interface C4FMFrameListener
{
/**
* Listener interface to receive the output of the C4FMMessageFramer.
*
* @param buffer - framed message without the sync pattern
* @param inverted - flag indicating if the message was received inverted
*/
public void receive( BinaryMessage buffer, boolean inverted );
}
<file_sep>package audio;
import audio.SquelchListener.SquelchState;
import audio.inverted.AudioType;
public interface IAudioOutput
{
/**
* Squelch / Unsquelch state for this channel
*/
public abstract void setSquelch( SquelchState state );
/**
* Audio playback defines if this channel is currently playing on the
* system speakers.
*/
public abstract void setAudioPlaybackEnabled( boolean enabled );
/**
* Dispose of any system resources for this audio output
*/
public abstract void dispose();
/**
* Sets the audio to normal or inverted output
*/
public abstract void setAudioType( AudioType type );
}<file_sep>package decode.p25.message.tsbk;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.P25Message;
import decode.p25.message.tsbk.motorola.MotorolaOpcode;
import decode.p25.message.tsbk.vendor.VendorOpcode;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import decode.p25.reference.Vendor;
import edac.CRC;
public class TSBKMessage extends P25Message
{
public static final int MESSAGE_START = 64;
public static final int LAST_BLOCK_FLAG = 64;
public static final int ENCRYPTED_FLAG = 65;
public static final int[] OPCODE = { 66,67,68,69,70,71 };
public static final int[] VENDOR_ID = { 72,73,74,75,76,77,78,79 };
public static final int[] BLOCK1 = { 64,65,66,67,68,69,70,71 };
public static final int[] BLOCK2 = { 72,73,74,75,76,77,78,79 };
public static final int[] BLOCK3 = { 80,81,82,83,84,85,86,87 };
public static final int[] BLOCK4 = { 88,89,90,91,92,93,94,95 };
public static final int[] BLOCK5 = { 96,97,98,99,100,101,102,103 };
public static final int[] BLOCK6 = { 104,105,106,107,108,109,110,111 };
public static final int[] BLOCK7 = { 112,113,114,115,116,117,118,119 };
public static final int[] BLOCK8 = { 120,121,122,123,124,125,126,127 };
public static final int[] BLOCK9 = { 128,129,130,131,132,133,134,135 };
public static final int[] BLOCK10 = { 136,137,138,139,140,141,142,143 };
public static final int[] BLOCK11 = { 144,145,146,147,148,149,150,151 };
public static final int[] BLOCK12 = { 152,153,154,155,156,157,158,159 };
public static final int CRC_START = 144;
public TSBKMessage( BinaryMessage message, DataUnitID duid, AliasList aliasList )
{
super( message, duid, aliasList );
/* Since CRC is checked before construction, mark it as passed */
mCRC = new CRC[ 1 ];
mCRC[ 0 ] = CRC.PASSED;
}
public boolean isLastBlock()
{
return mMessage.get( LAST_BLOCK_FLAG );
}
public boolean isEncrypted()
{
return mMessage.get( ENCRYPTED_FLAG );
}
public Vendor getVendor()
{
return Vendor.fromValue( mMessage.getInt( VENDOR_ID ) );
}
public Opcode getOpcode()
{
return Opcode.fromValue( mMessage.getInt( OPCODE ) );
}
public MotorolaOpcode getMotorolaOpcode()
{
return MotorolaOpcode.fromValue( mMessage.getInt( OPCODE ) );
}
public VendorOpcode getVendorOpcode()
{
return VendorOpcode.fromValue( mMessage.getInt( OPCODE ) );
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " - " + getMessageHex() );
return sb.toString();
}
protected String getMessageStub()
{
StringBuilder sb = new StringBuilder();
Vendor vendor = getVendor();
sb.append( "NAC:" );
sb.append( getNAC() );
sb.append( " " );
sb.append( getDUID().getLabel() );
if( vendor == Vendor.STANDARD )
{
if( isEncrypted() )
{
sb.append( " ENCRYPTED" );
}
else
{
sb.append( " " );
sb.append( getOpcode().getLabel() );
}
}
else
{
sb.append( " " );
sb.append( vendor.getLabel() );
if( isEncrypted() )
{
sb.append( " ENCRYPTED" );
}
else
{
sb.append( " OPCD:" );
sb.append( mMessage.getHex( OPCODE, 2 ) );
}
}
return sb.toString();
}
public String getMessageHex()
{
StringBuilder sb = new StringBuilder();
sb.append( mMessage.getHex( BLOCK1, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK2, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK3, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK4, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK5, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK6, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK7, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK8, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK9, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK10, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK11, 2 ) + " " );
sb.append( mMessage.getHex( BLOCK12, 2 ) + " " );
return sb.toString();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 alias;
import java.util.ArrayList;
import java.util.HashMap;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alias.action.AliasAction;
import alias.action.beep.BeepAction;
import alias.action.clip.ClipAction;
import alias.action.script.ScriptAction;
import alias.esn.Esn;
import alias.fleetsync.FleetsyncID;
import alias.fleetsync.StatusID;
import alias.mdc.MDC1200ID;
import alias.mobileID.Min;
import alias.mpt1327.MPT1327ID;
import alias.siteID.SiteID;
import alias.talkgroup.TalkgroupID;
import alias.uniqueID.UniqueID;
@XmlSeeAlso( { Alias.class,
AliasID.class,
FleetsyncID.class,
Esn.class,
Group.class,
MDC1200ID.class,
Min.class,
MPT1327ID.class,
UniqueID.class,
SiteID.class,
StatusID.class,
TalkgroupID.class,
/* Alias Actions */
AliasAction.class,
BeepAction.class,
ClipAction.class,
ScriptAction.class } )
@XmlRootElement( name = "alias_list" )
public class AliasList implements Comparable<AliasList>
{
private final static Logger mLog = LoggerFactory.getLogger( AliasList.class );
private String mName;
private ArrayList<Group> mGroups = new ArrayList<Group>();
private HashMap<String,Alias> mESN = new HashMap<String,Alias>();
private HashMap<String,Alias> mFleetsync = new HashMap<String,Alias>();
private HashMap<String,Alias> mMDC1200 = new HashMap<String,Alias>();
private HashMap<String,Alias> mMobileID = new HashMap<String,Alias>();
private HashMap<String,Alias> mMPT1327 = new HashMap<String,Alias>();
private HashMap<String, Alias> mSiteID = new HashMap<String,Alias>();
private HashMap<Integer, Alias> mStatus = new HashMap<Integer,Alias>();
private HashMap<String,Alias> mTalkgroup = new HashMap<String,Alias>();
private HashMap<Integer,Alias> mUniqueID = new HashMap<Integer,Alias>();
private boolean mESNWildcard = false;
private boolean mMobileIDWildcard = false;
private boolean mFleetsyncWildcard = false;
private boolean mMDC1200Wildcard = false;
private boolean mMPT1327Wildcard = false;
private boolean mSiteWildcard = false;
private boolean mTalkgroupWildcard = false;
public AliasList()
{
this( null );
}
public AliasList( String name )
{
mName = name;
update();
}
/**
* Load/Reload all lookup hashmaps
*/
public void update()
{
//Clear hashmaps
mESN.clear();
mFleetsync.clear();
mMDC1200.clear();
mMobileID.clear();
mMPT1327.clear();
mSiteID.clear();
mStatus.clear();
mTalkgroup.clear();
mUniqueID.clear();
for( Group group: mGroups )
{
for( Alias alias: group.getAlias() )
{
for( AliasID id: alias.getId() )
{
switch( id.getType() )
{
case ESN:
Esn esn = (Esn)id;
if( esn.getEsn().contains( "*" ) )
{
mESNWildcard = true;
mESN.put( fixWildcard( esn.getEsn() ), alias );
}
else
{
mESN.put( esn.getEsn(), alias );
}
break;
case Fleetsync:
FleetsyncID fs = (FleetsyncID)id;
if( fs.getIdent().contains( "*" ) )
{
mFleetsyncWildcard = true;
mFleetsync.put( fixWildcard( fs.getIdent() ), alias );
}
else
{
mFleetsync.put( fs.getIdent(), alias );
}
break;
case MDC1200:
MDC1200ID mdc = (MDC1200ID)id;
if( mdc.getIdent().contains( "*" ) )
{
mMDC1200Wildcard = true;
//Replace (*) wildcard with regex wildcard (.)
mMDC1200.put( fixWildcard( mdc.getIdent() ), alias );
}
else
{
mMDC1200.put( mdc.getIdent(), alias );
}
break;
case MPT1327:
MPT1327ID mpt = (MPT1327ID)id;
String ident = mpt.getIdent();
if( ident != null )
{
if( ident.contains( "*" ) )
{
mMPT1327Wildcard = true;
//Replace (*) wildcard with regex wildcard (.)
mMPT1327.put( fixWildcard( ident ), alias );
}
else
{
mMPT1327.put( ident, alias );
}
}
break;
case MIN:
Min min = (Min)id;
if( min.getMin().contains( "*" ) )
{
mMobileIDWildcard = true;
mMobileID.put( fixWildcard( min.getMin() ), alias );
}
else
{
mMobileID.put( min.getMin(), alias );
}
break;
case LTRNetUID:
UniqueID uid = (UniqueID)id;
mUniqueID.put( uid.getUid(), alias );
break;
case Site:
SiteID siteID = (SiteID)id;
if( siteID.getSite().contains( "*" ) )
{
mSiteWildcard = true;
mSiteID.put( fixWildcard( siteID.getSite() ), alias );
}
else
{
mSiteID.put( siteID.getSite(), alias );
}
break;
case Status:
mStatus.put( ((StatusID)id).getStatus(), alias );
break;
case Talkgroup:
TalkgroupID tgid = (TalkgroupID)id;
if( tgid.getTalkgroup().contains( "*" ) )
{
mTalkgroupWildcard = true;
//Replace (*) wildcard with regex wildcard (.)
mTalkgroup.put( fixWildcard( tgid.getTalkgroup() ), alias );
}
else
{
mTalkgroup.put( tgid.getTalkgroup(), alias );
}
break;
}
}
}
}
}
/**
* Converts user wildcard character (*) to regex single character wildcard (.)
* but ignores a regex multi-character wildcard (.*)
*/
private String fixWildcard( String value )
{
if( value.contains( "*" ) && !value.contains( ".*" ) )
{
return value.replace( "*", "." );
}
return value;
}
public Alias getSiteID( String siteID )
{
if( siteID != null )
{
if( mSiteWildcard )
{
for( String regex: mSiteID.keySet() )
{
if( siteID.matches( regex ) )
{
return mSiteID.get( regex );
}
}
}
else
{
return mSiteID.get( siteID );
}
}
return null;
}
public Alias getStatus( int status )
{
return mStatus.get( status );
}
public Alias getUniqueID( int uniqueID )
{
return mUniqueID.get( uniqueID );
}
public Alias getESNAlias( String esn )
{
if( esn != null )
{
Alias retVal = null;
if( mESNWildcard )
{
for( String regex: mESN.keySet() )
{
if( esn.matches( regex ) )
{
return mESN.get( regex );
}
}
}
else
{
return mESN.get( esn );
}
}
return null;
}
public Alias getFleetsyncAlias( String ident )
{
if( ident != null )
{
Alias retVal = null;
if( mFleetsyncWildcard )
{
for( String regex: mFleetsync.keySet() )
{
if( ident.matches( regex ) )
{
return mFleetsync.get( regex );
}
}
}
else
{
return mFleetsync.get( ident );
}
}
return null;
}
public Alias getMDC1200Alias( String ident )
{
if( ident != null )
{
Alias retVal = null;
if( mMDC1200Wildcard )
{
for( String regex: mMDC1200.keySet() )
{
if( ident.matches( regex ) )
{
return mMDC1200.get( regex );
}
}
}
else
{
return mMDC1200.get( ident );
}
}
return null;
}
public Alias getMPT1327Alias( String ident )
{
if( ident != null )
{
if( mMPT1327Wildcard )
{
for( String regex: mMPT1327.keySet() )
{
if( ident.matches( regex ) )
{
return mMPT1327.get( regex );
}
}
}
else
{
return mMPT1327.get( ident );
}
}
return null;
}
public Group getGroup( Alias alias )
{
if( alias != null )
{
for( Group group: mGroups )
{
if( group.contains( alias ) )
{
return group;
}
}
}
return null;
}
public Alias getMobileIDNumberAlias( String ident )
{
if( ident != null )
{
if( mMobileIDWildcard )
{
for( String regex: mMobileID.keySet() )
{
if( ident.matches( regex ) )
{
return mMobileID.get( regex );
}
}
}
else
{
return mMobileID.get( ident );
}
}
return null;
}
public Alias getTalkgroupAlias( String tgid )
{
if( tgid != null )
{
if( mTalkgroupWildcard )
{
for( String regex: mTalkgroup.keySet() )
{
if( tgid.matches( regex ) )
{
return mTalkgroup.get( regex );
}
}
}
else
{
return mTalkgroup.get( tgid );
}
}
return null;
}
public String toString()
{
return mName;
}
@XmlAttribute
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
public ArrayList<Group> getGroup()
{
return mGroups;
}
public void setGroup( ArrayList<Group> groups )
{
mGroups = groups;
}
public void addGroup( Group group )
{
mGroups.add( group );
}
public void removeGroup( Group group )
{
mGroups.remove( group );
}
@Override
public int compareTo( AliasList otherAliasList )
{
return getName().compareTo( otherAliasList.getName() );
}
}
<file_sep>package decode.p25.reference;
import java.util.List;
public enum Digit
{
D0( "0", "A" ),
D1( "1", "B" ),
D2( "2", "C" ),
D3( "3", "D" ),
D4( "4", "-" ),
D5( "5", "-" ),
D6( "6", "-" ),
D7( "7", "-" ),
D8( "8", "-" ),
D9( "9", "-" ),
D10( "*", "-" ),
D11( "#", "-" ),
D12( "-", "-" ),
D13( "HOOK FLASH", "-" ),
D14( "PAUSE", "-" ),
D15( "ESC", "NULL" ),
DUNK( "?", "?" );
private String mValue;
private String mEscapedValue;
private Digit( String value, String escapedValue )
{
mValue = value;
mEscapedValue = escapedValue;
}
public String getValue()
{
return mValue;
}
public String getEscapedValue()
{
return mEscapedValue;
}
public static Digit fromValue( int value )
{
if( 0 <= value && value <= 15 )
{
return values()[ value ];
}
return DUNK;
}
public static String decode( List<Integer> values )
{
StringBuilder sb = new StringBuilder();
boolean escape = false;
for( Integer value: values )
{
Digit d = Digit.fromValue( value );
if( d == Digit.D15 )
{
escape = true;
}
else if( escape )
{
sb.append( d.getEscapedValue() );
escape = false;
}
else
{
sb.append( d.getValue() );
}
}
return sb.toString();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 instrument.tap;
import instrument.gui.SampleModel;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Observer;
import javax.swing.JCheckBoxMenuItem;
import javax.swing.JMenu;
import javax.swing.JPanel;
public abstract class TapViewPanel extends JPanel implements Observer
{
protected SampleModel mModel;
protected String mLabel;
protected float mVerticalZoom = 1.0f;
public TapViewPanel( SampleModel model, String label )
{
mModel = model;
mModel.addObserver( this );
mLabel = label;
initGui();
}
private void initGui()
{
setBackground( Color.WHITE );
setForeground( Color.BLUE );
setSize( new Dimension( 400, 200 ) );
}
public void reset()
{
mModel.clearSamples();
}
public JMenu getContextMenu()
{
JMenu menu = new JMenu( mLabel );
JMenu verticalMenu = new JMenu( "Vertical Zoom" );
menu.add( verticalMenu );
verticalMenu.add( new VerticalZoomItem( this, "8", 8.0f ) );
verticalMenu.add( new VerticalZoomItem( this, "4", 4.0f ) );
verticalMenu.add( new VerticalZoomItem( this, "2", 2.0f ) );
verticalMenu.add( new VerticalZoomItem( this, "1", 1.0f ) );
verticalMenu.add( new VerticalZoomItem( this, ".5", 0.5f ) );
verticalMenu.add( new VerticalZoomItem( this, ".25", 0.25f ) );
return menu;
}
public SampleModel getModel()
{
return mModel;
}
public int getSampleCount()
{
return getModel().getSampleCount();
}
public void setSampleCount( int sampleCount )
{
getModel().setSampleCount( sampleCount );
}
public float getVerticalZoom()
{
return mVerticalZoom;
}
public void setVerticalZoom( float zoom )
{
mVerticalZoom = zoom;
repaint();
}
public class VerticalZoomItem extends JCheckBoxMenuItem
{
private TapViewPanel mPanel;
private float mZoom;
public VerticalZoomItem( TapViewPanel panel, String label, float zoom )
{
super( label );
mPanel = panel;
mZoom = zoom;
if( mPanel.getVerticalZoom() == zoom )
{
setSelected( true );
}
addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
mPanel.setVerticalZoom( mZoom );
}
} );
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 dsp.nbfm;
import sample.Listener;
import sample.complex.ComplexSample;
import sample.real.RealSampleListener;
public class FMDiscriminator implements Listener<ComplexSample>
{
private RealSampleListener mListener;
private ComplexSample mPreviousSample = new ComplexSample( 0.0f, 0.0f );
private double mGain;
/**
* Implements a polar discriminator with ArcTangent angle estimator to
* demodulate complex sampled frequency modulated signals.
*
* @param gain - gain to be applied to the demodulated output - can be
* dynamically applied to continuously adjust audio output
*/
public FMDiscriminator( double gain )
{
mGain = gain;
}
public void dispose()
{
mListener = null;
mPreviousSample = null;
}
public synchronized void setGain( double gain )
{
mGain = gain;
}
@Override
public void receive( ComplexSample currentSample )
{
/**
* Multiply the current sample against the complex conjugate of the
* previous sample to derive the phase delta between the two samples
*
* Negating the previous sample quadrature produces the conjugate
*/
double i = ( currentSample.inphase() * mPreviousSample.inphase() ) -
( currentSample.quadrature() * -mPreviousSample.quadrature() );
double q = ( currentSample.quadrature() * mPreviousSample.inphase() ) +
( currentSample.inphase() * -mPreviousSample.quadrature() );
double angle;
//Check for divide by zero
if( i == 0 )
{
angle = 0.0;
}
else
{
/**
* Use the arc-tangent of imaginary (q) divided by real (i) to
* get the phase angle (+/-) which was directly manipulated by the
* original message waveform during the modulation. This value now
* serves as the instantaneous amplitude of the demodulated signal
*/
double denominator = 1.0d / i;
angle = Math.atan( (double)q * denominator );
}
if( mListener != null )
{
mListener.receive( (float)( angle * mGain ) );
}
/**
* Store the current sample to use during the next iteration
*/
mPreviousSample = currentSample;
}
public void setListener( RealSampleListener listener )
{
mListener = listener;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 spectrum;
import java.awt.image.IndexColorModel;
public class WaterfallColorModel
{
public static IndexColorModel getDefaultColorModel()
{
int bitDepth = 8;
int indexSize = 256;
byte[] red = new byte[ indexSize ];
byte[] green = new byte[ indexSize ];
byte[] blue = new byte[ indexSize ];
//Background noise
for( int x = 0; x < 16; x++ ) //Blue
{
red[ x ] = (byte)0;
green[ x ] = (byte)0;
blue[ x ] = (byte)127;
}
for( int x = 16; x < 32; x++ ) //Blue
{
red[ x ] = (byte)0;
green[ x ] = (byte)0;
blue[ x ] = (byte)191;
}
int r = 0;
int g = 0;
int b = 191;
for( int x = 32; x < 60; x++ )
{
red[ x ] = (byte)r;
r += 9;
green[ x ] = (byte)g;
g += 9;
blue[ x ] = (byte)b;
b -= 6;
}
r = 255;
g = 255;
b = 0;
for( int x = 60; x < 188; x++ ) //Yellow
{
red[ x ] = (byte)r;
green[ x ] = (byte)g;
g -= 2;
blue[ x ] = (byte)b;
}
for( int x = 188; x < 256; x++ ) //Red
{
red[ x ] = (byte)255;
green[ x ] = (byte)0;
blue[ x ] = (byte)0;
}
return new IndexColorModel( bitDepth, indexSize, red, green, blue );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 eventlog;
import java.nio.file.Path;
import properties.SystemProperties;
import controller.channel.ProcessingChain;
import eventlog.MessageEventLogger.Type;
public class EventLogManager
{
private Path mDirectory;
public EventLogManager()
{
mDirectory = SystemProperties.getInstance()
.getApplicationFolder( "event_logs" );
}
public EventLogger getLogger( ProcessingChain chain, EventLogType eventLogType )
{
StringBuilder sb = new StringBuilder();
sb.append( chain.getChannel().getSystem() );
sb.append( "_" );
sb.append( chain.getChannel().getSite() );
sb.append( "_" );
sb.append( chain.getChannel().getName() );
sb.append( eventLogType.getFileSuffix() );
sb.append( ".log" );
switch( eventLogType )
{
case BINARY_MESSAGE:
return new MessageEventLogger( mDirectory, sb.toString(), Type.BINARY );
case DECODED_MESSAGE:
return new MessageEventLogger( mDirectory, sb.toString(), Type.DECODED );
case CALL_EVENT:
return new CallEventLogger( mDirectory, sb.toString() );
default:
return null;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.fcd;
public enum FCDCommand
{
/**
* Note: the javaxUSB and usb4Java libraries are slightly different than
* the signal9 HID libraries used in C, so you will see variations in the
* byte array length and indexes, when comparing this setup to the qthid
* source code.
*/
//Bootloader Mode Commands
BL_QUERY( (byte) 0x01, 64 ), //01 Decimal
BL_RESET( (byte) 0x08, 2 ), //08
BL_ERASE( (byte) 0x19, 2 ), //24
BL_SET_BYTE_ADDR( (byte) 0x1A, 6 ), //25
BL_GET_BYTE_ADDR_RANGE( (byte) 0x1B, 6 ), //26
BL_WRITE_FLASH_BLOCK( (byte) 0x1C, 52 ), //27
BL_READ_FLASH_BLOCK( (byte) 0x1D, 48 ), //28
//Application Mode Commands
APP_SET_FREQUENCY_KHZ( (byte)0x64, 5 ), //100
APP_SET_FREQUENCY_HZ( (byte)0x65, 6 ), //101
APP_GET_FREQUENCY_HZ( (byte)0x66, 6 ), //102
APP_GET_IF_RSSI( (byte) 0x68, 3 ), //104
APP_GET_PLL_LOCKED( (byte) 0x69, 3 ), //105
APP_SET_DC_CORRECTION( (byte) 0x6A, 5 ), //106
APP_GET_DC_CORRECTION( (byte) 0x6B, 6 ), //107
APP_SET_IQ_CORRECTION( (byte) 0x6C, 5 ), //108
APP_GET_IQ_CORRECTION( (byte) 0x6D, 6 ), //109
APP_SET_LNA_GAIN( (byte)0x6E, 2 ), //110
APP_SET_LNA_ENHANCE( (byte)0x6F, 2 ), //111
APP_SET_BAND( (byte)0x70, 2 ), //112
APP_SET_RF_FILTER( (byte)0x71, 2 ), //113
APP_SET_MIXER_GAIN( (byte)0x72, 2 ), //114
APP_SET_BIAS_CURRENT( (byte)0x73, 2 ), //115
APP_SET_MIXER_FILTER( (byte)0x74, 2 ), //116
APP_SET_IF_GAIN1( (byte)0x75, 2 ), //117
APP_SET_IF_GAIN_MODE( (byte)0x76, 2 ), //118
APP_SET_IF_RC_FILTER( (byte)0x77, 2 ), //119
APP_SET_IF_GAIN2( (byte)0x78, 2 ), //120
APP_SET_IF_GAIN3( (byte)0x79, 2 ), //121
APP_SET_IF_FILTER( (byte)0x7A, 2 ), //122
APP_SET_IF_GAIN4( (byte)0x7B, 2 ), //123
APP_SET_IF_GAIN5( (byte)0x7C, 2 ), //124
APP_SET_IF_GAIN6( (byte)0x7D, 2 ), //125
APP_SET_BIAS_TEE( (byte)0x7E, 2 ), //126
APP_GET_LNA_GAIN( (byte)0x96, 3 ), //150
APP_GET_LNA_ENHANCE( (byte)0x97, 3 ), //151
APP_GET_BAND( (byte)0x98, 3 ), //152
APP_GET_RF_FILTER( (byte)0x99, 3 ), //153
APP_GET_MIXER_GAIN( (byte)0x9A, 3 ), //154
APP_GET_BIAS_CURRENT( (byte)0x9B, 3 ), //155
APP_GET_MIXER_FILTER( (byte)0x9C, 3 ), //156
APP_GET_IF_GAIN1( (byte)0x9D, 3 ), //157
APP_GET_IF_GAIN_MODE( (byte)0x9E, 3 ), //158
APP_GET_IF_RC_FILTER( (byte)0x9F, 3 ), //159
APP_GET_IF_GAIN2( (byte)0xA0, 3 ), //160
APP_GET_IF_GAIN3( (byte)0xA1, 3 ), //161
APP_GET_IF_FILTER( (byte)0xA2, 3 ), //162
APP_GET_IF_GAIN4( (byte)0xA3, 3 ), //163
APP_GET_IF_GAIN5( (byte)0xA4, 3 ), //164
APP_GET_IF_GAIN6( (byte)0xA5, 3 ), //165
APP_GET_BIAS_TEE( (byte)0xA6, 3 ), //166
APP_SEND_I2C_BYTE( (byte)0xC8, 2 ), //200
APP_RECV_I2C_BYTE( (byte)0xC9, 3 ), //201
APP_RESET( (byte)0xFF, 1 ); //255
/**
* Single-byte value to use for the command
*/
private byte mCommandByte;
/**
* Required array length
*/
private int mArrayLength;
private FCDCommand( byte value, int responseLength )
{
mCommandByte = value;
mArrayLength = responseLength;
}
/**
* Returns a byte array of the specified length with the command byte value
* set in index position zero. Fill in additional command arguments prior
* to sending to the device
*/
public byte[] getRequestTemplate()
{
byte[] retVal = new byte[ 64 ];
retVal[ 0 ] = mCommandByte;
retVal[ 1 ] = (byte)0x0;
return retVal;
}
/**
* Returns an empty byte array of the correct length to receive the response
* from the associated command
*/
public byte[] getResponseTemplate()
{
return new byte[ 64 ];
}
/**
* Byte value of the command
*/
public byte getCommand()
{
return mCommandByte;
}
/**
* Total array length required to send the command or receive the response.
*
* Index 0: command is echoed back
* Index 1: 0-fail, 1-success
*/
public int getArrayLength()
{
return mArrayLength;
}
/**
* Checks the response array to verify the pass/fail value that is placed
* in array index position 1, in responses from the device
*/
public static boolean checkResponse( FCDCommand command, byte[] response )
{
boolean valid = false;
if( command != null && response != null )
{
valid = response[ 0 ] == command.getCommand() &&
response[ 1 ] == 1;
}
return valid;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 util;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TimeStamp
{
private static SimpleDateFormat mSDFDate = new SimpleDateFormat( "yyyyMMdd" );
private static SimpleDateFormat mSDFTime = new SimpleDateFormat( "HHmmss" );
/**
* Returns the current system date formatted as yyyy-MM-dd
*/
public static String getFormattedDate()
{
return getFormattedDate( System.currentTimeMillis() );
}
/**
* Returns the timestamp formatted as a date of yyyy-MM-dd
*/
public static String getFormattedDate( long timestamp )
{
return mSDFDate.format( new Date( timestamp ) );
}
/**
* Returns the current system time formatted as HH:mm:ss
*/
public static String getFormattedTime()
{
return getFormattedTime( System.currentTimeMillis() );
}
/**
* Returns the timestamp formatted as a time of HH:mm:ss
*/
public static String getFormattedTime( long timestamp )
{
return mSDFTime.format( new Date( timestamp ) );
}
/**
* Returns current system time formatted as yyyy-MM-dd*HH:mm:ss
* with the * representing the separator attribute
*/
public static String getTimeStamp( String separator )
{
return getTimeStamp( System.currentTimeMillis(), separator );
}
/**
* Returns timestamp formatted as yyyy-MM-dd*HH:mm:ss
* with the * representing the separator attribute
*/
public static String getTimeStamp( long timestamp, String separator )
{
StringBuilder sb = new StringBuilder();
sb.append( getFormattedDate( timestamp ) );
sb.append( separator );
sb.append( getFormattedTime( timestamp ) );
return sb.toString();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.state;
import message.Message;
import sample.Broadcaster;
import sample.Listener;
import controller.state.ChannelState.ChangedAttribute;
/**
* ChannelState for auxiliary decoders.
*/
public abstract class AuxChannelState implements Listener<Message>
{
protected ChannelState mParentChannelState;
protected Broadcaster<ChangedAttribute> mChangeBroadcaster =
new Broadcaster<ChangedAttribute>();
public AuxChannelState( ChannelState parentState )
{
mParentChannelState = parentState;
}
/**
* Prepare for garbage collect
*/
public void dispose()
{
mChangeBroadcaster.dispose();
mParentChannelState = null;
}
/**
* Call fade - change display and await a call to reset()
*/
public abstract void fade();
/**
* Activity summary for this decoder
*/
public abstract String getActivitySummary();
/**
* Call end - cleanup the display
*/
public abstract void reset();
public void addListener( Listener<ChangedAttribute> listener )
{
mChangeBroadcaster.addListener( listener );
}
public void removeListener( Listener<ChangedAttribute> listener )
{
mChangeBroadcaster.removeListener( listener );
}
public void broadcastChange( ChangedAttribute attribute )
{
if( mChangeBroadcaster != null )
{
mChangeBroadcaster.broadcast( attribute );
}
}
}
<file_sep><project name="SDRTrunk" default="SDRTrunk" basedir=".">
<description>
Ant build script for SDRTrunk Decoder Application
</description>
<!-- version properties -->
<property name="major" value="0"/>
<property name="minor" value="1"/>
<property name="build" value="5"/>
<!-- Build properties -->
<property name="classes" location="../classes"/>
<property name="configs" location="../config"/>
<property name="images" location="../images"/>
<property name="libs" location="../imports"/>
<property name="license" location="../license"/>
<property name="product" location="../product"/>
<property name="scripts" location="../scripts"/>
<property name="src" location="../src"/>
<path id="classpath">
<fileset dir="${libs}" includes="*.jar" />
</path>
<target name="init">
<!-- Create the classes folder to contain the compiled java classes -->
<mkdir dir="${classes}"/>
<!-- Create version file -->
<echo message="${major}.${minor}.${build}" file="${classes}/sdrtrunk-version"/>
</target>
<target name="compile" depends="clean,init"
description="Compile java classes" >
<!-- Compile the java code from ${src} into ${classes} -->
<javac srcdir="${src}"
destdir="${classes}"
classpathref="classpath"
includeantruntime="false" />
</target>
<target name="SDRTrunk" depends="compile" description="Create SDRTrunk application" >
<!-- Create the distribution directory -->
<mkdir dir="${product}"/>
<!-- Create jar file -->
<jar jarfile="${product}/SDRTrunk.jar" basedir="${classes}">
<manifest>
<attribute name="Main-Class" value="gui.SDRTrunk"/>
</manifest>
<fileset dir="${configs}">
<exclude name="*.rules"/>
</fileset>
<fileset dir="${license}">
<include name="license.txt"/>
</fileset>
</jar>
<!-- Copy third-party libraries -->
<mkdir dir="${product}/libs"/>
<copy todir="${product}/libs">
<fileset dir="${libs}" includes="*.jar" />
</copy>
<!-- Copy config files -->
<mkdir dir="${product}/config"/>
<copy todir="${product}/config">
<fileset dir="${configs}">
<include name="*.rules"/>
</fileset>
</copy>
<!-- Copy image files -->
<mkdir dir="${product}/images"/>
<copy todir="${product}/images">
<fileset dir="${images}" />
</copy>
<!-- Copy license file -->
<copy todir="${product}">
<fileset dir="${license}" />
</copy>
<!-- Copy program scripts -->
<copy todir="${product}">
<fileset dir="${scripts}" />
</copy>
<!-- Set linux permissions on start script -->
<chmod file="${product}/run_sdrtrunk_linux.sh" perm="777" />
<tstamp prefix="build" />
<property name="filename" value="sdrtrunk_${build.DSTAMP}_${build.TSTAMP}_${major}.${minor}.${build}"/>
<!-- Bundle the files into .zip -->
<zip destfile="${product}/${filename}.zip" basedir="${product}" />
<!-- Bundle the files into .tar.gz to preserve linux script permissions -->
<tar destfile="${product}/${filename}.tar.gz" compression="gzip">
<tarfileset dir="${product}" filemode="777">
<include name="*.sh"/>
</tarfileset>
<tarfileset dir="${product}">
<exclude name="*.sh"/>
<exclude name="${filename}.zip"/>
</tarfileset>
</tar>
</target>
<target name="clean" description="Clean previous build artifacts" >
<delete dir="${classes}"/>
<delete dir="${product}"/>
</target>
</project><file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 util.waveaudio;
public class WaveUtils
{
/**
* Returns a byte array representing a wave file RIFF chunk descriptor,
* for mono channel, signed 16-bit audio sample recording.
*
* @param sampleRate - audio sample rate
*
* @param duration - recording duration in seconds. Note: this is a
* temporary value, since you won't know the exact duration until after the
* recording is complete. Your code should overwrite this initial value
* with the correct value, upon completion of the recording
*/
public static byte[] getRIFFChunkDescriptor( float sampleRate, int duration )
{
//Byte array large enough to hold the descriptor
byte[] buffer = new byte[ 12 ];
//Load "RIFF" into the descriptor (4-bytes)
loadDouble( buffer, 0x46464952, 0, 4 );
//Initial total size value ... will be overwritten later (4-bytes)
//Note: assumes that sample rate is an integer value
int totalSize = 36 + ( (int)sampleRate * duration );
loadDouble( buffer, totalSize, 4, 4);
//Load "WAVE" into the descriptor (4-bytes)
loadDouble( buffer, 0x45564157, 8, 4);
return buffer;
}
/**
* WAVE format descriptor
* @param sampleRate
*/
public static byte[] getWAVEFormatDescriptor( float sampleRate,
int numberOfChannels,
int bitsPerSample )
{
int bytesPerSample = bitsPerSample / 8;
//Byte array large enough to hold the descriptor
byte[] buffer = new byte[ 24 ];
//SubChunk1ID = "fmt "
loadDouble( buffer, 0x20746D66, 0, 4);
//SubChunk1Size = 16
loadDouble( buffer, 16, 4, 4);
//AudioFormat = PCM ( 1 = not compressed )
loadDouble( buffer, 1, 8, 2 );
//NumberOfChannels
loadDouble( buffer, numberOfChannels, 10, 2);
//SampleRate
//Note: assumes sample rate is an integer value
loadDouble( buffer, (int)sampleRate, 12, 4 );
//ByteRate ( sampleRate * numberOfChannels * bytesPerSample )
loadDouble( buffer,
( (int)sampleRate * numberOfChannels * bytesPerSample ),
16,
4 );
//BlockAlign ( numberOfChannels * bytesPerSample )
loadDouble( buffer, ( numberOfChannels * bytesPerSample ), 20, 2 );
//BitsPerSample
loadDouble( buffer, bitsPerSample, 22, 2 );
return buffer;
}
/**
* Returns formatted data chunk header, based on the following values:
*
* @param numberSamples - number of samples that will be in the chunk
* @param numberChannels - number of channels
* @param bitsPerSample - bits per sample
* @return
*/
public static byte[] getDataChunkHeader( int numberBytes,
int numberChannels )
{
//Byte array large enough to hold the descriptor
byte[] buffer = new byte[ 24 ];
//SubChunk2ID = "data"
loadDouble( buffer, 0x61746164, 0, 4 );
//SubChunk2Size
loadDouble( buffer, ( numberBytes * numberChannels ), 4, 4 );
return buffer;
}
/**
* Loads valueToLoad into the byte buffer at start location
* @param buffer - byte array
* @param valueToLoad
* @param start
* @param numberOfBytes
*/
protected static void loadDouble ( byte[] buffer,
long valueToLoad,
int start,
int numberOfBytes )
{
if( !( ( start + numberOfBytes ) <= buffer.length ) )
{
throw new IllegalArgumentException( "Byte array buffer is not "
+ "large enough to load value:" + valueToLoad );
}
for ( int x = 0; x < numberOfBytes; x++ )
{
buffer[ start ] = (byte) ( valueToLoad & 0xFF);
valueToLoad >>= 8;
start++;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.channel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import controller.ConfigurableNode;
public class ChannelMapListNode extends ConfigurableNode
{
private static final long serialVersionUID = 1L;
public ChannelMapListNode( ChannelMapList list )
{
super( list );
}
public ChannelMapList getChannelMapList()
{
return (ChannelMapList)getUserObject();
}
public void init()
{
for( ChannelMap channelMap: getChannelMapList().getChannelMap() )
{
ChannelMapNode node = new ChannelMapNode( channelMap );
getModel().addNode( node, ChannelMapListNode.this, getChildCount() );
node.init();
}
sort();
}
public String toString()
{
return "Channel Maps [" + this.getChildCount() + "]";
}
public JPopupMenu getContextMenu()
{
JPopupMenu retVal = new JPopupMenu();
JMenuItem addSystemItem = new JMenuItem( "Add Channel Map" );
addSystemItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
ChannelMap channelMap = new ChannelMap();
getChannelMapList().addChannelMap( channelMap );
getModel().addNode( new ChannelMapNode( channelMap ),
ChannelMapListNode.this,
ChannelMapListNode.this.getChildCount() );
save();
}
} );
retVal.add( addSystemItem );
return retVal;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.RejectedExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceList;
import org.usb4java.LibUsb;
import source.Source;
import source.SourceException;
import source.config.SourceConfigTuner;
import source.mixer.MixerManager;
import source.tuner.fcd.FCDTuner;
import source.tuner.fcd.proV1.FCD1TunerController;
import source.tuner.fcd.proplusV2.FCD2TunerController;
import source.tuner.hackrf.HackRFTuner;
import source.tuner.hackrf.HackRFTunerController;
import source.tuner.rtl.RTL2832Tuner;
import source.tuner.rtl.RTL2832TunerController;
import source.tuner.rtl.e4k.E4KTunerController;
import source.tuner.rtl.r820t.R820TTunerController;
import controller.ResourceManager;
import controller.channel.ProcessingChain;
public class TunerManager
{
private final static Logger mLog =
LoggerFactory.getLogger( TunerManager.class );
private ResourceManager mResourceManager;
private ArrayList<Tuner> mTuners = new ArrayList<Tuner>();
public TunerManager( ResourceManager resourceManager )
{
mResourceManager = resourceManager;
/* initialize mixers */
MixerManager.getInstance();
initTuners();
}
/**
* Performs cleanup of USB related issues
*/
public void dispose()
{
LibUsb.exit( null );
}
/**
* Iterates current tuners to get a tuner channel source for the frequency
* specified in the channel config's source config object
*/
public Source getSource( ProcessingChain processingChain )
{
TunerChannelSource retVal = null;
if( processingChain.getChannel().getSourceConfiguration()
instanceof SourceConfigTuner )
{
TunerChannel tunerChannel = processingChain.getChannel().getTunerChannel();
Iterator<Tuner> it = mTuners.iterator();
Tuner tuner;
while( it.hasNext() && retVal == null )
{
tuner = it.next();
try
{
retVal = tuner.getChannel(
mResourceManager.getThreadPoolManager(), tunerChannel );
}
catch ( RejectedExecutionException ree )
{
mLog.error( "couldn't provide tuner channel source", ree );
}
catch ( SourceException e )
{
mLog.error( "error obtaining channel from tuner [" +
tuner.getName() + "]", e );
}
}
}
return retVal;
}
/**
* Get list of current tuners
*/
public List<Tuner> getTuners()
{
return mTuners;
}
/**
* Loads all USB tuners and USB/Mixer tuner devices
*/
private void initTuners()
{
DeviceList deviceList = new DeviceList();
int result = LibUsb.init( null );
if( result != LibUsb.SUCCESS )
{
mLog.error( "unable to initialize libusb [" +
LibUsb.errorName( result ) + "]" );
}
else
{
mLog.info( "LibUSB API Version: " + LibUsb.getApiVersion() );
mLog.info( "LibUSB Version: " + LibUsb.getVersion() );
result = LibUsb.getDeviceList( null, deviceList );
if( result < 0 )
{
mLog.error( "unable to get device list from libusb [" + result + " / " +
LibUsb.errorName( result ) + "]" );
}
else
{
mLog.info( "discovered [" + result + "] attached USB devices" );
}
}
for( Device device: deviceList )
{
DeviceDescriptor descriptor = new DeviceDescriptor();
result = LibUsb.getDeviceDescriptor( device, descriptor );
if( result != LibUsb.SUCCESS )
{
mLog.error( "unable to read device descriptor [" +
LibUsb.errorName( result ) + "]" );
}
else
{
TunerInitStatus status = initTuner( device, descriptor );
StringBuilder sb = new StringBuilder();
sb.append( "usb device [" );
sb.append( String.format( "%04X", descriptor.idVendor() ) );
sb.append( ":" );
sb.append( String.format( "%04X", descriptor.idProduct() ) );
if( status.isLoaded() )
{
Tuner tuner = status.getTuner();
sb.append( "] LOADED: " );
sb.append( tuner.toString() );
mTuners.add( tuner );
}
else
{
sb.append( "] NOT LOADED: " );
sb.append( status.getInfo() );
}
mLog.info( sb.toString() );
}
}
LibUsb.freeDeviceList( deviceList, true );
}
private TunerInitStatus initTuner( Device device,
DeviceDescriptor descriptor )
{
if( device != null && descriptor != null )
{
TunerClass tunerClass = TunerClass.valueOf( descriptor.idVendor(),
descriptor.idProduct() );
switch( tunerClass )
{
case ETTUS_USRP_B100:
return initEttusB100Tuner( device, descriptor );
case FUNCUBE_DONGLE_PRO:
return initFuncubeProTuner( device, descriptor );
case FUNCUBE_DONGLE_PRO_PLUS:
return initFuncubeProPlusTuner( device, descriptor );
case HACKRF_ONE:
return initHackRFTuner( device, descriptor );
case COMPRO_VIDEOMATE_U620F:
case COMPRO_VIDEOMATE_U650F:
case COMPRO_VIDEOMATE_U680F:
case GENERIC_2832:
case GENERIC_2838:
case DEXATEK_5217_DVBT:
case DEXATEK_DIGIVOX_MINI_II_REV3:
case DEXATEK_LOGILINK_VG002A:
case GIGABYTE_GTU7300:
case GTEK_T803:
case LIFEVIEW_LV5T_DELUXE:
case MYGICA_TD312:
case PEAK_102569AGPK:
case PROLECTRIX_DV107669:
case SVEON_STV20:
case TERRATEC_CINERGY_T_REV1:
case TERRATEC_CINERGY_T_REV3:
case TERRATEC_NOXON_REV1_B3:
case TERRATEC_NOXON_REV1_B4:
case TERRATEC_NOXON_REV1_B7:
case TERRATEC_NOXON_REV1_C6:
case TERRATEC_NOXON_REV2:
case TERRATEC_T_STICK_PLUS:
case TWINTECH_UT40:
case ZAAPA_ZTMINDVBZP:
return initRTL2832Tuner( tunerClass, device, descriptor );
case UNKNOWN:
default:
break;
}
}
return new TunerInitStatus( null, "Unknown Device" );
}
private TunerInitStatus initEttusB100Tuner( Device device,
DeviceDescriptor descriptor )
{
return new TunerInitStatus( null, "Ettus B100 tuner not currently "
+ "supported" );
// case ETTUS_USRP_B100:
// mTuners.add( new B100Tuner( device ) );
// status = sLOADED;
// reason = null;
// break;
}
private TunerInitStatus initFuncubeProTuner( Device device,
DeviceDescriptor descriptor )
{
String reason = "NOT LOADED";
MixerTunerDataLine dataline = getMixerTunerDataLine(
TunerClass.FUNCUBE_DONGLE_PRO.getTunerType() );
if( dataline != null )
{
FCD1TunerController controller =
new FCD1TunerController( device, descriptor );
try
{
controller.init();
FCDTuner tuner =
new FCDTuner( dataline, controller );
TunerConfiguration config = getTunerConfiguration( tuner );
if( config != null )
{
tuner.apply( config );
}
return new TunerInitStatus( tuner, "LOADED" );
}
catch ( SourceException e )
{
mLog.error( "couldn't load funcube dongle pro tuner", e );
reason = "error during initialization - " + e.getLocalizedMessage();
}
}
else
{
reason = "couldn't find matching mixer dataline";
}
return new TunerInitStatus( null, "Funcube Dongle Pro tuner not "
+ "loaded - " + reason );
}
private TunerInitStatus initFuncubeProPlusTuner( Device device,
DeviceDescriptor descriptor )
{
String reason = "NOT LOADED";
MixerTunerDataLine dataline = getMixerTunerDataLine(
TunerClass.FUNCUBE_DONGLE_PRO_PLUS.getTunerType() );
if( dataline != null )
{
FCD2TunerController controller =
new FCD2TunerController( device, descriptor );
try
{
controller.init();
FCDTuner tuner =
new FCDTuner( dataline, controller );
TunerConfiguration config = getTunerConfiguration( tuner );
if( config != null )
{
tuner.apply( config );
}
return new TunerInitStatus( tuner, "LOADED" );
}
catch ( SourceException e )
{
mLog.error( "couldn't load funcube dongle pro plus tuner", e );
reason = "error during initialization - " +
e.getLocalizedMessage();
}
}
else
{
reason = "couldn't find matching mixer dataline";
}
return new TunerInitStatus( null, "Funcube Dongle Pro tuner not "
+ "loaded - " + reason );
}
private TunerInitStatus initHackRFTuner( Device device,
DeviceDescriptor descriptor )
{
try
{
HackRFTunerController hackRFController =
new HackRFTunerController( device, descriptor );
hackRFController.init();
HackRFTuner tuner = new HackRFTuner( hackRFController );
TunerConfiguration config = getTunerConfiguration( tuner );
if( config != null )
{
tuner.apply( config );
}
return new TunerInitStatus( tuner, "LOADED" );
}
catch( SourceException se )
{
mLog.error( "couldn't construct HackRF controller/tuner", se );
return new TunerInitStatus( null,
"error constructing HackRF tuner controller" );
}
}
private TunerInitStatus initRTL2832Tuner( TunerClass tunerClass,
Device device,
DeviceDescriptor deviceDescriptor )
{
String reason = "NOT LOADED";
TunerType tunerType = tunerClass.getTunerType();
if( tunerType == TunerType.RTL2832_VARIOUS )
{
try
{
tunerType = RTL2832TunerController.identifyTunerType( device );
}
catch( SourceException e )
{
mLog.error( "couldn't determine RTL2832 tuner type", e );
tunerType = TunerType.UNKNOWN;
}
}
switch( tunerType )
{
case ELONICS_E4000:
try
{
E4KTunerController controller =
new E4KTunerController( device, deviceDescriptor );
controller.init();
RTL2832Tuner rtlTuner =
new RTL2832Tuner( tunerClass, controller );
TunerConfiguration config =
getTunerConfiguration( rtlTuner );
if( config != null )
{
rtlTuner.apply( config );
}
return new TunerInitStatus( rtlTuner, "LOADED" );
}
catch( SourceException se )
{
return new TunerInitStatus( null, "Error constructing E4K tuner "
+ "controller - " + se.getLocalizedMessage() );
}
case RAFAELMICRO_R820T:
mLog.debug( "attempting to construct R820T "
+ "tuner controller" );
try
{
R820TTunerController controller =
new R820TTunerController( device, deviceDescriptor );
mLog.debug( "initializing R820T tuner controller" );
controller.init();
RTL2832Tuner rtlTuner =
new RTL2832Tuner( tunerClass, controller );
TunerConfiguration config =
getTunerConfiguration( rtlTuner );
if( config != null )
{
mLog.debug( "applying tuner config to R820T tuner" );
rtlTuner.apply( config );
}
else
{
mLog.debug( "R820T tuner config was "
+ "null - not applied" );
}
return new TunerInitStatus( rtlTuner, "LOADED" );
}
catch( SourceException se )
{
mLog.error( "error constructing tuner", se );
return new TunerInitStatus( null, "Error constructing R820T "
+ "tuner controller - " + se.getLocalizedMessage() );
}
case FITIPOWER_FC0012:
case FITIPOWER_FC0013:
case RAFAELMICRO_R828D:
case UNKNOWN:
default:
reason = "SDRTRunk doesn't currently support RTL2832 "
+ "Dongle with [" + tunerType.toString() +
"] tuner for tuner class[" + tunerClass.toString() + "]";
break;
}
return new TunerInitStatus( null, reason );
}
/**
* Get a stored tuner configuration or create a default tuner configuration
* for the tuner type, connected at the address.
*
* Note: a named tuner configuration will be stored for for each tuner type
* and address combination.
* @param type - tuner type
* @param address - current usb address/port
* @return - stored tuner configuration or default configuration
*/
private TunerConfiguration getTunerConfiguration( Tuner tuner )
{
TunerConfigurationAssignment selected = mResourceManager
.getSettingsManager().getSelectedTunerConfiguration(
tuner.getTunerType(), tuner.getUniqueID() );
ArrayList<TunerConfiguration> configs = mResourceManager
.getSettingsManager().getTunerConfigurations( tuner.getTunerType() );
TunerConfiguration config = null;
if( selected != null )
{
for( TunerConfiguration tunerConfig: configs )
{
if( tunerConfig.getName().contentEquals( selected.getTunerConfigurationName() ) )
{
config = tunerConfig;
}
}
}
else
{
config = configs.get( 0 );
}
//If we're still null at this point, create a default config
if( config == null )
{
config = mResourceManager.getSettingsManager()
.addNewTunerConfiguration( tuner.getTunerType(), "Default" );
}
//Persist the config as the selected tuner configuration. The method
//auto-saves the setting
mResourceManager.getSettingsManager().setSelectedTunerConfiguration(
tuner.getTunerType(), tuner.getUniqueID(), config );
return config;
}
/**
* Gets the first tuner mixer dataline that corresponds to the tuner class.
*
* Note: this method is not currently able to align multiple tuner mixer
* data lines of the same tuner type. If you have multiple Funcube Dongle
* tuners of the same TYPE, there is no guarantee that you will get the
* correct mixer.
*
* @param tunerClass
* @return
*/
private MixerTunerDataLine getMixerTunerDataLine( TunerType tunerClass )
{
Collection<MixerTunerDataLine> datalines =
MixerManager.getInstance().getMixerTunerDataLines();
for( MixerTunerDataLine mixerTDL: datalines )
{
if( mixerTDL.getMixerTunerType().getTunerClass() == tunerClass )
{
return mixerTDL;
}
}
return null;
}
public class TunerInitStatus
{
private Tuner mTuner;
private String mInfo;
public TunerInitStatus( Tuner tuner, String info )
{
mTuner = tuner;
mInfo = info;
}
public Tuner getTuner()
{
return mTuner;
}
public String getInfo()
{
return mInfo;
}
public boolean isLoaded()
{
return mTuner != null;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.SwingUtilities;
import controller.Editor;
import controller.channel.AbstractChannelEditor;
import controller.channel.ChannelNode;
import controller.channel.ChannelValidationException;
import decode.config.AuxDecodeConfiguration;
public class AuxDecodeComponentEditor extends AbstractChannelEditor
{
private static final long serialVersionUID = 1L;
private HashMap<DecoderType,AuxDecoderCheckBox> mControls =
new HashMap<DecoderType,AuxDecoderCheckBox>();
public AuxDecodeComponentEditor( ChannelNode channelNode )
{
super( channelNode );
List<DecoderType> decoders = DecoderType.getAuxDecoders();
Collections.sort( decoders );
for( DecoderType decoder: decoders )
{
AuxDecoderCheckBox control = new AuxDecoderCheckBox( decoder );
if( getConfig().getAuxDecoders().contains( decoder ) )
{
control.setSelected( true );
}
add( control, "wrap" );
mControls.put( decoder, control );
}
}
public AuxDecodeConfiguration getConfig()
{
return getChannelNode().getChannel().getAuxDecodeConfiguration();
}
@Override
public void save()
{
getConfig().clearAuxDecoders();
for( DecoderType decoder: mControls.keySet() )
{
if( mControls.get( decoder ) .isSelected() )
{
getConfig().addAuxDecoder( decoder );
}
}
}
@Override
public void reset()
{
SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
for( DecoderType decoder: mControls.keySet() )
{
mControls.get( decoder ).setSelected(
getConfig().getAuxDecoders().contains( decoder ) );
}
}
});
}
public class AuxDecoderCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private DecoderType mDecoderType;
public AuxDecoderCheckBox( DecoderType decoder )
{
super( decoder.getDisplayString() );
mDecoderType = decoder;
}
}
}
<file_sep>package source.tuner.hackrf;
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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/>
******************************************************************************/
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.tuner.hackrf.HackRFTunerController.Serial;
public class HackRFInformationPanel extends JPanel
{
private static final long serialVersionUID = 1L;
private final static Logger mLog =
LoggerFactory.getLogger( HackRFInformationPanel.class );
private HackRFTunerController mController;
/**
* Displays HackRF firmware, serial number and part identifier
*/
public HackRFInformationPanel( HackRFTunerController controller )
{
mController = controller;
initGUI();
}
private void initGUI()
{
setLayout( new MigLayout( "fill,wrap 2",
"[right,grow][grow]",
"[][][][grow]" ) );
Serial serial = null;
try
{
serial = mController.getSerial();
}
catch( Exception e )
{
mLog.error( "couldn't read HackRF serial number", e );
}
if( serial != null )
{
add( new JLabel( "Serial:" ) );
add( new JLabel( serial.getSerialNumber() ) );
add( new JLabel( "Part:" ) );
add( new JLabel( serial.getPartID() ) );
}
else
{
add( new JLabel( "Serial:" ) );
add( new JLabel( "Unknown" ) );
add( new JLabel( "Part:" ) );
add( new JLabel( "Unknown" ) );
}
String firmware = null;
try
{
firmware = mController.getFirmwareVersion();
}
catch( Exception e )
{
mLog.error( "couldn't read HackRF firmware version", e );
}
add( new JLabel( "Firmware:" ) );
if( firmware != null )
{
add( new JLabel( firmware ) );
}
else
{
add( new JLabel( "Unknown" ) );
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 record.wave;
import gui.SDRTrunk;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.concurrent.LinkedBlockingQueue;
import javax.sound.sampled.AudioFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import record.Recorder;
import record.RecorderType;
import util.waveaudio.WaveWriter;
/**
* Threaded WAVE audio recorder.
*/
public class WaveRecorder extends Recorder
{
private final static Logger mLog =
LoggerFactory.getLogger( WaveRecorder.class );
private AudioFormat mAudioFormat;
private boolean mRunning = false;
private boolean mPaused = false;
private WaveWriter mWriter;
private String mFileName;
private BufferProcessor mBufferProcessor;
//Sample buffer queue ... constrained to 512 sample buffers (arbitrary size)
LinkedBlockingQueue<ByteBuffer> mBufferQueue =
new LinkedBlockingQueue<ByteBuffer>( 512 );
public WaveRecorder( AudioFormat format, String filename )
{
super( RecorderType.AUDIO );
mAudioFormat = format;
mFileName = filename;
}
public void start() throws IOException
{
if( !mRunning )
{
mWriter = new WaveWriter( mFileName + ".wav", mAudioFormat );
mWriter.start();
mBufferProcessor = new BufferProcessor();
mBufferProcessor.start();
mRunning = true;
}
}
public void stop() throws IOException
{
if( mRunning )
{
mBufferProcessor = null;
mWriter.stop();
mWriter = null;
mRunning = false;
}
}
public void pause()
{
mPaused = true;
}
public void resume()
{
mPaused = false;
}
/**
* Assumes that the byte[] represents samples corresponding to the
* audio format object defined at construction
*/
public void receive( ByteBuffer buffer )
{
if( mRunning && !mPaused )
{
boolean success = mBufferQueue.offer( buffer );
if( !success )
{
mLog.error( "Wave recorder buffer overflow - throwing away " +
buffer.capacity() + " samples" );
}
}
}
public class BufferProcessor extends Thread
{
public void run()
{
while( true )
{
try
{
if( mWriter != null )
{
mWriter.write( mBufferQueue.take() );
}
}
catch ( IOException ioe )
{
mLog.error( "IOException while trying to write to the "
+ "wave writer", ioe );
}
catch ( InterruptedException e )
{
mLog.error( "Oops ... error while processing the buffer"
+ " queue for the wave recorder", e );
}
}
}
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.DenyReason;
import decode.p25.reference.Opcode;
public class DenyResponse extends TSBKMessage
{
public static final int ADDITIONAL_INFORMATION_FLAG = 80;
public static final int[] SERVICE_TYPE = { 82,83,84,85,86,87 };
public static final int[] REASON_CODE = { 88,89,90,91,92,93,94,95 };
public static final int[] CALL_OPTIONS = { 96,97,98,99,100,101,102,103 };
public static final int[] SOURCE_GROUP = { 104,105,106,107,108,109,110,111 };
public static final int[] SOURCE_ADDRESS = { 96,97,98,99,100,101,102,103,104,
105,106,107,108,109,110,111 };
public static final int[] TARGET_ADDRESS = { 120,121,122,123,124,125,126,
127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 };
public DenyResponse( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.DENY_RESPONSE.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " TGT ADDR: " + getTargetAddress() );
sb.append( " REASON:" + getReason().name() );
return sb.toString();
}
public DenyReason getReason()
{
int code = mMessage.getInt( REASON_CODE );
return DenyReason.fromCode( code );
}
public boolean hasAdditionalInformation()
{
return mMessage.get( ADDITIONAL_INFORMATION_FLAG );
}
public Opcode getServiceType()
{
return Opcode.fromValue( mMessage.getInt( SERVICE_TYPE ) );
}
public String getSourceAddress()
{
switch( getServiceType() )
{
case GROUP_DATA_CHANNEL_GRANT:
case GROUP_VOICE_CHANNEL_GRANT:
return mMessage.getHex( SOURCE_GROUP, 4 );
case UNIT_TO_UNIT_VOICE_CHANNEL_GRANT:
case INDIVIDUAL_DATA_CHANNEL_GRANT:
case TELEPHONE_INTERCONNECT_VOICE_CHANNEL_GRANT:
return mMessage.getHex( SOURCE_ADDRESS, 6 );
default:
break;
}
return null;
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
@Override
public String getToID()
{
return getTargetAddress();
}
}
<file_sep>package decode.p25.message.pdu.confirmed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.reference.MDPConfigurationOption;
public class SNDCPActivateTDSContextRequest extends PDUConfirmedMessage
{
public final static Logger mLog =
LoggerFactory.getLogger( SNDCPActivateTDSContextRequest.class );
public static final int[] SNDCP_VERSION = { 180,181,182,183 };
public static final int[] NSAPI = { 184,185,186,187 };
public static final int[] NAT = { 188,189,190,191 };
public static final int[] IP_1 = { 192,193,194,195,196,197,198,199 };
public static final int[] IP_2 = { 200,201,202,203,204,205,206,207 };
public static final int[] IP_3 = { 208,209,210,211,212,213,214,215 };
public static final int[] IP_4 = { 216,217,218,219,220,221,222,223 };
public static final int[] DSUT = { 224,225,226,227 };
public static final int[] UDPC = { 228,229,230,231 };
public static final int[] IPHC = { 232,233,234,235,236,237,238,239 };
public static final int[] TCPSS = { 240,241,242,243 };
public static final int[] UDPSS = { 244,245,246,247 };
public static final int[] MDPCO = { 248,249,250,251,252,253,254,255 };
public SNDCPActivateTDSContextRequest( PDUConfirmedMessage message )
{
super( message );
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( "NAC:" );
sb.append( getNAC() );
sb.append( " PDUC LLID:" );
sb.append( getLogicalLinkID() );
sb.append( " REQUEST SNDCP PACKET DATA ACTIVATE " );
sb.append( getNetworkAddressType() );
sb.append( " " );
sb.append( getIPAddress() );
sb.append( " NSAPI:" );
sb.append( getNSAPI() );
sb.append( " CRC[" );
sb.append( getErrorStatus() );
sb.append( "]" );
sb.append( " PACKET #" );
sb.append( getPacketSequenceNumber() );
if( isFinalFragment() && getFragmentSequenceNumber() == 0 )
{
sb.append( ".C" );
}
else
{
sb.append( "." );
sb.append( getFragmentSequenceNumber() );
if( isFinalFragment() )
{
sb.append( "C" );
}
}
sb.append( " " );
return sb.toString();
}
/**
* SNDCP Version: 1 = P25 SNDCP Version 1
*/
public int getSNDCPVersion()
{
return mMessage.getInt( SNDCP_VERSION );
}
/**
* Network Service Access Point Identifier - up to 14 NSAPI's can be
* allocated to the mobile with each NSAPI to be used for a specific
* protocol layer.
*/
public int getNSAPI()
{
return mMessage.getInt( NSAPI );
}
public String getNetworkAddressType()
{
return mMessage.getInt( NAT ) == 0 ? "IPV4 STATIC" : "IPV4 DYNAMIC";
}
public String getIPAddress()
{
StringBuilder sb = new StringBuilder();
sb.append( mMessage.getInt( IP_1 ) );
sb.append( "." );
sb.append( mMessage.getInt( IP_2 ) );
sb.append( "." );
sb.append( mMessage.getInt( IP_3 ) );
sb.append( "." );
sb.append( mMessage.getInt( IP_4 ) );
return sb.toString();
}
public String getDataSubscriberUnitType()
{
switch( mMessage.getInt( DSUT ) )
{
case 0:
return "DATA ONLY MRC";
case 1:
return "DATA AND VOICE MRC";
}
return "UNKNOWN";
}
public boolean hasIPHeaderCompression()
{
return mMessage.getInt( IPHC ) == 1;
}
public boolean hasUserDataPayloadCompression()
{
return mMessage.getInt( UDPC ) == 1;
}
public int getTCPStateSlots()
{
return mMessage.getInt( TCPSS );
}
public int getUDPStateSlots()
{
return mMessage.getInt( UDPSS );
}
public MDPConfigurationOption getMDPConfigurationOption()
{
return MDPConfigurationOption.fromValue( mMessage.getInt( MDPCO ) );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 audio.inverted;
public enum AudioType
{
NORMAL( "Normal Audio", "Clear", 0 ),
MUTE( "Muted Audio", "Muted", 0 ),
INV2500( "Inverted Audio 2500Hz", "Inverted", 2500 ),
INV2550( "Inverted Audio 2550Hz", "Inverted", 2550 ),
INV2600( "Inverted Audio 2600Hz", "Inverted", 2600 ),
INV2632( "Inverted Audio 2632Hz", "Inverted", 2632 ),
INV2675( "Inverted Audio 2675Hz", "Inverted", 2675 ),
INV2718( "Inverted Audio 2718Hz", "Inverted", 2718 ),
INV2725( "Inverted Audio 2725Hz", "Inverted", 2725 ),
INV2750( "Inverted Audio 2750Hz", "Inverted", 2750 ),
INV2760( "Inverted Audio 2760Hz", "Inverted", 2760 ),
INV2775( "Inverted Audio 2775Hz", "Inverted", 2775 ),
INV2800( "Inverted Audio 2800Hz", "Inverted", 2800 ),
INV2825( "Inverted Audio 2825Hz", "Inverted", 2825 ),
INV2868( "Inverted Audio 2868Hz", "Inverted", 2868 ),
INV3023( "Inverted Audio 3023Hz", "Inverted", 3023 ),
INV3107( "Inverted Audio 3107Hz", "Inverted", 3107 ),
INV3196( "Inverted Audio 3196Hz", "Inverted", 3196 ),
INV3333( "Inverted Audio 3333Hz", "Inverted", 3333 ),
INV3339( "Inverted Audio 3339Hz", "Inverted", 3339 ),
INV3360( "Inverted Audio 3360Hz", "Inverted", 3360 ),
INV3375( "Inverted Audio 3375Hz", "Inverted", 3375 ),
INV3400( "Inverted Audio 3400Hz", "Inverted", 3400 ),
INV3450( "Inverted Audio 3450Hz", "Inverted", 3450 ),
INV3496( "Inverted Audio 3496Hz", "Inverted", 3496 ),
INV3729( "Inverted Audio 3729Hz", "Inverted", 3729 ),
INV4096( "Inverted Audio 4096Hz", "Inverted", 4096 ),
INV4300( "Inverted Audio 4300Hz", "Inverted", 4300 ),
INV4500( "Inverted Audio 4500Hz", "Inverted", 4500 ),
INV4700( "Inverted Audio 4700Hz", "Inverted", 4700 ),
INV4900( "Inverted Audio 4900Hz", "Inverted", 4900 );
private String mDisplayString;
private String mShortDisplayString;
private int mAudioInversionFrequency;
AudioType( String displayString,
String shortDisplayString,
int inversionFrequency )
{
mDisplayString = displayString;
mShortDisplayString = shortDisplayString;
mAudioInversionFrequency = inversionFrequency;
}
public String getDisplayString()
{
return mDisplayString;
}
public String getShortDisplayString()
{
return mShortDisplayString;
}
public int getAudioInversionFrequency()
{
return mAudioInversionFrequency;
}
@Override
public String toString()
{
return mDisplayString;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
/**
* Abstract class to hold a named configuration for a specific type of tuner
*/
@XmlType( name = "tuner_configuration" )
public abstract class TunerConfiguration
{
protected String mName;
/**
* Default constructor to support JAXB
*/
public TunerConfiguration()
{
this( "Unknown" );
}
public String toString()
{
return mName;
}
/**
* Normal constructor
*/
public TunerConfiguration( String name )
{
mName = name;
}
@XmlAttribute( name = "name" )
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
@XmlAttribute( name = "tuner_type" )
public abstract TunerType getTunerType();
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.p25;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.SourceEditor;
import source.tuner.TunerEditor;
import controller.Editor;
import controller.channel.ChannelValidationException;
import decode.DecodeEditor;
import decode.config.DecodeConfigP25Phase1;
import decode.config.DecodeConfiguration;
import decode.p25.P25Decoder.Modulation;
public class P25Editor extends DecodeEditor
{
private final static Logger mLog = LoggerFactory.getLogger( P25Editor.class );
private static final long serialVersionUID = 1L;
private JComboBox<P25Decoder.Modulation> mComboModulation;
public P25Editor( DecodeConfiguration config )
{
super( config );
initGUI();
}
private void initGUI()
{
mComboModulation = new JComboBox<P25Decoder.Modulation>();
mComboModulation.setModel( new DefaultComboBoxModel<P25Decoder.Modulation>(
P25Decoder.Modulation.values() ) );
mComboModulation.setSelectedItem( ((DecodeConfigP25Phase1)mConfig).getModulation() );
mComboModulation.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
P25Decoder.Modulation selected = mComboModulation
.getItemAt( mComboModulation.getSelectedIndex() );
if( selected != null )
{
((DecodeConfigP25Phase1)mConfig).setModulation( selected );
}
}
} );
add( mComboModulation, "span 2,wrap" );
}
/**
* Enforce source=tuner for CQPSK modulation
*/
@Override
public void validate( Editor editor ) throws ChannelValidationException
{
if( editor instanceof SourceEditor &&
((DecodeConfigP25Phase1)mConfig).getModulation() == Modulation.CQPSK )
{
if( !( editor instanceof TunerEditor ) )
{
throw new ChannelValidationException(
"<html><body width='175'><h1>LSM Simulcast</h1>"
+ "<p>P25 LSM Simulcast decoder can only be used with "
+ "a tuner source. Please change the Source to use a tuner"
+ " or change the P25 Decoder to C4FM modulation" );
}
}
}
}
<file_sep>#!/bin/bash
java -XX:+UseG1GC -cp "*:libs/*" gui.SDRTrunk&<file_sep>package decode.p25.message.tsbk.osp.voice;
import java.util.ArrayList;
import java.util.List;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Digit;
import decode.p25.reference.Opcode;
public class TelephoneInterconnectAnswerRequest extends TSBKMessage
{
public static final int[] DIGIT_1 = { 80,81,82,83 };
public static final int[] DIGIT_2 = { 84,85,86,87 };
public static final int[] DIGIT_3 = { 88,89,90,91 };
public static final int[] DIGIT_4 = { 92,93,94,95 };
public static final int[] DIGIT_5 = { 96,97,98,99 };
public static final int[] DIGIT_6 = { 100,101,102,103 };
public static final int[] DIGIT_7 = { 104,105,106,107 };
public static final int[] DIGIT_8 = { 108,109,110,111 };
public static final int[] DIGIT_9 = { 112,113,114,115 };
public static final int[] DIGIT_10 = { 116,117,118,119 };
public static final int[] TARGET_ADDRESS = { 120,121,122,123,124,125,126,
127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 };
public TelephoneInterconnectAnswerRequest( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.TELEPHONE_INTERCONNECT_ANSWER_REQUEST.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " TO:" );
sb.append( getTargetAddress() );
sb.append( " TEL:" );
sb.append( getTelephoneNumber() );
return sb.toString();
}
public String getTelephoneNumber()
{
List<Integer> digits = new ArrayList<Integer>();
digits.add( mMessage.getInt( DIGIT_1 ) );
digits.add( mMessage.getInt( DIGIT_2 ) );
digits.add( mMessage.getInt( DIGIT_3 ) );
digits.add( mMessage.getInt( DIGIT_4 ) );
digits.add( mMessage.getInt( DIGIT_5 ) );
digits.add( mMessage.getInt( DIGIT_6 ) );
digits.add( mMessage.getInt( DIGIT_7 ) );
digits.add( mMessage.getInt( DIGIT_8 ) );
digits.add( mMessage.getInt( DIGIT_9 ) );
digits.add( mMessage.getInt( DIGIT_10 ) );
return Digit.decode( digits );
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
@Override
public String getToID()
{
return getTargetAddress();
}
}
<file_sep>package decode.p25.message.pdu.confirmed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class PDUConfirmedMessageFactory
{
public final static Logger mLog =
LoggerFactory.getLogger( PDUConfirmedMessage.class );
public static PDUConfirmedMessage getMessage( PDUConfirmedMessage message )
{
switch( message.getServiceAccessPoint() )
{
case ADDRESS_RESOLUTION_PROTOCOL:
break;
case CHANNEL_REASSIGNMENT:
break;
case CIRCUIT_DATA:
break;
case CIRCUIT_DATA_CONTROL:
break;
case ENCRYPTED_KEY_MANAGEMENT_MESSAGE:
break;
case ENCRYPTED_TRUNKING_CONTROL:
break;
case ENCRYPTED_USER_DATA:
break;
case EXTENDED_ADDRESS:
break;
case MR_CONFIGURATION:
break;
case MR_LOOPBACK:
break;
case MR_OUT_OF_SERVICE:
break;
case MR_PAGING:
break;
case MR_STATISTICS:
break;
case PACKET_DATA:
break;
case REGISTRATION_AND_AUTHORIZATION:
break;
/* Deliberate fall-through */
case SNDCP_PACKET_DATA_CONTROL:
case UNENCRYPTED_USER_DATA:
switch( message.getPDUType() )
{
case SN_ACTIVATE_TDS_CONTEXT_ACCEPT:
return new SNDCPActivateTDSContextAccept( message );
case SN_ACTIVATE_TDS_CONTEXT_REJECT:
return new SNDCPActivateTDSContextReject( message );
case SN_ACTIVATE_TDS_CONTEXT_REQUEST:
return new SNDCPActivateTDSContextRequest( message );
case SN_DEACTIVATE_TDS_CONTEXT_ACCEPT:
case SN_DEACTIVATE_TDS_CONTEXT_REQUEST:
return new SNDCPDeactivateTDSContext( message );
case SN_RF_CONFIRMED_DATA:
return new SNDCPUserData( message );
case SN_RF_UNCONFIRMED_DATA:
break;
default:
break;
}
break;
case SYSTEM_CONFIGURATION:
break;
case UNENCRYPTED_KEY_MANAGEMENT_MESSAGE:
break;
case UNENCRYPTED_TRUNKING_CONTROL:
break;
default:
}
return message;
}
}
<file_sep>package decode.p25;
import dsp.symbol.Dibit;
import sample.Broadcaster;
import sample.Listener;
import sample.real.RealSampleListener;
/**
* C4FM slicer to convert the output stream of the C4FMSymbolFilter into a
* stream of C4FM symbols.
*
* Supports registering listener(s) to receive normal and/or inverted symbol
* output streams.
*/
public class C4FMSlicer implements RealSampleListener
{
private static final float THRESHOLD = 2.0f;
private Broadcaster<Dibit> mBroadcaster = new Broadcaster<Dibit>();
/**
* Primary method for receiving output from the C4FMSymbolFilter. Slices
* (converts) the filtered sample value into a C4FMSymbol decision.
*/
@Override
public void receive( float sample )
{
if( sample > THRESHOLD )
{
dispatch( Dibit.D01_PLUS_3 );
}
else if( sample > 0 )
{
dispatch( Dibit.D00_PLUS_1 );
}
else if( sample > -THRESHOLD )
{
dispatch( Dibit.D10_MINUS_1 );
}
else
{
dispatch( Dibit.D11_MINUS_3 );
}
}
/**
* Dispatches the symbol decision to any registered listeners
*/
private void dispatch( Dibit symbol )
{
mBroadcaster.receive( symbol );
}
/**
* Registers the listener to receive the normal (non-inverted) C4FM symbol
* stream.
*/
public void addListener( Listener<Dibit> listener )
{
mBroadcaster.addListener( listener );
}
/**
* Removes the listener
*/
public void removeListener( Listener<Dibit> listener )
{
mBroadcaster.removeListener( listener );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.mixer;
import java.util.List;
import javax.sound.sampled.Mixer;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import source.SourceEditor;
import source.config.SourceConfigMixer;
import source.config.SourceConfiguration;
import source.mixer.MixerManager.DiscoveredMixer;
import controller.ResourceManager;
public class MixerEditor extends SourceEditor
{
private static final long serialVersionUID = 1L;
private JComboBox<DiscoveredMixer> mComboMixers;
private JComboBox<MixerChannel>mComboChannels;
protected Mixer.Info mSelectedMixer = null;
public MixerEditor( ResourceManager resourceManager,
SourceConfiguration config )
{
super( resourceManager, config );
initGUI();
}
private void initGUI()
{
JLabel mixerLabel = new JLabel( "Mixer:" );
add( mixerLabel, "align right" );
mComboMixers = new JComboBox<DiscoveredMixer>();
add( mComboMixers, "wrap" );
resetMixers();
JLabel channelLabel = new JLabel( "Channel:" );
add( channelLabel, "align right" );
mComboChannels = new JComboBox<MixerChannel>();
add( mComboChannels, "wrap" );
resetChannels();
}
public void reset()
{
resetMixers();
resetChannels();
}
public void save()
{
SourceConfigMixer config = (SourceConfigMixer)mConfig;
DiscoveredMixer selectedMixer =
mComboMixers.getItemAt( mComboMixers.getSelectedIndex() );
if( selectedMixer != null )
{
config.setMixer( selectedMixer.getMixerName() );
}
MixerChannel channel = mComboChannels.getItemAt(
mComboChannels.getSelectedIndex() );
if( channel != null )
{
if( config.getChannel() != channel )
{
config.setChannel( channel );
}
}
}
private void resetMixers()
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
DiscoveredMixer[] mixers = MixerManager.getInstance().getMixers();
mComboMixers.setModel(
new DefaultComboBoxModel<DiscoveredMixer>( mixers ) );
SourceConfigMixer config = (SourceConfigMixer)mConfig;
String mixer = config.getMixer();
if( mixer != null )
{
mComboMixers.setSelectedItem( mixer );
}
else
{
//Mixer either hasn't been set yet, or it was set to a
//mixer that is no longer available. Set the mixer to the
//first item, and then store the value
if( mixers.length > 0 )
{
mComboMixers.setSelectedIndex( 0 );
DiscoveredMixer selectedMixer =
(DiscoveredMixer)mComboMixers.getSelectedItem();
config.setMixer( selectedMixer.getMixerName() );
}
}
}
});
}
private void resetChannels()
{
javax.swing.SwingUtilities.invokeLater(new Runnable()
{
@Override
public void run()
{
mComboChannels.setModel(
new DefaultComboBoxModel<MixerChannel>( MixerChannel.values() ) );
MixerChannel channel = ((SourceConfigMixer)mConfig).getChannel();
mComboChannels.setSelectedItem( channel );
}
});
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import decode.p25.reference.Response;
public class LocationRegistrationResponse extends TSBKMessage
{
public static final int[] REGISTRATION_RESPONSE = { 86,87 };
public static final int[] GROUP_ADDRESS = { 88,89,90,91,92,93,94,95,96,97,
98,99,100,101,102,103 };
public static final int[] RFSS_ID = { 104,105,106,107,108,109,110,111 };
public static final int[] SITE_ID = { 112,113,114,115,116,117,118,119 };
public static final int[] TARGET_ADDRESS = { 120,121,122,123,124,125,126,
127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 };
public LocationRegistrationResponse( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.LOCATION_REGISTRATION_RESPONSE.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " REGISTRATION:" + getResponse().name() );
sb.append( " GROUP:" + getGroupAddress() );
sb.append( " RFSS: " + getRFSSID() );
sb.append( " SITE: " + getSiteID() );
sb.append( " TGT ADDR: " + getTargetAddress() );
return sb.toString();
}
public Response getResponse()
{
return Response.fromValue( mMessage.getInt( REGISTRATION_RESPONSE ) );
}
public String getGroupAddress()
{
return mMessage.getHex( GROUP_ADDRESS, 4 );
}
public String getRFSSID()
{
return mMessage.getHex( RFSS_ID, 2 );
}
public String getSiteID()
{
return mMessage.getHex( SITE_ID, 2 );
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
@Override
public String getToID()
{
return getTargetAddress();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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.jdesktop.swingx.mapviewer.bmng;
import java.awt.Dimension;
import java.awt.geom.Point2D;
import org.jdesktop.swingx.mapviewer.DefaultTileFactory;
import org.jdesktop.swingx.mapviewer.GeoPosition;
/**
* @author joshy
*/
public class CylindricalProjectionTileFactory extends DefaultTileFactory
{
/**
* Uses {@link SLMapServerInfo}
*/
public CylindricalProjectionTileFactory()
{
this(new SLMapServerInfo());
}
/**
* @param info the tile factory info
*/
public CylindricalProjectionTileFactory(SLMapServerInfo info)
{
super(info);
}
@Override
public Dimension getMapSize(int zoom)
{
int midpoint = ((SLMapServerInfo) getInfo()).getMidpoint();
if (zoom < midpoint)
{
int w = (int) Math.pow(2, midpoint - zoom);
return new Dimension(w, w / 2);
// return super.getMapSize(zoom);
}
return new Dimension(2, 1);
}
@Override
public Point2D geoToPixel(GeoPosition c, int zoom)
{
// calc the pixels per degree
Dimension mapSizeInTiles = getMapSize(zoom);
// double size_in_tiles = (double)getInfo().getMapWidthInTilesAtZoom(zoom);
// double size_in_tiles = Math.pow(2, getInfo().getTotalMapZoom() - zoom);
double size_in_pixels = mapSizeInTiles.getWidth() * getInfo().getTileSize(zoom);
double ppd = size_in_pixels / 360;
// the center of the world
double centerX = this.getTileSize(zoom) * mapSizeInTiles.getWidth() / 2;
double centerY = this.getTileSize(zoom) * mapSizeInTiles.getHeight() / 2;
double x = c.getLongitude() * ppd + centerX;
double y = -c.getLatitude() * ppd + centerY;
return new Point2D.Double(x, y);
}
@Override
public GeoPosition pixelToGeo(Point2D pix, int zoom)
{
// calc the pixels per degree
Dimension mapSizeInTiles = getMapSize(zoom);
double size_in_pixels = mapSizeInTiles.getWidth() * getInfo().getTileSize(zoom);
double ppd = size_in_pixels / 360;
// the center of the world
double centerX = this.getTileSize(zoom) * mapSizeInTiles.getWidth() / 2;
double centerY = this.getTileSize(zoom) * mapSizeInTiles.getHeight() / 2;
double lon = (pix.getX() - centerX) / ppd;
double lat = -(pix.getY() - centerY) / ppd;
return new GeoPosition(lat, lon);
}
/*
* x = lat * ppd + fact x - fact = lat * ppd (x - fact)/ppd = lat y = -lat*ppd + fact -(y-fact)/ppd = lat
*/
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.mpt1327;
import java.util.Iterator;
import java.util.TreeSet;
import message.Message;
import sample.Listener;
import alias.Alias;
import alias.AliasList;
import controller.activity.ActivitySummaryProvider;
public class MPT1327ActivitySummary implements ActivitySummaryProvider,
Listener<Message>
{
private static final int sINT_NULL_VALUE = -1;
private AliasList mAliasList;
private TreeSet<String> mIdents = new TreeSet<String>();
private String mSite;
/**
* Compiles a summary of active talkgroups, unique radio ids encountered
* in the decoded messages. Talkgroups have to be heard a minimum of twice
* to be considered valid ... in order to weed out the invalid ones.
*
* Returns a textual summary of the activity
*/
public MPT1327ActivitySummary( AliasList list )
{
mAliasList = list;
}
/**
* Cleanup method
*/
public void dispose()
{
mIdents.clear();
}
@Override
public void receive( Message message )
{
if( message instanceof MPT1327Message )
{
MPT1327Message mpt = ((MPT1327Message)message);
if( mpt.isValid() )
{
switch( mpt.getMessageType() )
{
case ACK:
mIdents.add( mpt.getFromID() );
break;
case ACKI:
mIdents.add( mpt.getFromID() );
mIdents.add( mpt.getToID() );
break;
case AHYC:
mIdents.add( mpt.getToID() );
break;
case ALH:
mSite = mpt.getSiteID();
break;
case GTC:
if( mpt.hasFromID() )
{
mIdents.add( mpt.getFromID() );
}
if( mpt.hasToID() )
{
mIdents.add( mpt.getToID() );
}
break;
}
}
}
}
@Override
public String getSummary()
{
StringBuilder sb = new StringBuilder();
sb.append( "Activity Summary\n" );
sb.append( "Decoder:\tMPT-1327\n" );
sb.append( "Site:\t" );
if( mSite != null )
{
sb.append( mSite );
if( mAliasList != null )
{
Alias siteAlias = mAliasList.getSiteID( mSite );
if( siteAlias != null )
{
sb.append( " " );
sb.append( siteAlias.getName() );
sb.append( "\n" );
}
}
}
else
{
sb.append( "Unknown\n" );
}
sb.append( "\n" );
sb.append( "Talkgroups\n" );
if( mIdents.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<String> it = mIdents.iterator();
while( it.hasNext() )
{
String ident = it.next();
sb.append( " " );
sb.append( ident );
sb.append( " " );
Alias alias = mAliasList.getMPT1327Alias( ident );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
return sb.toString();
}
}
<file_sep>package source;
import sample.Provider;
import sample.real.RealBuffer;
public abstract class RealSource extends Source implements Provider<RealBuffer>
{
public RealSource( String name )
{
super( name, SampleType.REAL );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import sample.Broadcaster;
import sample.Listener;
public class FloatToByteBufferAssembler implements Listener<Float>
{
private Broadcaster<ByteBuffer> mBroadcaster = new Broadcaster<ByteBuffer>();
private int mBufferSize = 0;
private ByteBuffer mBuffer;
public FloatToByteBufferAssembler( int bufferSize )
{
mBufferSize = bufferSize;
resetBuffer();
}
public void addByteBufferListener( Listener<ByteBuffer> listener )
{
mBroadcaster.addListener( listener );
}
public void removeByteBufferListener( Listener<ByteBuffer> listener )
{
mBroadcaster.removeListener( listener );
}
private void resetBuffer()
{
mBuffer = ByteBuffer.allocate( mBufferSize );
mBuffer.order( ByteOrder.BIG_ENDIAN );
}
@Override
public void receive( Float sample )
{
mBuffer.putShort( Float.valueOf( sample ).shortValue() );
if( mBuffer.position() >= mBufferSize )
{
//Buffer is full ... send it
mBroadcaster.receive( mBuffer );
//Reset the buffer
resetBuffer();
}
}
}
<file_sep>package decode.p25.reference;
public enum MDPConfigurationOption
{
INTERNAL( "INTERNAL INTERFACE", 0 ),
MDP_SLIP( "MDP SLIP", 1 ),
MDP_PPP( "MDP PPP", 2 ),
UNKNOWN( "UNKNOWN", -1 );
private String mLabel;
private int mValue;
private MDPConfigurationOption( String label, int value )
{
mLabel = label;
mValue = value;
}
public String getLabel()
{
return mLabel;
}
public int getValue()
{
return mValue;
}
public static MDPConfigurationOption fromValue( int value )
{
if( 0 <= value && value <= 2 )
{
return values()[ value ];
}
return UNKNOWN;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.mpt1327;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import message.Message;
import sample.Listener;
import source.config.SourceConfigTuner;
import alias.AliasList;
import audio.SquelchListener;
import audio.SquelchListener.SquelchState;
import controller.activity.CallEvent;
import controller.activity.CallEvent.CallEventType;
import controller.channel.Channel;
import controller.channel.Channel.ChannelType;
import controller.channel.ChannelMap;
import controller.channel.ProcessingChain;
import controller.state.AuxChannelState;
import controller.state.ChannelState;
import decode.config.DecodeConfigMPT1327;
import decode.mpt1327.MPT1327Message.IdentType;
public class MPT1327ChannelState extends ChannelState
{
private final static Logger mLog = LoggerFactory.getLogger( MPT1327ChannelState.class );
private String mSite;
private String mFromTalkgroup;
private String mToTalkgroup;
private int mChannelNumber;
private ChannelType mChannelType;
private ChannelMap mChannelMap;
private MPT1327ActivitySummary mActivitySummary;
public MPT1327ChannelState( ProcessingChain processingChain,
AliasList aliasList,
ChannelMap channelMap )
{
super( processingChain, aliasList );
mActivitySummary = new MPT1327ActivitySummary( aliasList );
mChannelMap = channelMap;
mChannelType = processingChain.getChannel().getChannelType();
}
public void dispose()
{
super.dispose();
mActivitySummary.dispose();
mActivitySummary = null;
mCurrentCallEvent = null;
}
public void setCurrentCall( MPT1327CallEvent event )
{
mCurrentCallEvent = event;
}
@Override
public String getActivitySummary()
{
StringBuilder sb = new StringBuilder();
sb.append( mActivitySummary.getSummary() );
for( AuxChannelState state: mAuxChannelStates )
{
sb.append( state.getActivitySummary() );
sb.append( "\n\n" );
}
return sb.toString();
}
@Override
public void receive( Message message )
{
super.receive( message );
if( message instanceof MPT1327Message )
{
mActivitySummary.receive( message );
MPT1327Message mpt = (MPT1327Message)message;
if( mpt.isValid() )
{
switch( mpt.getMessageType() )
{
case ACK:
IdentType identType = ( (MPT1327Message) message ).getIdent1Type();
if( identType == IdentType.REGI )
{
mCallEventModel.add(
new MPT1327CallEvent.Builder( CallEventType.REGISTER )
.aliasList( getProcessingChain().getAliasList() )
.channel( String.valueOf( mChannelNumber ) )
.details( "REGISTERED ON NETWORK" )
.frequency( mChannelMap.getFrequency( mChannelNumber ) )
.from( mpt.getToID() )
.to( mpt.getFromID() )
.build() );
}
else
{
mCallEventModel.add(
new MPT1327CallEvent.Builder( CallEventType.RESPONSE )
.aliasList( getProcessingChain().getAliasList() )
.channel( String.valueOf( mChannelNumber ) )
.details( "ACK " + identType.getLabel() )
.frequency( mChannelMap.getFrequency( mChannelNumber ) )
.from( mpt.getFromID() )
.to( mpt.getToID() )
.build() );
}
break;
case AHYC:
mCallEventModel.add(
new MPT1327CallEvent.Builder( CallEventType.COMMAND )
.aliasList( getProcessingChain().getAliasList() )
.channel( String.valueOf( mChannelNumber ) )
.details( ( (MPT1327Message) message ).getRequestString() )
.frequency( mChannelMap.getFrequency( mChannelNumber ) )
.from( mpt.getFromID() )
.to( mpt.getToID() )
.build() );
break;
case AHYQ:
mCallEventModel.add(
new MPT1327CallEvent.Builder( CallEventType.STATUS )
.aliasList( getProcessingChain().getAliasList() )
.channel( String.valueOf( mChannelNumber ) )
.details( mpt.getStatusMessage() )
.frequency( mChannelMap.getFrequency( mChannelNumber ) )
.from( mpt.getFromID() )
.to( mpt.getToID() )
.build() );
break;
case ALH:
String site = mpt.getSiteID();
if( mSite == null )
{
mSite = site;
broadcastChange( ChangedAttribute.CHANNEL_SITE_NUMBER );
}
else if( site != null && !site.contentEquals( mSite ) )
{
mSite = site;
broadcastChange( ChangedAttribute.CHANNEL_SITE_NUMBER );
}
setState( State.CONTROL );
break;
case GTC:
if( mpt.isValidCall() )
{
int channelNumber = mpt.getChannel();
if( !getProcessingChain().getChannel()
.hasTrafficChannel( channelNumber ) )
{
String aliasListName = mProcessingChain
.getChannel().getAliasListName();
Channel traffic = getTrafficChannel( channelNumber,
aliasListName );
/* Set the system and site to same as control channel */
traffic.setSystem( getProcessingChain().getChannel()
.getSystem(), false );
traffic.setSite( getProcessingChain().getChannel()
.getSite(), false );
/* Add the traffic channel to the parent control channel */
getProcessingChain().getChannel()
.addTrafficChannel( channelNumber, traffic );
/* Start the traffic channel */
traffic.setEnabled( true );
/* Set traffic channel state info */
MPT1327ChannelState trafficState =
(MPT1327ChannelState)traffic
.getProcessingChain().getChannelState();
MPT1327ChannelState controlState =
(MPT1327ChannelState)getProcessingChain()
.getChannelState();
trafficState.setChannelMap( controlState.getChannelMap() );
trafficState.setChannelNumber( channelNumber );
trafficState.setFromTalkgroup( mpt.getFromID() );
trafficState.setToTalkgroup( mpt.getToID() );
/* Add this control channel as message listener on the
* traffic channel so we can receive call tear-down
* messages */
traffic.addListener( (Listener<Message>)this );
CallEventType type = traffic.isProcessing() ?
CallEventType.CALL :
CallEventType.CALL_NO_TUNER;
/*
* Set the traffic channel's call event model to
* share the control channel's call event model
*/
traffic.getProcessingChain().getChannelState()
.setCallEventModel( mCallEventModel );
MPT1327CallEvent callStartEvent =
new MPT1327CallEvent.Builder( type )
.aliasList( traffic.getProcessingChain().getAliasList() )
.channel( String.valueOf( channelNumber ) )
.frequency( mChannelMap.getFrequency( channelNumber ) )
.from( mpt.getFromID() )
.to( mpt.getToID() )
.build();
traffic.getProcessingChain().getChannelState()
.setCurrentCallEvent( callStartEvent );
mCallEventModel.add( callStartEvent );
}
}
break;
case CLEAR:
case MAINT:
if( mChannelType == ChannelType.TRAFFIC )
{
fade( CallEventType.CALL_END );
}
break;
case HEAD_PLUS1:
case HEAD_PLUS2:
case HEAD_PLUS3:
case HEAD_PLUS4:
mCallEventModel.add(
new MPT1327CallEvent.Builder( CallEventType.SDM )
.aliasList( mAliasList )
.details( mpt.getMessage() )
.from( mpt.getFromID() )
.to( mpt.getToID() )
.build() );
break;
}
}
}
}
/**
* Intercept the fade event so that we can generate a call end event
*/
@Override
public void fade( final CallEventType type )
{
/*
* We can receive multiple call tear-down messages -- only post a call
* end event for the one that can change the state to fade
*/
if( getState().canChangeTo( State.FADE ) )
{
CallEvent current = getCurrentCallEvent();
if( current != null )
{
mCallEventModel.setEnd( current );
}
else
{
mCallEventModel.add(
new MPT1327CallEvent.Builder( type )
.aliasList( getAliasList() )
.channel( String.valueOf( mChannelNumber ) )
.frequency( mChannelMap.getFrequency( mChannelNumber ) )
.from( mFromTalkgroup )
.to( mToTalkgroup )
.build() );
}
setCurrentCall( null );
}
super.fade( type );
}
/**
* Make the ConventionalChannelState always unsquelched
*/
public void addListener( SquelchListener listener )
{
super.addListener( listener );
super.setSquelchState( SquelchState.UNSQUELCH );
}
public void reset()
{
mFromTalkgroup = null;
broadcastChange( ChangedAttribute.FROM_TALKGROUP );
mToTalkgroup = null;
broadcastChange( ChangedAttribute.TO_TALKGROUP );
super.reset();
}
public String getSite()
{
return mSite;
}
public ChannelMap getChannelMap()
{
return mChannelMap;
}
public void setChannelMap( ChannelMap channelMap )
{
mChannelMap = channelMap;
}
public String getFromTalkgroup()
{
return mFromTalkgroup;
}
/**
* Set the talkgroup. This is used primarily for traffic channels since
* the talkgroup will already have been identified prior to the traffic
* channel being created.
*/
public void setFromTalkgroup( String fromTalkgroup )
{
mFromTalkgroup = fromTalkgroup;
broadcastChange( ChangedAttribute.FROM_TALKGROUP );
}
public String getToTalkgroup()
{
return mToTalkgroup;
}
/**
* Set the talkgroup. This is used primarily for traffic channels since
* the talkgroup will already have been identified prior to the traffic
* channel being created.
*/
public void setToTalkgroup( String toTalkgroup )
{
mToTalkgroup = toTalkgroup;
broadcastChange( ChangedAttribute.TO_TALKGROUP );
}
public int getChannelNumber()
{
return mChannelNumber;
}
/**
* Set the channel number. This is used primarily for traffic channels since
* the channel will already have been identified prior to the traffic
* channel being created.
*/
public void setChannelNumber( int channel )
{
mChannelNumber = channel;
broadcastChange( ChangedAttribute.CHANNEL_NUMBER );
}
public String getAliasListName()
{
return mProcessingChain.getChannel().getAliasListName();
}
private Channel getTrafficChannel( int channelNumber, String aliasListName )
{
Channel traffic = new Channel( "Traffic Channel " + channelNumber,
ChannelType.TRAFFIC );
traffic.setResourceManager( getProcessingChain().getResourceManager() );
SourceConfigTuner source = new SourceConfigTuner();
long frequency = mChannelMap.getFrequency( channelNumber );
source.setFrequency( frequency );
traffic.setSourceConfiguration( source );
DecodeConfigMPT1327 decode = new DecodeConfigMPT1327();
traffic.setDecodeConfiguration( decode );
traffic.setAliasListName( aliasListName );
return traffic;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 dsp.filter;
import dsp.filter.Window.WindowType;
/**
* Implements the Goertzel Filter as described in
* http://en.wikipedia.org/wiki/Goertzel_algorithm
*
* Calculates the magnitude of a specific frequency component within a window of
* samples, using a Goertzel Filter (ie an optimized DFT).
*/
public class GoertzelFilter
{
private int mSampleRate;
private long mTargetFrequency;
private int mBlockSize;
private double[] mWindowCoefficients;
private double mCoefficient;
/**
* Constructs the Goertzel Filter to use for block processing of
* time-domain signal samples.
*
* @param sampleRate
* - sample rate (Hz)
* @param targetFrequency
* - target frequency (Hz)
* @param blockSize
* - number of samples per block of processing
* @param window
* - window to apply against the samples prior to calculating
* the magnitude
*/
public GoertzelFilter( int sampleRate,
long targetFrequency,
int blockSize,
WindowType window )
{
mSampleRate = sampleRate;
mTargetFrequency = targetFrequency;
mBlockSize = blockSize;
mWindowCoefficients = Window.getWindow( window, blockSize );
init();
}
/**
* Establish the pre-calculated values to use in the filter
*/
private void init()
{
double normalizedFrequency = (double) mTargetFrequency / mSampleRate;
mCoefficient = 2.0D * Math.cos( 2 * Math.PI * normalizedFrequency );
}
/**
* Returns the power (dB) of the target frequency within the block of
* samples as normalized against the bin(0) magnitude value
*
* @param samples
* - array of time-domain samples -- array size must be the same
* size as the windowSize parameter passed upon construction
*
* @return - power measurement in dB
* @throws IllegalArgumentException if the sample array size is not equal
* to the defined block size
*/
public int getPower( float[] samples ) throws IllegalArgumentException
{
// Verify size of samples array against block size
if ( samples.length != mBlockSize )
{
throw new IllegalArgumentException(
"Sample array size does not equal Block Size" );
}
// Apply the window against the samples
samples = Window.apply( mWindowCoefficients, samples );
// Process the samples
double s = 0.0D;
double s_prev = 0.0D;
double s_prev2 = 0.0D;
for ( int x = 0; x < samples.length; x++ )
{
s = samples[x] + ( mCoefficient * s_prev ) - s_prev2;
s_prev2 = s_prev;
s_prev = s;
}
//power = s_prev2 * s_prev2 + s_prev * s_prev - coeff * s_prev * s_prev2 ;
double magnitude = ( s_prev2 * s_prev2 ) + ( s_prev * s_prev) - (mCoefficient * s_prev * s_prev2);
int binZero = getBinZeroPower( samples );
int power = (int) (20 * Math.log10( magnitude / binZero ) );
return power;
}
/**
* Sums all of the sample values to derive the bin 0 power
*/
private int getBinZeroPower( float[] samples )
{
int retVal = 0;
for( int x = 0; x < samples.length; x++ )
{
retVal += samples[ x ];
}
return retVal;
}
/**
* @return the Sample Rate
*/
public int getSampleRate()
{
return mSampleRate;
}
/**
* @return the Target Frequency
*/
public long getTargetFrequency()
{
return mTargetFrequency;
}
/**
* @return the Block Size
*/
public int getBlockSize()
{
return mBlockSize;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 dsp.nbfm;
import sample.Listener;
import sample.complex.ComplexSample;
import sample.real.RealSampleBroadcaster;
import sample.real.RealSampleListener;
import dsp.filter.ComplexFIRFilter;
import dsp.filter.FilterFactory;
import dsp.filter.Window.WindowType;
public class NBFMDemodulator implements Listener<ComplexSample>
{
private RealSampleBroadcaster mBroadcaster = new RealSampleBroadcaster();
private ComplexFIRFilter mIQFilter;
private FMDiscriminator mDiscriminator;
/**
* Implements a quadrature narrow-band demodulator that produces float
* valued demodulated, audio filtered output samples.
*/
public NBFMDemodulator()
{
this( FilterFactory.getLowPass( 48000, 6250, 73, WindowType.HAMMING ),
1.0002, true );
}
public NBFMDemodulator( double[] iqFilter, double iqGain, boolean afc )
{
mIQFilter = new ComplexFIRFilter( iqFilter, iqGain );
mDiscriminator = new FMDiscriminator( 1 );
mIQFilter.setListener( mDiscriminator );
mDiscriminator.setListener( mBroadcaster );
}
public void dispose()
{
mDiscriminator.dispose();
mBroadcaster.dispose();
mIQFilter.dispose();
}
/**
* Receive method for complex samples that are fed into this class to be
* processed
*/
@Override
public void receive( ComplexSample sample )
{
mIQFilter.receive( sample );
}
/**
* Adds a listener to receive demodulated samples
*/
public void addListener( RealSampleListener listener )
{
mBroadcaster.addListener( listener );
}
/**
* Removes a listener from receiving demodulated samples
*/
public void removeListener( RealSampleListener listener )
{
mBroadcaster.removeListener( listener );
}
}
<file_sep>package bits;
public interface ISyncProcessor
{
public void checkSync( long value );
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.channel;
import java.awt.Color;
import java.awt.ComponentOrientation;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collections;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import record.RecordComponentEditor;
import source.SourceComponentEditor;
import alias.AliasList;
import com.jidesoft.swing.JideTabbedPane;
import controller.Editor;
import decode.AuxDecodeComponentEditor;
import decode.DecodeComponentEditor;
import eventlog.EventLogComponentEditor;
public class ChannelEditor extends Editor implements ActionListener
{
private final static Logger mLog = LoggerFactory.getLogger( ChannelEditor.class );
private static final long serialVersionUID = 1L;
private DefaultTreeModel mTreeModel;
private ChannelNode mChannelNode;
private DecodeComponentEditor mDecodeEditor;
private AuxDecodeComponentEditor mAuxDecodeEditor;
private EventLogComponentEditor mEventLogEditor;
private RecordComponentEditor mRecordEditor;
private SourceComponentEditor mSourceEditor;
private JTextField mChannelName;
private JCheckBox mChannelEnabled = new JCheckBox();
private JComboBox<AliasList> mComboAliasLists;
public ChannelEditor( ChannelNode channel )
{
super();
mChannelNode = channel;
initGUI();
}
private void initGUI()
{
setLayout( new MigLayout( "fill,wrap 2", "[right,grow][grow]", "[][][][][grow][]" ) );
add( new JLabel( "Channel Configuration" ), "span, align center" );
add( new JLabel( "Enabled:" ) );
mChannelEnabled.setSelected(
mChannelNode.getChannel().getEnabled() );
mChannelEnabled.setComponentOrientation( ComponentOrientation.RIGHT_TO_LEFT );
add( mChannelEnabled );
add( new JLabel( "Name:" ) );
mChannelName = new JTextField( mChannelNode.getChannel().getName() );
add( mChannelName, "growx,push" );
/**
* ComboBox: Alias Lists
*/
add( new JLabel( "Aliases:" ) );
mComboAliasLists = new JComboBox<AliasList>();
List<AliasList> lists = mChannelNode.getModel().getResourceManager()
.getPlaylistManager().getPlayist().getAliasDirectory().getAliasList();
Collections.sort( lists );
mComboAliasLists.setModel( new DefaultComboBoxModel<AliasList>(
lists.toArray( new AliasList[ lists.size() ] ) ) );
String aliasListName =
mChannelNode.getChannel().getAliasListName();
if( aliasListName != null )
{
AliasList selected = mChannelNode.getModel().getResourceManager()
.getPlaylistManager().getPlayist().getAliasDirectory()
.getAliasList( aliasListName );
mComboAliasLists.setSelectedItem( selected );
}
add( mComboAliasLists, "growx,push" );
JideTabbedPane tabs = new JideTabbedPane();
tabs.setFont( this.getFont() );
tabs.setForeground( Color.BLACK );
mSourceEditor = new SourceComponentEditor( mChannelNode );
tabs.addTab( "Source", mSourceEditor );
mDecodeEditor = new DecodeComponentEditor( mChannelNode );
tabs.addTab( "Decoder", mDecodeEditor );
mAuxDecodeEditor = new AuxDecodeComponentEditor( mChannelNode );
tabs.addTab( "Aux", mAuxDecodeEditor );
mEventLogEditor = new EventLogComponentEditor( mChannelNode );
tabs.addTab( "Event Log", mEventLogEditor );
mRecordEditor = new RecordComponentEditor( mChannelNode );
tabs.addTab( "Record", mRecordEditor );
add( tabs, "span,grow,push" );
JButton btnSave = new JButton( "Save" );
btnSave.addActionListener( ChannelEditor.this );
add( btnSave, "growx,push" );
JButton btnReset = new JButton( "Reset" );
btnReset.addActionListener( ChannelEditor.this );
add( btnReset, "growx,push" );
}
@Override
public void actionPerformed( ActionEvent e )
{
String command = e.getActionCommand();
if( command.contentEquals( "Save" ) )
{
save();
}
else if( command.contentEquals( "Reset" ) )
{
reset();
}
if( mTreeModel != null )
{
mTreeModel.nodeChanged( mChannelNode );
}
}
@Override
public void save()
{
try
{
/**
* Validate the source configuration against the other component
* configuration editors
*/
validate( mSourceEditor.getSourceEditor() );
boolean expanded = mChannelNode.getModel().getTree()
.isExpanded( new TreePath( mChannelNode ) );
mSourceEditor.save();
mDecodeEditor.save();
mAuxDecodeEditor.save();
mEventLogEditor.save();
mRecordEditor.save();
mChannelNode.getChannel().setName( mChannelName.getText(), false );
mChannelNode.getChannel().setEnabled( mChannelEnabled.isSelected(), false );
AliasList selected = mComboAliasLists.getItemAt(
mComboAliasLists.getSelectedIndex() );
if( selected != null )
{
mChannelNode.getChannel().setAliasListName( selected.getName(), false );
}
mChannelNode.save();
mChannelNode.show();
if( expanded )
{
mChannelNode.getModel().getTree().expandPath( new TreePath( mChannelNode ) );
}
}
catch ( ChannelValidationException validationException )
{
/* ChannelValidationException can be thrown by any of the component
* editors. Show the validation error text in a popup menu to the
* user */
JOptionPane.showMessageDialog( ChannelEditor.this,
validationException.getMessage(),
"Channel Configuration Error",
JOptionPane.ERROR_MESSAGE );
}
}
@Override
public void reset()
{
mChannelName.setText(
mChannelNode.getChannel().getName() );
mChannelName.requestFocus();
mChannelName.requestFocusInWindow();
mChannelEnabled.setSelected(
mChannelNode.getChannel().getEnabled() );
mChannelEnabled.requestFocus();
mChannelEnabled.requestFocusInWindow();
String aliasListName =
mChannelNode.getChannel().getAliasListName();
if( aliasListName != null )
{
AliasList selected = mChannelNode.getModel().getResourceManager()
.getPlaylistManager().getPlayist().getAliasDirectory()
.getAliasList( aliasListName );
mComboAliasLists.setSelectedItem( selected );
}
mSourceEditor.reset();
mDecodeEditor.reset();
mAuxDecodeEditor.reset();
mEventLogEditor.reset();
mRecordEditor.reset();
}
/**
* Validate the specified editor against each of the component editors
*/
@Override
public void validate( Editor editor ) throws ChannelValidationException
{
mSourceEditor.validate( editor );
mDecodeEditor.validate( editor );
mAuxDecodeEditor.validate( editor );
mEventLogEditor.validate( editor );
mRecordEditor.validate( editor );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 playlist;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
import alias.AliasDirectory;
import controller.channel.ChannelMapList;
import controller.system.SystemList;
@XmlSeeAlso( { AliasDirectory.class,
ChannelMapList.class,
SystemList.class } )
@XmlRootElement( name = "playlist" )
public class Playlist
{
private AliasDirectory mAliasDirectory = new AliasDirectory();
private ChannelMapList mChannelMapList = new ChannelMapList();
private SystemList mSystemList = new SystemList();
public Playlist()
{
}
@XmlElement( name = "alias_directory" )
public AliasDirectory getAliasDirectory()
{
mAliasDirectory.refresh();
return mAliasDirectory;
}
public void setAliasDirectory( AliasDirectory directory )
{
mAliasDirectory = directory;
}
@XmlElement( name = "system_list" )
public SystemList getSystemList()
{
return mSystemList;
}
public void setSystemList( SystemList list )
{
mSystemList = list;
}
@XmlElement( name = "channel_maps" )
public ChannelMapList getChannelMapList()
{
return mChannelMapList;
}
public void setChannelMapList( ChannelMapList list )
{
mChannelMapList = list;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.passport;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import map.Plottable;
import message.Message;
import message.MessageType;
import alias.Alias;
import alias.AliasList;
import bits.BinaryMessage;
import decode.DecoderType;
import edac.CRC;
import edac.CRCPassport;
public class PassportMessage extends Message
{
private static final String sUNKNOWN = "**UNKNOWN**";
private SimpleDateFormat mSDF = new SimpleDateFormat( "yyyyMMdd HHmmss" );
private DecimalFormat mDecimalFormatter = new DecimalFormat("0.00000");
@SuppressWarnings( "unused" )
private static final int[] sSYNC = { 8,7,6,5,4,3,2,1,0 };
private static final int[] sDCC = { 10,9 }; //Digital Color Code
private static final int[] sLCN = { 21,20,19,18,17,16,15,14,13,12,11 };
private static final int[] sSITE = { 28,27,26,25,24,23,22 };
private static final int[] sGROUP = { 44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29 };
private static final int[] sRADIO_ID = { 44,43,42,41,40,39,38,37,36,35,34,33,32,31,30,29,28,27,26,25,24,23,22 };
// private static final int[] sNEIGHBOR_OFFSET = { 32,31,30 };
private static final int[] sNEIGHBOR_BAND = { 36,35,34,33 };
private static final int[] sNEIGHBOR_REGISTRATION = { 29 };
private static final int[] sSITE_OFFSET = { 40,39,38 };
private static final int[] sSITE_BAND = { 44,43,42,41 };
private static final int[] sSITE_REGISTRATION = { 37 };
private static final int[] sTYPE = { 48,47,46,45 };
private static final int[] sFREE = { 59,58,57,56,55,54,53,52,51,50,49 };
private static final int[] sCHECKSUM = { 67,66,65,64,63,62,61,60 };
private BinaryMessage mMessage;
private CRC mCRC;
private AliasList mAliasList;
private PassportMessage mIdleMessage;
public PassportMessage( BinaryMessage message,
PassportMessage idleMessage,
AliasList list )
{
mMessage = CRCPassport.correct( message );
mIdleMessage = idleMessage;
mCRC = CRCPassport.check( mMessage );
mAliasList = list;
}
public PassportMessage( BinaryMessage message, AliasList list )
{
this( message, null, list );
}
public BinaryMessage getBitSetBuffer()
{
return mMessage;
}
public boolean isValid()
{
return mCRC != CRC.FAILED_CRC &&
mCRC != CRC.FAILED_PARITY &&
mCRC != CRC.UNKNOWN;
}
public CRC getCRC()
{
return mCRC;
}
public MessageType getMessageType()
{
MessageType retVal = MessageType.UN_KNWN;
int type = getMessageTypeNumber();
int lcn = getLCN();
switch( type )
{
case 0: //Group Call
retVal = MessageType.CA_STRT;
break;
case 1:
if( getFree() == 2042 )
{
retVal = MessageType.ID_TGAS;
}
else if( lcn < 1792 )
{
retVal = MessageType.CA_STRT;
}
else if( lcn == 1792 || lcn == 1793 )
{
retVal = MessageType.SY_IDLE;
}
else if( lcn == 2047 )
{
retVal = MessageType.CA_ENDD;
}
break;
case 2:
retVal = MessageType.CA_STRT;
break;
case 5:
retVal = MessageType.CA_PAGE;
break;
case 6:
retVal = MessageType.ID_RDIO;
break;
case 9:
retVal = MessageType.DA_STRT;
break;
case 11:
retVal = MessageType.RA_REGI;
break;
default:
break;
}
return retVal;
}
public int getDCC()
{
return getInt( sDCC );
}
public int getSite()
{
return getInt( sSITE );
}
public int getMessageTypeNumber()
{
return getInt( sTYPE );
}
public int getTalkgroupID()
{
if( getMessageType() == MessageType.SY_IDLE )
{
return 0;
}
else
{
return getInt( sGROUP );
}
}
public Alias getTalkgroupIDAlias()
{
int tg = getTalkgroupID();
if( mAliasList != null )
{
return mAliasList.getTalkgroupAlias( String.valueOf( tg ) );
}
return null;
}
public int getLCN()
{
return getInt( sLCN );
}
public long getLCNFrequency()
{
return getSiteFrequency( getLCN() );
}
public String getLCNFrequencyFormatted()
{
return mDecimalFormatter.format( (double)getLCNFrequency() / 1000000.0d );
}
public PassportBand getSiteBand()
{
return PassportBand.lookup( getInt( sSITE_BAND ) );
}
public PassportBand getNeighborBand()
{
return PassportBand.lookup( getInt( sNEIGHBOR_BAND ) );
}
public int getFree()
{
return getInt( sFREE );
}
public long getFreeFrequency()
{
return getSiteFrequency( getFree() );
}
public String getFreeFrequencyFormatted()
{
return mDecimalFormatter.format( (double)getFreeFrequency() / 1000000.0d );
}
public long getNeighborFrequency()
{
if( getMessageType() == MessageType.SY_IDLE )
{
PassportBand band = getNeighborBand();
return band.getFrequency( getFree() );
}
return 0;
}
/**
* Returns the radio id in hex format, or null if not the correct message
* type
*
* @return - radio id or null
*/
public String getMobileID()
{
if( getMessageType() == MessageType.ID_RDIO )
{
int radioId = getInt( sRADIO_ID );
return String.format("%06X", radioId & 0xFFFFFF );
}
else
{
return null;
}
}
public Alias getMobileIDAlias()
{
String min = getMobileID();
if( mAliasList != null && min != null )
{
return mAliasList.getMobileIDNumberAlias( min );
}
return null;
}
/**
* Appends spaces to the end of the stringbuilder to make it length long
*/
private void pad( StringBuilder sb, int length )
{
while( sb.length() < length )
{
sb.append( " " );
}
}
@Override
public String getBinaryMessage()
{
return mMessage.toString();
}
/**
* Returns a value formatted in hex notation.
*
* @param value - integer value
* @return - hex digits returned
*/
private static String getHex( int value, int digits )
{
return String.format( "%0" + digits + "X", value );
}
private int getInt( int[] bits )
{
int retVal = 0;
for( int x = 0; x < bits.length; x++ )
{
if( mMessage.get( bits[ x ] ) )
{
retVal += 1<<x;
}
}
return retVal;
}
/**
* Pads an integer value with additional zeroes to make it decimalPlaces long
*/
public String format( int number, int decimalPlaces )
{
StringBuilder sb = new StringBuilder();
int paddingRequired = decimalPlaces - ( String.valueOf( number ).length() );
for( int x = 0; x < paddingRequired; x++)
{
sb.append( "0" );
}
sb.append( number );
return sb.toString();
}
public String format( String val, int places )
{
StringBuilder sb = new StringBuilder();
sb.append( val );
while( sb.length() < places )
{
sb.append( " " );
}
return sb.toString();
}
@Override
public String getProtocol()
{
return DecoderType.PASSPORT.getDisplayString();
}
@Override
public String getEventType()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getFromID()
{
// TODO Auto-generated method stub
return null;
}
@Override
public Alias getFromIDAlias()
{
// TODO Auto-generated method stub
return null;
}
@Override
public String getToID()
{
return String.valueOf( getTalkgroupID() );
}
@Override
public Alias getToIDAlias()
{
return getTalkgroupIDAlias();
}
public long getSiteFrequency( int channel )
{
if( mIdleMessage != null && 0 < channel && channel < 1792 )
{
PassportBand band = mIdleMessage.getSiteBand();
if( band != PassportBand.BAND_UNKNOWN )
{
return band.getFrequency( channel );
}
}
return 0;
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
switch( getMessageType() )
{
case SY_IDLE:
sb.append( "IDLE SITE:" );
sb.append( format( getSite(), 3 ) );
sb.append( " NEIGHBOR:" );
sb.append( format( getFree(), 3 ) );
sb.append( "/" );
sb.append( getFreeFrequencyFormatted() );
break;
case CA_PAGE:
sb.append( "PAGING TG:" );
sb.append( format( getTalkgroupID(), 5 ) );
sb.append( "/" );
Alias pageAlias = getTalkgroupIDAlias();
if( pageAlias != null )
{
sb.append( pageAlias.getName() );
}
else
{
sb.append( sUNKNOWN );
}
sb.append( " SITE:" );
sb.append( format( getSite(), 3 ) );
sb.append( " CHAN:" );
sb.append( format( getLCN(), 4 ) );
sb.append( "/" );
sb.append( getLCNFrequencyFormatted() );
sb.append( " FREE:" );
sb.append( format( getFree(), 3 ) );
sb.append( "/" );
sb.append( getFreeFrequencyFormatted() );
break;
case CA_STRT:
sb.append( "CALL TG:" );
sb.append( format( getTalkgroupID(), 5 ) );
sb.append( "/" );
Alias startAlias = getTalkgroupIDAlias();
if( startAlias != null )
{
sb.append( startAlias.getName() );
}
else
{
sb.append( sUNKNOWN );
}
sb.append( " SITE:" );
sb.append( format( getSite(), 3 ) );
sb.append( " CHAN:" );
sb.append( format( getLCN(), 4 ) );
sb.append( "/" );
sb.append( getLCNFrequencyFormatted() );
sb.append( " FREE:" );
sb.append( format( getFree(), 3 ) );
sb.append( "/" );
sb.append( getFreeFrequencyFormatted() );
break;
case DA_STRT:
sb.append( "** DATA TG:" );
sb.append( format( getTalkgroupID(), 5 ) );
sb.append( "/" );
Alias dataStartAlias = getTalkgroupIDAlias();
if( dataStartAlias != null )
{
sb.append( dataStartAlias.getName() );
}
else
{
sb.append( sUNKNOWN );
}
sb.append( " SITE:" );
sb.append( format( getSite(), 3 ) );
sb.append( " CHAN:" );
sb.append( format( getLCN(), 4 ) );
sb.append( "/" );
sb.append( getLCNFrequencyFormatted() );
sb.append( " FREE:" );
sb.append( format( getFree(), 3 ) );
sb.append( "/" );
sb.append( getFreeFrequencyFormatted() );
break;
case CA_ENDD:
sb.append( "END TG:" );
sb.append( format( getTalkgroupID(), 5 ) );
sb.append( "/" );
Alias endAlias = getTalkgroupIDAlias();
if( endAlias != null )
{
sb.append( endAlias.getName() );
}
else
{
sb.append( sUNKNOWN );
}
sb.append( " SITE:" );
sb.append( format( getSite(), 3 ) );
sb.append( " CHAN:" );
sb.append( format( getLCN(), 4 ) );
sb.append( "/" );
sb.append( getLCNFrequencyFormatted() );
sb.append( " FREE:" );
sb.append( format( getFree(), 3 ) );
sb.append( "/" );
sb.append( getFreeFrequencyFormatted() );
break;
case ID_RDIO:
sb.append( "MOBILE ID MIN:" );
sb.append( getMobileID() );
sb.append( "/" );
Alias mobileIDAlias = getMobileIDAlias();
if( mobileIDAlias != null )
{
sb.append( mobileIDAlias.getName() );
}
else
{
sb.append( "UNKNOWN" );
}
sb.append( " FREE:" );
sb.append( format( getFree(), 3 ) );
sb.append( "/" );
sb.append( getFreeFrequencyFormatted() );
break;
case ID_TGAS:
sb.append( "ASSIGN TALKGROUP:" );
sb.append( format( getTalkgroupID(), 5 ) );
sb.append( "/" );
Alias assignAlias = getTalkgroupIDAlias();
if( assignAlias != null )
{
sb.append( assignAlias.getName() );
}
else
{
sb.append( sUNKNOWN );
}
sb.append( " SITE:" );
sb.append( format( getSite(), 3 ) );
sb.append( " CHAN:" );
sb.append( format( getLCN(), 4 ) );
sb.append( "/" );
sb.append( getLCNFrequencyFormatted() );
break;
case RA_REGI:
sb.append( "RADIO REGISTER TG: " );
sb.append( format( getTalkgroupID(), 5 ) );
sb.append( "/" );
Alias regAlias = getTalkgroupIDAlias();
if( regAlias != null )
{
sb.append( regAlias.getName() );
}
else
{
sb.append( sUNKNOWN );
}
break;
default:
sb.append( "UNKNOWN SITE:" );
sb.append( format( getSite(), 3 ) );
sb.append( " CHAN:" );
sb.append( format( getLCN(), 4 ) );
sb.append( "/" );
sb.append( getLCNFrequencyFormatted() );
sb.append( " FREE:" );
int free = getFree();
sb.append( format( free, 3 ) );
if( free > 0 && free < 896 )
{
sb.append( "/" );
sb.append( getFreeFrequencyFormatted() );
}
sb.append( " TYP:" );
sb.append( format( getMessageTypeNumber(), 2 ) );
sb.append( " TG:" );
sb.append( format( getTalkgroupID(), 5 ) );
break;
}
return sb.toString();
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( mSDF.format( mTimeReceived ) );
sb.append( " " );
sb.append( getMessage() );
pad( sb, 100 );
sb.append( mCRC.toString() );
pad( sb, 110 );
sb.append( " [" );
sb.append( mMessage );
sb.append( "]" );
return sb.toString();
}
@Override
public String getErrorStatus()
{
return mCRC.getDisplayText();
}
public boolean matches( PassportMessage otherMessage )
{
return this.getBitSetBuffer().equals( otherMessage.getBitSetBuffer() );
}
@Override
public Plottable getPlottable()
{
// TODO Auto-generated method stub
return null;
}
/**
* Provides a listing of aliases contained in the message.
*/
public List<Alias> getAliases()
{
List<Alias> aliases = new ArrayList<Alias>();
Alias talkgroup = getTalkgroupIDAlias();
if( talkgroup != null )
{
aliases.add( talkgroup );
}
Alias mid = getMobileIDAlias();
if( mid != null )
{
aliases.add( mid );
}
return aliases;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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.jdesktop.swingx.mapviewer;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.CacheRequest;
import java.net.CacheResponse;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ResponseCache;
import java.net.URI;
import java.net.URLConnection;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author joshy
*/
public class LocalResponseCache extends ResponseCache
{
private final static Logger mLog =
LoggerFactory.getLogger( LocalResponseCache.class );
private final File cacheDir;
private boolean checkForUpdates;
private String baseURL;
/**
* Private constructor to prevent instantiation.
* @param baseURL the URI that should be cached or <code>null</code> (for all URLs)
* @param cacheDir the cache directory
* @param checkForUpdates true if the URL is queried for newer versions of a file first
*/
private LocalResponseCache(String baseURL, File cacheDir, boolean checkForUpdates)
{
this.baseURL = baseURL;
this.cacheDir = cacheDir;
this.checkForUpdates = checkForUpdates;
if (!cacheDir.exists())
{
cacheDir.mkdirs();
}
}
/**
* Sets this cache as default response cache
* @param baseURL the URL, the caching should be restricted to or <code>null</code> for none
* @param cacheDir the cache directory
* @param checkForUpdates true if the URL is queried for newer versions of a file first
*/
public static void installResponseCache(String baseURL, File cacheDir, boolean checkForUpdates)
{
ResponseCache.setDefault(new LocalResponseCache(baseURL, cacheDir, checkForUpdates));
}
/**
* Returns the local File corresponding to the given remote URI.
* @param remoteUri the remote URI
* @return the corresponding local file
*/
public File getLocalFile(URI remoteUri)
{
if (baseURL != null)
{
String remote = remoteUri.toString();
if (!remote.startsWith(baseURL))
{
return null;
}
}
StringBuilder sb = new StringBuilder();
String host = remoteUri.getHost();
String query = remoteUri.getQuery();
String path = remoteUri.getPath();
String fragment = remoteUri.getFragment();
if (host != null)
{
sb.append(host);
}
if (path != null)
{
sb.append(path);
}
if (query != null)
{
sb.append('?');
sb.append(query);
}
if (fragment != null)
{
sb.append('#');
sb.append(fragment);
}
String name;
final int maxLen = 250;
if (sb.length() < maxLen)
{
name = sb.toString();
}
else
{
name = sb.substring(0, maxLen);
}
name = name.replace('?', '$');
name = name.replace('*', '$');
name = name.replace(':', '$');
name = name.replace('<', '$');
name = name.replace('>', '$');
name = name.replace('"', '$');
File f = new File(cacheDir, name);
return f;
}
/**
* @param remoteUri the remote URI
* @param localFile the corresponding local file
* @return true if the resource at the given remote URI is newer than the resource cached locally.
*/
private static boolean isUpdateAvailable(URI remoteUri, File localFile)
{
URLConnection conn;
try
{
conn = remoteUri.toURL().openConnection();
}
catch (MalformedURLException ex)
{
mLog.error("An exception occurred - ", ex );
return false;
}
catch (IOException ex)
{
mLog.error("An exception occurred - ", ex );
return false;
}
if (!(conn instanceof HttpURLConnection))
{
// don't bother with non-http connections
return false;
}
long localLastMod = localFile.lastModified();
long remoteLastMod = 0L;
HttpURLConnection httpconn = (HttpURLConnection) conn;
// disable caching so we don't get in feedback loop with ResponseCache
httpconn.setUseCaches(false);
try
{
httpconn.connect();
remoteLastMod = httpconn.getLastModified();
}
catch (IOException ex)
{
// log.error("An exception occurred", ex);();
return false;
}
finally
{
httpconn.disconnect();
}
return (remoteLastMod > localLastMod);
}
@Override
public CacheResponse get(URI uri, String rqstMethod, Map<String, List<String>> rqstHeaders) throws IOException
{
File localFile = getLocalFile(uri);
if (localFile == null)
{
// we don't want to cache this URL
return null;
}
if (!localFile.exists())
{
// the file isn't already in our cache, return null
return null;
}
if (checkForUpdates)
{
if (isUpdateAvailable(uri, localFile))
{
// there is an update available, so don't return cached version
return null;
}
}
return new LocalCacheResponse(localFile, rqstHeaders);
}
@Override
public CacheRequest put(URI uri, URLConnection conn) throws IOException
{
// only cache http(s) GET requests
if (!(conn instanceof HttpURLConnection) || !(((HttpURLConnection) conn).getRequestMethod().equals("GET")))
{
return null;
}
File localFile = getLocalFile(uri);
if (localFile == null)
{
// we don't want to cache this URL
return null;
}
new File(localFile.getParent()).mkdirs();
return new LocalCacheRequest(localFile);
}
private class LocalCacheResponse extends CacheResponse
{
private FileInputStream fis;
private final Map<String, List<String>> headers;
private LocalCacheResponse(File localFile, Map<String, List<String>> rqstHeaders)
{
try
{
this.fis = new FileInputStream(localFile);
}
catch (FileNotFoundException ex)
{
// should not happen, since we already checked for existence
mLog.error("An exception occurred - ", ex );
}
this.headers = rqstHeaders;
}
@Override
public Map<String, List<String>> getHeaders() throws IOException
{
return headers;
}
@Override
public InputStream getBody() throws IOException
{
return fis;
}
}
private class LocalCacheRequest extends CacheRequest
{
private final File localFile;
private FileOutputStream fos;
private LocalCacheRequest(File localFile)
{
this.localFile = localFile;
try
{
this.fos = new FileOutputStream(localFile);
}
catch (FileNotFoundException ex)
{
// should not happen if cache dir is valid
mLog.error("An exception occurred", ex );
}
}
@Override
public OutputStream getBody() throws IOException
{
return fos;
}
@Override
public void abort()
{
// abandon the cache attempt by closing the stream and deleting
// the local file
try
{
fos.close();
localFile.delete();
}
catch (IOException e)
{
// ignore
}
}
}
}
<file_sep>package source.tuner.frequency;
public class FrequencyChangeEvent
{
public enum Attribute
{
SAMPLE_RATE_ERROR,
BANDWIDTH,
FREQUENCY,
FREQUENCY_ERROR,
SAMPLE_RATE;
}
private Attribute mAttribute;
private Number mValue;
public FrequencyChangeEvent( Attribute attribute, Number value )
{
mAttribute = attribute;
mValue = value;
}
public Attribute getAttribute()
{
return mAttribute;
}
public Number getValue()
{
return mValue;
}
}
<file_sep>package filter;
import java.util.ArrayList;
import java.util.List;
public class FilterSet<T> implements IFilter<T>
{
protected List<IFilter<T>> mFilters = new ArrayList<IFilter<T>>();
protected boolean mEnabled = true;
protected String mName;
public FilterSet( String name )
{
mName = name;
}
public String getName()
{
return mName;
}
public void setName( String name )
{
mName = name;
}
public String toString()
{
return getName();
}
@Override
public boolean passes( T t )
{
if( mEnabled )
{
for( IFilter<T> filter: mFilters )
{
if( filter.canProcess( t ) )
{
return filter.passes( t );
}
}
}
return false;
}
@Override
public boolean canProcess( T t )
{
if( mEnabled )
{
for( IFilter<T> filter: mFilters )
{
if( filter.canProcess( t ) )
{
return true;
}
}
}
return false;
}
public List<IFilter<T>> getFilters()
{
return mFilters;
}
public void addFilters( List<IFilter<T>> filters )
{
mFilters.addAll( filters );
}
public void addFilter( IFilter<T> filter )
{
mFilters.add( filter );
}
public void removeFilter( IFilter<T> filter )
{
mFilters.remove( filter );
}
@Override
public boolean isEnabled()
{
return mEnabled;
}
@Override
public void setEnabled( boolean enabled )
{
mEnabled = enabled;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.config;
import javax.xml.bind.annotation.XmlAttribute;
import decode.DecoderType;
import decode.p25.P25Decoder;
import decode.p25.P25Decoder.Modulation;
public class DecodeConfigP25Phase1 extends DecodeConfiguration
{
private P25Decoder.Modulation mModulation = Modulation.C4FM;
public DecodeConfigP25Phase1()
{
super( DecoderType.P25_PHASE1 );
setAFC( false );
}
public boolean supportsAFC()
{
return false;
}
@XmlAttribute( name = "modulation" )
public P25Decoder.Modulation getModulation()
{
return mModulation;
}
public void setModulation( P25Decoder.Modulation modulation )
{
mModulation = modulation;
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.reference.LinkControlOpcode;
public class TelephoneInterconnectVoiceChannelUser extends TDULinkControlMessage
{
private final static Logger mLog =
LoggerFactory.getLogger( TelephoneInterconnectVoiceChannelUser.class );
/* Service Options */
public static final int EMERGENCY_FLAG = 92;
public static final int ENCRYPTED_CHANNEL_FLAG = 93;
public static final int DUPLEX_MODE = 94;
public static final int SESSION_MODE = 95;
public static final int[] CALL_TIMER = { 120,121,122,123,136,137,138,139,
140,141,142,143,144,145,146,147 };
public static final int[] ADDRESS = { 160,161,162,163,164,165,166,
167,168,169,170,171,184,185,186,187,188,189,190,191,192,193,194,195 };
public TelephoneInterconnectVoiceChannelUser( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.TELEPHONE_INTERCONNECT_VOICE_CHANNEL_USER.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
if( isEmergency() )
{
sb.append( " EMERGENCY" );
}
if( isEncryptedChannel() )
{
sb.append( " ENCRYPTED CHANNEL" );
}
sb.append( " TIMER:" + getCallTimer() + " SECS" );
sb.append( " ADDR:" + getAddress() );
return sb.toString();
}
public boolean isEmergency()
{
return mMessage.get( EMERGENCY_FLAG );
}
public boolean isEncryptedChannel()
{
return mMessage.get( ENCRYPTED_CHANNEL_FLAG );
}
public DuplexMode getDuplexMode()
{
return mMessage.get( DUPLEX_MODE ) ? DuplexMode.FULL : DuplexMode.HALF;
}
public SessionMode getSessionMode()
{
return mMessage.get( SESSION_MODE ) ?
SessionMode.CIRCUIT : SessionMode.PACKET;
}
public String getAddress()
{
return mMessage.getHex( ADDRESS, 6 );
}
/**
* Call timer in seconds
*/
public int getCallTimer()
{
int units = mMessage.getInt( CALL_TIMER );
return (int)( units / 10 );
}
}
<file_sep>package alias.action.clip;
import java.io.File;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;
import javax.xml.bind.annotation.XmlTransient;
import message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alias.Alias;
import alias.action.RecurringAction;
public class ClipAction extends RecurringAction
{
private final static Logger mLog = LoggerFactory.getLogger( ClipAction.class );
private String mFilePath;
@XmlTransient
private Clip mClip;
public ClipAction()
{
}
public String getPath()
{
return mFilePath;
}
public void setPath( String path )
{
mFilePath = path;
}
@Override
public void performAction( Alias alias, Message message )
{
try
{
play();
}
catch( Exception e )
{
mLog.debug( "Couldn't play audio clip", e );
}
}
public void play() throws Exception
{
try
{
if( mFilePath != null )
{
if( mClip == null )
{
mClip = AudioSystem.getClip();
AudioInputStream ais =
AudioSystem.getAudioInputStream( new File( mFilePath ) );
mClip.open( ais );
}
if( mClip.isRunning() )
{
mClip.stop();
}
mClip.setFramePosition( 0 );
mClip.start();
}
}
catch( Exception e )
{
mClip = null;
mLog.error( "Error playing sound clip [" + mFilePath + "] - " + e.getMessage() );
throw e;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner.fcd.proV1;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.text.DecimalFormat;
import java.util.ArrayList;
import javax.swing.ComboBoxModel;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JSpinner;
import javax.swing.JTextField;
import javax.swing.SpinnerModel;
import javax.swing.SpinnerNumberModel;
import javax.swing.SwingConstants;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import javax.usb.UsbClaimException;
import javax.usb.UsbException;
import net.miginfocom.swing.MigLayout;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.SourceException;
import source.tuner.TunerConfiguration;
import source.tuner.TunerType;
import source.tuner.fcd.proV1.FCD1TunerController.LNAEnhance;
import source.tuner.fcd.proV1.FCD1TunerController.LNAGain;
import source.tuner.fcd.proV1.FCD1TunerController.MixerGain;
import com.jidesoft.swing.JideTabbedPane;
import controller.ResourceManager;
public class FCD1TunerConfigurationPanel extends JPanel
{
private final static Logger mLog =
LoggerFactory.getLogger( FCD1TunerConfigurationPanel.class );
private static final long serialVersionUID = 1L;
private ResourceManager mResourceManager;
private FCD1TunerController mController;
private FCD1TunerConfiguration mSelectedConfig;
private JButton mNewConfiguration;
private JButton mDeleteConfiguration;
private JComboBox<FCD1TunerConfiguration> mComboConfigurations;
private JComboBox<LNAGain> mComboLNAGain;
private JComboBox<LNAEnhance> mComboLNAEnhance;
private JComboBox<MixerGain> mComboMixerGain;
private JTextField mName;
private JSpinner mCorrectionFrequency;
private CorrectionSpinner mCorrectionDCI;
private CorrectionSpinner mCorrectionDCQ;
private CorrectionSpinner mCorrectionGain;
private CorrectionSpinner mCorrectionPhase;
public FCD1TunerConfigurationPanel( ResourceManager resourceManager,
FCD1TunerController controller )
{
mResourceManager = resourceManager;
mController = controller;
mSelectedConfig = controller.getTunerConfiguration();
init();
}
private void init()
{
setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][][grow]" ) );
/**
* Tuner configurations combo
*/
mComboConfigurations = new JComboBox<FCD1TunerConfiguration>();
mComboConfigurations.setToolTipText( "Select a tuner configuration. "
+ "Create a separate tuner configuration for each of your "
+ "funcube dongles by using the NEW button and typing a "
+ "descriptive name" );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedItem( mSelectedConfig );
mComboConfigurations.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
FCD1TunerConfiguration selected =
(FCD1TunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
update( selected );
}
}
});
add( new JLabel( "Config:" ) );
add( mComboConfigurations, "growx,push" );
/**
* Tuner Configuration - Name
*/
mName = new JTextField( mSelectedConfig.getName() );
mName.setToolTipText( "Name for the selected tuner configuration" );
mName.addFocusListener( new FocusListener()
{
@Override
public void focusLost( FocusEvent e )
{
mSelectedConfig.setName( mName.getText() );
save();
}
@Override
public void focusGained( FocusEvent e ) {}
} );
add( new JLabel( "Name:" ) );
add( mName, "growx,push" );
JideTabbedPane tabs = new JideTabbedPane();
tabs.setFont( this.getFont() );
tabs.setForeground( Color.BLACK );
add( tabs, "span,grow,push" );
JPanel gainPanel = new JPanel();
gainPanel.setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][grow]" ) );
/**
* LNA Gain
*/
mComboLNAGain = new JComboBox<LNAGain>( LNAGain.values() );
mComboLNAGain.setToolTipText( "Adjust the low noise amplifier gain "
+ "setting. Default value is 20db" );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
mComboLNAGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
LNAGain gain = (LNAGain)mComboLNAGain.getSelectedItem();
mSelectedConfig.setLNAGain( gain );
try
{
mController.setLNAGain( gain );
}
catch ( UsbClaimException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - cannot claim FCD "
+ "Controller to apply LNA gain [" + gain.toString() + "]" );
mLog.error( "FuncubeDonglePro Controller - usb claim "
+ "exception while applying LNA gain value [" +
gain.toString() + "]", e1 );
}
catch ( UsbException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - FCD Controller "
+ "cannot apply LNA gain [" + gain.toString() + "]" );
mLog.error( "FuncubeDonglePro Controller - "
+ "exception while applying LNA gain value [" +
gain.toString() + "]", e1 );
}
save();
}
} );
gainPanel.add( new JLabel( "LNA:" ) );
gainPanel.add( mComboLNAGain, "growx,push" );
/**
* LNA Enhance
*/
mComboLNAEnhance = new JComboBox<LNAEnhance>( LNAEnhance.values() );
mComboLNAEnhance.setToolTipText( "Adjust the LNA enhance setting. "
+ "Default value is OFF" );
mComboLNAEnhance.setSelectedItem( mSelectedConfig.getLNAEnhance() );
mComboLNAEnhance.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
LNAEnhance enhance = (LNAEnhance)mComboLNAEnhance.getSelectedItem();
mSelectedConfig.setLNAEnhance( enhance );
try
{
mController.setLNAEnhance( enhance );
}
catch ( UsbClaimException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - cannot claim FCD "
+ "Controller to apply LNA enhance [" + enhance.toString() + "]" );
mLog.error( "FuncubeDonglePro Controller - usb claim "
+ "exception while applying LNA enhance value [" +
enhance.toString() + "]", e1 );
}
catch ( UsbException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - FCD Controller "
+ "cannot apply LNA enhance [" + enhance.toString() + "]" );
mLog.error( "FuncubeDonglePro Controller - "
+ "exception while applying LNA enhance value [" +
enhance.toString() + "]", e1 );
}
save();
}
} );
gainPanel.add( new JLabel( "LNA Enhance:" ) );
gainPanel.add( mComboLNAEnhance, "growx,push" );
/**
* Mixer Gain
*/
mComboMixerGain = new JComboBox<MixerGain>( MixerGain.values() );
mComboMixerGain.setToolTipText( "Adjust mixer gain setting" );
mComboMixerGain.setSelectedItem( mSelectedConfig.getMixerGain() );
mComboMixerGain.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
MixerGain gain = (MixerGain)mComboMixerGain.getSelectedItem();
mSelectedConfig.setMixerGain( gain );
try
{
mController.setMixerGain( gain );
}
catch ( UsbClaimException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - cannot claim FCD "
+ "Controller to apply Mixer gain [" + gain.toString() + "]" );
mLog.error( "FuncubeDonglePro Controller - usb claim "
+ "exception while applying Mixer gain value [" +
gain.toString() + "]", e1 );
}
catch ( UsbException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - FCD Controller "
+ "cannot apply Mixer gain [" + gain.toString() + "]" );
mLog.error( "FuncubeDonglePro Controller - "
+ "exception while applying Mixer gain value [" +
gain.toString() + "]", e1 );
}
save();
}
} );
gainPanel.add( new JLabel( "Mixer:" ) );
gainPanel.add( mComboMixerGain, "growx,push" );
tabs.add( "Gain", gainPanel );
JPanel correctionPanel = new JPanel();
correctionPanel.setLayout( new MigLayout( "fill,wrap 2", "[right][left]", "[][][][][][grow]" ) );
/**
* Frequency Correction
*/
SpinnerModel model =
new SpinnerNumberModel( 0.0, -1000.0, 1000.0, 0.1 ); //initial,min,max,step
mCorrectionFrequency = new JSpinner( model );
mCorrectionFrequency.setToolTipText( "Frequency Correction: adjust "
+ "value +/- to align the displayed frequency label with the "
+ "actual signals" );
JSpinner.NumberEditor editor =
(JSpinner.NumberEditor)mCorrectionFrequency.getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits( 1 );
editor.getTextField().setHorizontalAlignment( SwingConstants.CENTER );
mCorrectionFrequency.setValue( mSelectedConfig.getFrequencyCorrection() );
mCorrectionFrequency.addChangeListener( new ChangeListener()
{
@Override
public void stateChanged( ChangeEvent e )
{
double value = ((SpinnerNumberModel)mCorrectionFrequency
.getModel()).getNumber().doubleValue();
try
{
mSelectedConfig.setFrequencyCorrection( value );
mController.setFrequencyCorrection( value );
save();
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - couldn't "
+ "apply frequency correction value: " + value +
e1.getLocalizedMessage() );
mLog.error( "FuncubeDonglePro Controller - couldn't apply "
+ "frequency correction value: " + value, e1 );
}
}
} );
correctionPanel.add( new JLabel( "Frequency PPM:" ) );
correctionPanel.add( mCorrectionFrequency, "growx,push" );
/**
* Inphase DC Correction
*/
mCorrectionDCI = new CorrectionSpinner( Correction.DC_INPHASE,
mSelectedConfig.getInphaseDCCorrection(), 0.00001, 5 );
mCorrectionDCI.setToolTipText( "DC Bias Correction/Inphase "
+ "Component: valid values are -1.0 to 1.0 (default: 0.0)" );
correctionPanel.add( new JLabel( "DC Inphase:" ) );
correctionPanel.add( mCorrectionDCI, "growx,push" );
/**
* Quadrature DC Correction
*/
mCorrectionDCQ = new CorrectionSpinner( Correction.DC_QUADRATURE,
mSelectedConfig.getQuadratureDCCorrection(), 0.00001, 5 );
mCorrectionDCQ.setToolTipText( "DC Bias Correction/Quadrature "
+ "Component: valid values are -1.0 to 1.0 (default: 0.0)" );
correctionPanel.add( new JLabel( "DC Quadrature:" ) );
correctionPanel.add( mCorrectionDCQ, "growx,push" );
/**
* Gain Correction
*/
mCorrectionGain = new CorrectionSpinner( Correction.GAIN,
mSelectedConfig.getGainCorrection(), 0.00001, 5 );
mCorrectionGain.setToolTipText( "Gain Correction: valid values are "
+ "-1.0 to 1.0 (default: 0.0)" );
correctionPanel.add( new JLabel( "Gain:" ) );
correctionPanel.add( mCorrectionGain, "growx,push" );
/**
* Phase Correction
*/
mCorrectionPhase = new CorrectionSpinner( Correction.PHASE,
mSelectedConfig.getPhaseCorrection(), 0.00001, 5 );
mCorrectionPhase.setToolTipText( "Phase Correction: valid values are "
+ "-1.0 to 1.0 (default: 0.0)" );
correctionPanel.add( new JLabel( "Phase:" ) );
correctionPanel.add( mCorrectionPhase, "growx,push" );
tabs.add( "Correction", correctionPanel );
/**
* Create a new configuration
*/
mNewConfiguration = new JButton( "New" );
mNewConfiguration.setToolTipText( "Create a new tuner configuration "
+ "for each of your dongles to keep track of the specific "
+ "settings for each dongle" );
mNewConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
TunerConfiguration config =
mResourceManager.getSettingsManager()
.addNewTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO,
"New Configuration" );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedItem( config );
repaint();
}
} );
add( mNewConfiguration, "growx,push" );
/**
* Delete the currently selected configuration
*/
mDeleteConfiguration = new JButton( "Delete" );
mDeleteConfiguration.setToolTipText( "Deletes the currently selected "
+ "tuner configuration. Note: the DEFAULT tuner "
+ "configuration will be recreated if you delete it, "
+ "after you restart the application" );
mDeleteConfiguration.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
FCD1TunerConfiguration selected =
(FCD1TunerConfiguration)mComboConfigurations
.getItemAt( mComboConfigurations.getSelectedIndex() );
if( selected != null )
{
int n = JOptionPane.showConfirmDialog(
FCD1TunerConfigurationPanel.this,
"Are you sure you want to delete '"
+ selected.getName() + "'?",
"Are you sure?",
JOptionPane.YES_NO_OPTION );
if( n == JOptionPane.YES_OPTION )
{
mResourceManager.getSettingsManager()
.deleteTunerConfiguration( selected );
mComboConfigurations.setModel( getModel() );
mComboConfigurations.setSelectedIndex( 0 );
repaint();
}
}
}
} );
add( mDeleteConfiguration, "growx,push" );
}
private void update( FCD1TunerConfiguration config )
{
mSelectedConfig = config;
try
{
mController.apply( config );
mName.setText( config.getName() );
mComboLNAGain.setSelectedItem( mSelectedConfig.getLNAGain() );
mComboLNAEnhance.setSelectedItem( mSelectedConfig.getLNAEnhance() );
mComboMixerGain.setSelectedItem( mSelectedConfig.getMixerGain() );
mCorrectionFrequency.setValue( config.getFrequencyCorrection() );
mCorrectionDCI.setValue( config.getInphaseDCCorrection() );
mCorrectionDCQ.setValue( config.getQuadratureDCCorrection() );
mCorrectionGain.setValue( config.getGainCorrection() );
mCorrectionPhase.setValue( config.getPhaseCorrection() );
mResourceManager.getSettingsManager()
.setSelectedTunerConfiguration(
TunerType.FUNCUBE_DONGLE_PRO,
mController.getUSBAddress(), config );
}
catch ( SourceException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - couldn't "
+ "apply the tuner configuration settings - " +
e1.getLocalizedMessage() );
mLog.error( "FuncubeDonglePro Controller - couldn't apply "
+ "config [" + config.getName() + "]", e1 );
}
}
private ComboBoxModel<FCD1TunerConfiguration> getModel()
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.FUNCUBE_DONGLE_PRO );
DefaultComboBoxModel<FCD1TunerConfiguration> model =
new DefaultComboBoxModel<FCD1TunerConfiguration>();
for( TunerConfiguration config: configs )
{
model.addElement( (FCD1TunerConfiguration)config );
}
return model;
}
@SuppressWarnings( "unused" )
private FCD1TunerConfiguration getNamedConfiguration( String name )
{
ArrayList<TunerConfiguration> configs =
mResourceManager.getSettingsManager()
.getTunerConfigurations( TunerType.FUNCUBE_DONGLE_PRO );
for( TunerConfiguration config: configs )
{
if( config.getName().contentEquals( name ) )
{
return (FCD1TunerConfiguration)config;
}
}
return null;
}
private void save()
{
mResourceManager.getSettingsManager().save();
}
public enum Correction { GAIN, PHASE, DC_INPHASE, DC_QUADRATURE };
public class CorrectionSpinner extends JSpinner
{
private static final long serialVersionUID = 1L;
private static final double sMIN_VALUE = -1.0d;
private static final double sMAX_VALUE = 1.0d;
private Correction mCorrectionComponent;
public CorrectionSpinner( Correction component,
double initialValue,
double step,
int decimalPlaces )
{
mCorrectionComponent = component;
SpinnerModel model = new SpinnerNumberModel( initialValue,
sMIN_VALUE, sMAX_VALUE, step );
setModel( model );
JSpinner.NumberEditor editor = (JSpinner.NumberEditor)getEditor();
DecimalFormat format = editor.getFormat();
format.setMinimumFractionDigits( decimalPlaces );
editor.getTextField().setHorizontalAlignment( SwingConstants.CENTER );
addChangeListener( new ChangeListener()
{
@Override
public void stateChanged( ChangeEvent e )
{
double value =
((SpinnerNumberModel)getModel()).getNumber().doubleValue();
try
{
switch( mCorrectionComponent )
{
case DC_INPHASE:
mSelectedConfig.setInphaseDCCorrection( value );
mController.setDCCorrectionInPhase( value );
break;
case DC_QUADRATURE:
mSelectedConfig.setQuadratureDCCorrection( value );
mController.setDCCorrectionQuadrature( value );
break;
case GAIN:
mSelectedConfig.setGainCorrection( value );
mController.setGainCorrection( value );
break;
case PHASE:
mSelectedConfig.setPhaseCorrection( value );
mController.setPhaseCorrection( value );
break;
}
//Save the change(s) to the selected tuner config
save();
}
catch ( UsbClaimException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - cannot claim FCD "
+ "Controller to apply "
+ mCorrectionComponent.toString() +
" correction value [" + value + "]" );
mLog.error( "FuncubeDonglePro Controller - usb claim "
+ "exception while applying "
+ mCorrectionComponent.toString()
+ " correction value [" + value + "]", e1 );
}
catch ( UsbException e1 )
{
JOptionPane.showMessageDialog(
FCD1TunerConfigurationPanel.this,
"FCD Pro Tuner Controller - USB error from FCD "
+ "Controller while applying "
+ mCorrectionComponent.toString() +
" correction value [" + value + "]" );
mLog.error( "FuncubeDonglePro Controller - usb "
+ "exception while applying "
+ mCorrectionComponent.toString()
+ " correction value [" + value + "]", e1 );
}
}
} );
}
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class SecondaryControlChannelBroadcast extends TSBKMessage
implements IdentifierReceiver, Comparable<SecondaryControlChannelBroadcast>
{
private final static Logger mLog =
LoggerFactory.getLogger( SecondaryControlChannelBroadcast.class );
public static final int[] RFSS_ID = { 80,81,82,83,84,85,86,87 };
public static final int[] SITE_ID = { 88,89,90,91,92,93,94,95 };
public static final int[] IDENTIFIER_1 = { 96,97,98,99 };
public static final int[] CHANNEL_1 = { 100,101,102,103,104,105,106,107,108,
109,110,111 };
public static final int[] SYSTEM_SERVICE_CLASS_1 = { 112,113,114,115,116,
117,118,119 };
public static final int[] IDENTIFIER_2 = { 120,121,122,123 };
public static final int[] CHANNEL_2 = { 124,125,126,127,128,129,130,131,132,
133,134,135 };
public static final int[] SYSTEM_SERVICE_CLASS_2 = { 136,137,138,139,140,
141,142,143 };
private IBandIdentifier mIdentifierUpdate1;
private IBandIdentifier mIdentifierUpdate2;
public SecondaryControlChannelBroadcast( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.SECONDARY_CONTROL_CHANNEL_BROADCAST.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " SITE:" + getRFSS() + "-" + getSiteID() );
sb.append( " CHAN1:" + getIdentifier1() + "-" + getChannel1() );
sb.append( " DN1:" + getDownlinkFrequency1() );
sb.append( " UP1:" + getUplinkFrequency1() );
sb.append( " SVC1:" +
SystemService.toString( getSystemServiceClass1() ) );
if( hasChannel2() )
{
sb.append( " CHAN2:" + getIdentifier2() + "-" + getChannel2() );
sb.append( " DN2:" + getDownlinkFrequency2() );
sb.append( " UP2:" + getUplinkFrequency2() );
sb.append( " SVC2:" +
SystemService.toString( getSystemServiceClass2() ) );
}
return sb.toString();
}
public String getRFSS()
{
return mMessage.getHex( RFSS_ID, 2 );
}
public String getSiteID()
{
return mMessage.getHex( SITE_ID, 2 );
}
public int getIdentifier1()
{
return mMessage.getInt( IDENTIFIER_1 );
}
public int getChannel1()
{
return mMessage.getInt( CHANNEL_1 );
}
public int getSystemServiceClass1()
{
return mMessage.getInt( SYSTEM_SERVICE_CLASS_1 );
}
public int getIdentifier2()
{
return mMessage.getInt( IDENTIFIER_2 );
}
public int getChannel2()
{
return mMessage.getInt( CHANNEL_2 );
}
public int getSystemServiceClass2()
{
return mMessage.getInt( SYSTEM_SERVICE_CLASS_2 );
}
public boolean hasChannel2()
{
return getSystemServiceClass2() != 0;
}
public long getDownlinkFrequency1()
{
return calculateDownlink( mIdentifierUpdate1, getChannel1() );
}
public long getUplinkFrequency1()
{
return calculateUplink( mIdentifierUpdate1, getChannel1() );
}
public long getDownlinkFrequency2()
{
return calculateDownlink( mIdentifierUpdate2, getChannel2() );
}
public long getUplinkFrequency2()
{
return calculateUplink( mIdentifierUpdate2, getChannel2() );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
if( identifier == getIdentifier1() )
{
mIdentifierUpdate1 = message;
}
if( identifier == getIdentifier2() )
{
mIdentifierUpdate2 = message;
}
}
public int[] getIdentifiers()
{
int[] idens;
if( hasChannel2() )
{
idens = new int[ 2 ];
idens[ 0 ] = getIdentifier1();
idens[ 1 ] = getIdentifier2();
}
else
{
idens = new int[ 1 ];
idens[ 0 ] = getIdentifier1();
}
return idens;
}
@Override
public int compareTo( SecondaryControlChannelBroadcast other )
{
if( other.getSiteID().contentEquals( getSiteID() ) &&
other.getIdentifier1() == getIdentifier1() &&
other.getChannel1() == getChannel1() &&
other.getChannel2() == getChannel2() &&
other.getIdentifier2() == getIdentifier2() &&
other.getDownlinkFrequency1() == getDownlinkFrequency1() &&
other.getUplinkFrequency1() == getUplinkFrequency1() &&
other.getDownlinkFrequency2() == getDownlinkFrequency2() &&
other.getUplinkFrequency2() == getUplinkFrequency2() )
{
return 0;
}
else if( other.getIdentifier1() < getIdentifier1() )
{
return -1;
}
else
{
return 1;
}
}
}
<file_sep>package decode.p25.message.ldu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.ldu.LDU1Message;
import decode.p25.reference.LinkControlOpcode;
public class ChannelIdentifierUpdate extends LDU1Message
implements IBandIdentifier
{
private final static Logger mLog =
LoggerFactory.getLogger( ChannelIdentifierUpdate.class );
public static final int[] IDENTIFIER = { 364,365,366,367 };
public static final int[] BANDWIDTH = { 372,373,374,375,376,377,382,383,384 };
public static final int[] TRANSMIT_OFFSET = { 385,386,387,536,537,538,539,
540,541 };
public static final int[] CHANNEL_SPACING = { 546,547,548,549,550,551,556,
557,558,559 };
public static final int[] BASE_FREQUENCY = { 560,561,566,567,568,569,570,
571,720,721,722,723,724,725,730,731,732,733,734,735,740,741,742,743,744,
745,750,751,752,753,754,755 };
public ChannelIdentifierUpdate( LDU1Message message )
{
super( message );
}
@Override
public String getEventType()
{
return LinkControlOpcode.CHANNEL_IDENTIFIER_UPDATE.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " IDEN:" + getIdentifier() );
sb.append( " BASE:" + getBaseFrequency() );
sb.append( " BW:" + getBandwidth() );
sb.append( " SPACING:" + getChannelSpacing() );
sb.append( " OFFSET:" + getTransmitOffset() );
return sb.toString();
}
@Override
public int getIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
/**
* Channel bandwidth in hertz
*/
@Override
public int getBandwidth()
{
return mMessage.getInt( BANDWIDTH ) * 125;
}
@Override
public long getChannelSpacing()
{
return mMessage.getLong( CHANNEL_SPACING ) * 125l;
}
@Override
public long getBaseFrequency()
{
return mMessage.getLong( BASE_FREQUENCY ) * 5l;
}
@Override
public long getTransmitOffset()
{
return -1 * mMessage.getLong( TRANSMIT_OFFSET ) * 250000l;
}
}
<file_sep>package decode.p25.message;
/**
* Interface to allow messages to be augmented with IdentiferUpdateXXX type
* messages that provide the channel information necessary to calculate the
* uplink and downlink frequency for the channel.
*/
public interface IdentifierReceiver
{
public void setIdentifierMessage( int identifier, IBandIdentifier message );
public int[] getIdentifiers();
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.state;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import javax.swing.JTable;
import message.Message;
import message.MessageFilterFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import properties.SystemProperties;
import sample.Broadcaster;
import sample.Listener;
import alias.AliasList;
import audio.SquelchListener;
import audio.SquelchListener.SquelchState;
import audio.inverted.AudioType;
import audio.inverted.IAudioTypeListener;
import controller.activity.CallEvent;
import controller.activity.CallEvent.CallEventType;
import controller.activity.CallEventAliasCellRenderer;
import controller.activity.CallEventModel;
import controller.activity.MessageActivityModel;
import controller.channel.Channel.ChannelType;
import controller.channel.ProcessingChain;
import filter.FilterSet;
/**
* ChannelState provides a state machine for tracking a voice or data call
* through it's life cycle of CALL/DATA, FADE, and then END, and then back to
* an IDLE state. This class also provides squelch control for unsquelching
* sound to the speakers, and/or sound to an audio recorder
*
* State Descriptions:
* IDLE No voice or data call activity
* CALL/DATA A voice or data call has started, or is continuing
* CONTROL Control channel
* FADE The phase after a voice or data call when either an explicit
* call end has been received, or when no new signalling updates
* have been received, and the fade timer has expired. This phase
* allows for gui updates to signal to the user that the call is
* ended, while continuing to display the call details for the user
* END The phase after the voice or data call FADE, when the call is
* now over, and the gui should be reset to IDLE.
*
* When a call is started, invoke mTimerService.startFadeTimer() to start the
* call fade monitoring timer process that will automatically signal a call end
* once no more call signalling has been detected after the fade timeout has
* occurred, by invoking the fade() method.
*
* When a call ends, invoke the mTimerService.stopFadeTimer() and then invoke
* the mTimerService.startResetTimer(). Once the reset timeout occurs,
* the reset() method will be called, allowing the channel state to perform
* any reset actions, like clearing status and id labels on any view panels.
*
* AuxChannelState class allows for auxiliary decoders like Fleetsync to both
* have a state and leverage the state machine of the parent ChannelState.
* This allows a non-squelching channel state like for conventional fm to have
* an aux decoder like fleetsync, and allow the fleetsync auxchannelstate to
* leverage the call/end states of the parent conventional channelstate.
*
*/
public abstract class ChannelState implements Listener<Message>
{
private final static Logger mLog =
LoggerFactory.getLogger( ChannelState.class );
private State mState = State.IDLE;
private Object mCallFadeLock = new Object();
private Object mCallResetLock = new Object();
private long mFadeTimeout = -1;
private long mResetTimeout = -1;
protected long mCallFadeTimeout;
protected long mCallResetTimeout;
protected TimerService mTimerService = new TimerService();
protected ArrayList<SquelchListener> mSquelchListeners =
new ArrayList<SquelchListener>();
protected ArrayList<AuxChannelState> mAuxChannelStates =
new ArrayList<AuxChannelState>();
protected Broadcaster<ChangedAttribute> mChangeBroadcaster =
new Broadcaster<ChangedAttribute>();
protected IAudioTypeListener mAudioTypeListener;
protected AudioType mAudioType = AudioType.NORMAL;
protected CallEventModel mCallEventModel = new CallEventModel();
protected JTable mCallEventTable;
protected MessageActivityModel mMessageActivityModel;
protected JTable mMessageActivityTable;
protected ProcessingChain mProcessingChain;
protected AliasList mAliasList;
protected CallEvent mCurrentCallEvent;
public ChannelState( ProcessingChain processingChain, AliasList aliasList )
{
mProcessingChain = processingChain;
mAliasList = aliasList;
/* Register to receive decoded messages from the processing chain */
mProcessingChain.addListener( this );
SystemProperties props = SystemProperties.getInstance();
mCallFadeTimeout = props.get( "call.fade.timeout", 2000 );
mCallResetTimeout = props.get( "call.reset.timeout", 4000 );
/* Get a message filter for the primary decoder and aux decoders */
FilterSet messageFilter = MessageFilterFactory
.getMessageFilter( mProcessingChain.getChannel() );
mMessageActivityModel = new MessageActivityModel( messageFilter );
}
public void setCurrentCallEvent( CallEvent callEvent )
{
mCurrentCallEvent = callEvent;
}
public CallEvent getCurrentCallEvent()
{
return mCurrentCallEvent;
}
/**
* Allows setting the call event model to use for traffic channels, so that
* all traffic channels can share the parent control channel call event
* model.
* @param model
*/
public void setCallEventModel( CallEventModel model )
{
mCallEventModel = model;
}
public CallEventModel getCallEventModel()
{
return mCallEventModel;
}
public void receiveCallEvent( CallEvent event )
{
mCallEventModel.add( event );
}
public void dispose()
{
mTimerService.dispose();
mAuxChannelStates.clear();
mSquelchListeners.clear();
mChangeBroadcaster.dispose();
mChangeBroadcaster = null;
if( mProcessingChain.getChannel().getChannelType() == ChannelType.STANDARD )
{
mCallEventModel.dispose();
}
/* If we're a traffic channel, set the call event model to null so that
* we don't dispose the parent control channel's call event model */
else
{
mCallEventModel = null;
}
mMessageActivityModel.dispose();
mMessageActivityModel = null;
mAliasList = null;
mAudioTypeListener = null;
mCallEventModel = null;
mProcessingChain = null;
}
/**
* Channel Activity Summary - implemented by the sub-class.
*/
public abstract String getActivitySummary();
public AliasList getAliasList()
{
return mAliasList;
}
public boolean hasAliasList()
{
return mAliasList != null;
}
public void broadcastChange( final ChangedAttribute attribute )
{
mChangeBroadcaster.broadcast( attribute );
}
public void setCallFadeTimeout( long milliseconds )
{
mCallFadeTimeout = milliseconds;
}
public JTable getCallEventTable()
{
if( mCallEventTable == null )
{
mCallEventTable = new JTable( mCallEventModel );
mCallEventTable.setAutoCreateRowSorter( true );
mCallEventTable.setAutoResizeMode( JTable.AUTO_RESIZE_LAST_COLUMN );
CallEventAliasCellRenderer renderer =
new CallEventAliasCellRenderer( mProcessingChain
.getResourceManager().getSettingsManager() );
mCallEventTable.getColumnModel().getColumn( 3 )
.setCellRenderer( renderer );
mCallEventTable.getColumnModel().getColumn( 5 )
.setCellRenderer( renderer );
}
return mCallEventTable;
}
/**
* Returns the message activity model.
*/
public MessageActivityModel getMessageActivityModel()
{
return mMessageActivityModel;
}
public void addAuxChannelState( AuxChannelState state )
{
mAuxChannelStates.add( state );
}
public ArrayList<AuxChannelState> getAuxChannelStates()
{
return mAuxChannelStates;
}
public void receive( Message message )
{
if( mMessageActivityModel != null )
{
mMessageActivityModel.receive( message );
}
for( AuxChannelState state: mAuxChannelStates )
{
if( state != null )
{
state.receive( message );
}
}
}
public ProcessingChain getProcessingChain()
{
return mProcessingChain;
}
public State getState()
{
return mState;
}
public void setState( State state )
{
/* Let all CALL state changes go through in order to update the fade
* timer, otherwise, don't update the state if it hasn't changed */
if( mState != state || state == State.CALL || state == State.DATA || state == State.ENCRYPTED )
{
if( mState.canChangeTo( state ) )
{
mState = state;
switch( state )
{
case CONTROL:
setSquelchState( SquelchState.SQUELCH );
break;
case CALL:
setSquelchState( SquelchState.UNSQUELCH );
mTimerService.stopResetTimer();
mTimerService.startFadeTimer();
break;
case DATA:
mTimerService.stopResetTimer();
mTimerService.startFadeTimer();
break;
case ENCRYPTED:
setSquelchState( SquelchState.SQUELCH );
mTimerService.stopResetTimer();
mTimerService.startFadeTimer();
case NO_TUNER:
mTimerService.stopResetTimer();
if( getProcessingChain().getChannel()
.getChannelType() == ChannelType.TRAFFIC )
{
mTimerService.startFadeTimer();
}
break;
case FADE:
mTimerService.stopFadeTimer();
mTimerService.startResetTimer();
setSquelchState( SquelchState.SQUELCH );
if( mAudioTypeListener != null )
{
mAudioTypeListener.setAudioType( mAudioType );
}
break;
case END:
mTimerService.stopResetTimer();
mTimerService.stopFadeTimer();
setSquelchState( SquelchState.SQUELCH );
if( mAudioTypeListener != null )
{
mAudioTypeListener.setAudioType( mAudioType );
}
/* If this is a traffic channel, stop it */
if( mProcessingChain.getChannel()
.getChannelType() == ChannelType.TRAFFIC )
{
mProcessingChain.getChannel().setEnabled( false );
}
break;
case IDLE:
break;
default:
break;
}
broadcastChange( ChangedAttribute.CHANNEL_STATE );
}
else
{
mLog.error( "Channel State - can't change from [" +
mState.toString() + "] to [" + state.toString() + "]" );
}
}
}
/**
* End method to reset the channel state once a call has completely
* ended and now you want to return the channel state to idle
*/
protected void reset()
{
setState( State.END );
for( AuxChannelState state: mAuxChannelStates )
{
state.reset();
}
//Reset the state to idle
setState( State.IDLE );
}
/**
* Method to perform any call fade actions. On fade, you should change the
* channel state to fading, and construct a call-reset timer to execute a few
* seconds later. This allows the view to signal to the user that the call
* has faded/ended, and display faded information to the user, until the
* cleanup() task is run.
*/
protected void fade( CallEventType type )
{
for( AuxChannelState state: mAuxChannelStates )
{
state.fade();
}
setState( State.FADE );
}
public void setListener( IAudioTypeListener listener )
{
mAudioTypeListener = listener;
}
public void addListener( SquelchListener listener )
{
mSquelchListeners.add( listener );
}
public void removeListener( SquelchListener listener )
{
mSquelchListeners.remove( listener );
}
protected void setSquelchState( SquelchState state )
{
Iterator<SquelchListener> it = mSquelchListeners.iterator();
while( it.hasNext() )
{
it.next().setSquelch( state );
}
}
/**
* Timer service
*/
public class TimerService extends ScheduledThreadPoolExecutor
{
private long mTimerMonitorRevisitRate = 100; //100 milliseconds
private ScheduledFuture<?> mTimerMonitor;
public TimerService()
{
super( 1 );
}
public void dispose()
{
if( mTimerMonitor != null )
{
mTimerMonitor.cancel( true );
}
this.shutdownNow();
}
private void checkMonitor()
{
boolean createTimer = false;
synchronized( mCallFadeLock )
{
if( mFadeTimeout != -1 )
{
createTimer = true;
}
}
synchronized( mCallResetLock )
{
if( mResetTimeout != -1 )
{
createTimer = true;
}
}
if( createTimer )
{
//Check to see if the timer is already running, if not, start it
if( mTimerMonitor == null || mTimerMonitor.isDone() )
{
scheduleAtFixedRate( new StateTimeoutMonitor(),
mTimerMonitorRevisitRate,
mTimerMonitorRevisitRate,
TimeUnit.MILLISECONDS );
}
}
else
{
if( mTimerMonitor != null )
{
mTimerMonitor.cancel( true );
}
}
}
public void startFadeTimer()
{
synchronized( mCallFadeLock )
{
mFadeTimeout = System.currentTimeMillis() + mCallFadeTimeout;
}
checkMonitor();
}
public void resetFadeTimer()
{
startFadeTimer();
}
public void stopFadeTimer()
{
synchronized( mCallFadeLock )
{
mFadeTimeout = -1;
}
checkMonitor();
}
public void startResetTimer()
{
synchronized( mCallResetLock )
{
mResetTimeout = System.currentTimeMillis() + mCallResetTimeout;
}
checkMonitor();
}
public void stopResetTimer()
{
synchronized( mCallResetLock )
{
mResetTimeout = -1;
}
checkMonitor();
}
}
public class StateTimeoutMonitor implements Runnable
{
@Override
public void run()
{
long now = System.currentTimeMillis();
synchronized( mCallFadeLock )
{
if( mFadeTimeout != -1 && now >= mFadeTimeout )
{
mFadeTimeout = -1;
fade( CallEventType.CALL_TIMEOUT );
}
}
synchronized( mCallResetLock )
{
if( mResetTimeout != -1 && now >= mResetTimeout )
{
mResetTimeout = -1;
reset();
}
}
}
}
public enum State
{
IDLE( "IDLE" ) {
@Override
public boolean canChangeTo( State state )
{
return true;
}
},
CALL( "CALL" ) {
@Override
public boolean canChangeTo( State state )
{
return state == CALL ||
state == CONTROL ||
state == DATA ||
state == ENCRYPTED ||
state == FADE;
}
},
DATA( "DATA" ) {
@Override
public boolean canChangeTo( State state )
{
return state == CALL ||
state == CONTROL ||
state == DATA ||
state == State.ENCRYPTED ||
state == FADE;
}
},
ENCRYPTED( "ENCRYPTED" )
{
@Override
public boolean canChangeTo( State state )
{
return state == FADE;
}
},
CONTROL( "CONTROL" )
{
@Override
public boolean canChangeTo( State state )
{
return true;
}
},
FADE( "FADE" ) {
@Override
public boolean canChangeTo( State state )
{
return state != FADE; //All states except fade allowed
}
},
END( "END" ) {
@Override
public boolean canChangeTo( State state )
{
return state != FADE; //Fade is only disallowed state
}
},
NO_TUNER( "NO TUNER" ) {
@Override
public boolean canChangeTo( State state )
{
return state == FADE || state == END;
}
};
private String mDisplayValue;
private State( String displayValue )
{
mDisplayValue = displayValue;
}
public abstract boolean canChangeTo( State state );
public String getDisplayValue()
{
return mDisplayValue;
}
}
/**
* Registers a listener to receive channel state attribute changes
*/
public void addListener( Listener<ChangedAttribute> listener )
{
mChangeBroadcaster.addListener( listener );
}
/**
* Removes a listener from receiving channel state attribute changes
*/
public void removeListener( Listener<ChangedAttribute> listener )
{
mChangeBroadcaster.removeListener( listener );
}
public enum ChangedAttribute
{
AUDIO_TYPE,
CHANNEL_NUMBER,
CHANNEL_NAME,
CHANNEL_SITE_NUMBER,
CHANNEL_SITE_NUMBER_ALIAS,
CHANNEL_STATE,
DESCRIPTION,
FROM_TALKGROUP,
FROM_TALKGROUP_ALIAS,
FROM_TALKGROUP_TYPE,
MESSAGE,
MESSAGE_TYPE,
NAC,
SITE,
SITE_ALIAS,
SITE_NAME,
SOURCE,
SYSTEM,
SYSTEM_NAME,
SQUELCH,
TO_TALKGROUP,
TO_TALKGROUP_ALIAS,
TO_TALKGROUP_TYPE,
WACN;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.wave;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.ShortBuffer;
import java.util.Arrays;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.UnsupportedAudioFileException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Broadcaster;
import sample.Listener;
import sample.complex.ComplexSample;
public class ComplexWaveSource extends WaveSource
{
private final static Logger mLog =
LoggerFactory.getLogger( ComplexWaveSource.class );
private boolean mRunning = false;
private boolean mLoop = false;
private AudioInputStream mInputStream = null;
private int mBytesPerFrame = 0;
private long mFrequency = 0;
private byte[] mBuffer;
private int mBufferPointer = 0;
private int mBufferLength;
private ShortBuffer mBufferWrapper;
private static int BUFFER_SAMPLE_SIZE = 2000;
private Broadcaster<ComplexSample> mBroadcaster = new Broadcaster<ComplexSample>();
/**
* Single channel (mono) wave file playback source with optional looping
* for continous playback.
*
* Playback can be invoked manually with the next() and next(x) methods to
* get sample(s).
*
* Plaback can be run automatically by invoking the start() and stop()
* methods.
*
* Registered float sample listener(s) will receive any samples produced
* by the manual or automatic methods.
*
* @param loop - true for looping
*
* @throws FileNotFoundException if filename is not found
*/
public ComplexWaveSource( File file, boolean loop ) throws IOException
{
super( file, SampleType.COMPLEX );
mLoop = loop;
}
@Override
public int getSampleRate()
{
return (int)mInputStream.getFormat().getSampleRate();
}
/**
* Returns the frequency set for this file. Normally returns zero, but
* the value can be set with setFrequency() method.
*/
public long getFrequency()
{
return mFrequency;
}
/**
* Changes the value returned from getFrequency() for this source.
*/
public void setFrequency( long frequency )
{
mFrequency = frequency;
}
/**
* Closes the audio input stream
* @throws IOException
*/
public void close() throws IOException
{
if( mInputStream != null )
{
mInputStream.close();
}
mInputStream = null;
}
public void open() throws IOException
{
try
{
mInputStream = AudioSystem.getAudioInputStream( getFile() );
}
catch( UnsupportedAudioFileException e )
{
throw new IOException( "MonoWaveSource - unsupported audio file "
+ "exception - ", e );
}
mBytesPerFrame = mInputStream.getFormat().getFrameSize();
AudioFormat format = mInputStream.getFormat();
if( format.getChannels() != 2 || format.getSampleSizeInBits() != 16 )
{
throw new IOException( "Unsupported Wave Format - EXPECTED: 2 " +
"channels 16-bit samples FOUND: " +
mInputStream.getFormat().getChannels() + " channels " +
mInputStream.getFormat().getSampleSizeInBits() + "-bit samples" );
}
mBuffer = new byte[ mBytesPerFrame * BUFFER_SAMPLE_SIZE ];
readBuffer();
}
/**
* Reads a sample from the wave file and broadcasts the sample to all
* registered float listeners.
*
* @return - true if data was read or false if no more data. If loop is
* set to true, then this method will continue to produce samples as long
* as there are not IO exceptions.
*
* @throws IOException if unable to read data from the wave file
*/
/**
* Reads the next buffer from the wave file.
* @throws IOException
*/
public void readBuffer() throws IOException
{
if( mInputStream != null )
{
/* reset the buffer pointer and fill the buffer with zeros */
mBufferPointer = 0;
mBufferLength = 0;
Arrays.fill( mBuffer, (byte)0 );
while( mBufferLength == 0 )
{
boolean reset = false;
/* Fill the buffer with samples from the file */
mBufferLength = (int)( mInputStream.read( mBuffer ) /
mBytesPerFrame );
if( reset && mBufferLength == 0 )
{
return;
}
/* If we get a partial buffer, reset the file for the next read */
if( mBufferLength < mBuffer.length && mLoop )
{
close();
open();
reset = true;
}
}
if( mBufferLength > 0 )
{
mBufferWrapper = ByteBuffer.wrap( mBuffer ).order(
ByteOrder.LITTLE_ENDIAN ).asShortBuffer();
}
else
{
mBufferWrapper = null;
}
}
}
private boolean next( boolean broadcast ) throws IOException
{
boolean success = false;
if( mBufferPointer >= mBufferLength )
{
readBuffer();
}
if( mBufferLength != 0 &&
mBufferWrapper != null &&
mBufferWrapper.hasRemaining() )
{
short i = mBufferWrapper.get();
short q = mBufferWrapper.get();
mBufferPointer++;
incrementCurrentLocation( 1, false );
if( broadcast )
{
send( new ComplexSample( (float)i / 32767.0f, (float)q / 32767.0f ) );
}
success = true;
}
return success;
}
public boolean next() throws IOException
{
return next( true );
}
/**
* Reads the next (count) samples from the wave file and broadcasts them
* to the registered listeners.
* @param count - number of samples to broadcast
* @return - true if successful
* @throws IOException for any IO issues
*/
public boolean next( int count ) throws IOException
{
for( int x = 0; x < count; x++ )
{
next();
}
return true;
}
@Override
public void jumpTo( long index ) throws IOException
{
if( index < mCurrentPosition )
{
close();
open();
}
while( mCurrentPosition < index )
{
next( false );
}
incrementCurrentLocation( 0, true );
}
/**
* Broadcasts a sample to the registered listeners
*/
private void send( ComplexSample sample )
{
mBroadcaster.broadcast( sample );
}
/**
* Adds a new listener to receive samples as they are read from the wave file
*/
public void addListener( Listener<ComplexSample> listener )
{
mBroadcaster.addListener( listener );
}
public void removeListener( Listener<ComplexSample> listener )
{
mBroadcaster.removeListener( listener );
}
@Override
public void dispose()
{
/* Method not implemented */
}
}
<file_sep>package decode.p25.reference;
public enum DenyReason
{
RESERVED( 0x00 ),
REQUESTING_UNIT_NOT_VALID( 0x10 ),
REQUESTING_UNIT_NOT_AUTHORIZED_FOR_SERVICE( 0x11 ),
TARGET_UNIT_NOT_VALID( 0x20 ),
TARGET_UNIT_NOT_AUTHORIZED_FOR_SERVICE( 0x21 ),
TARGET_UNIT_REFUSED_CALL( 0x2F ),
TARGET_GROUP_NOT_VALID( 0x30 ),
TARGET_GROUP_NOT_AUTHORIZED_FOR_SERVICE( 0x31 ),
INVALID_DIALING( 0x40 ),
TELEPHONE_NUMBER_NOT_AUTHORIZED( 0x41 ),
PSTN_NOT_VALID( 0x42 ),
CALL_TIMEOUT( 0x50 ),
LANDLINE_TERMINATED_CALL( 0x51 ),
SUBSCRIBER_UNIT_TERMINATED_CALL( 0x52 ),
CALL_PREEMPTED( 0x5F ),
SITE_ACCESS_DENIAL( 0x60 ),
USER_OR_SYSTEM_DEFINED( 0x61 ),
CALL_OPTIONS_NOT_VALID_FOR_SERVICE( 0xF0 ),
PROTECTION_SERVICE_OPTION_NOT_VALID( 0xF1 ),
DUPLEX_SERVICE_OPTION_NOT_VALID( 0xF2 ),
CIRCUIT_OR_PACKET_MODE_OPTION_NOT_VALID( 0xF3 ),
SYSTEM_DOES_NOT_SUPPORT_SERVICE( 0xFF ),
UNKNOWN( -1 );
private int mCode;
private DenyReason( int code )
{
mCode = code;
}
public static DenyReason fromCode( int code )
{
if( code == 0x10 )
{
return DenyReason.REQUESTING_UNIT_NOT_VALID;
}
else if( code == 0x11 )
{
return REQUESTING_UNIT_NOT_AUTHORIZED_FOR_SERVICE;
}
else if( code == 0x20 )
{
return DenyReason.TARGET_UNIT_NOT_VALID;
}
else if( code == 0x21 )
{
return TARGET_UNIT_NOT_AUTHORIZED_FOR_SERVICE;
}
else if( code == 0x2F )
{
return DenyReason.TARGET_UNIT_REFUSED_CALL;
}
else if( code == 0x30 )
{
return TARGET_GROUP_NOT_VALID;
}
else if( code == 0x31 )
{
return DenyReason.TARGET_GROUP_NOT_AUTHORIZED_FOR_SERVICE;
}
else if( code == 0x40 )
{
return DenyReason.INVALID_DIALING;
}
else if( code == 0x41 )
{
return DenyReason.TELEPHONE_NUMBER_NOT_AUTHORIZED;
}
else if( code == 0x42 )
{
return DenyReason.PSTN_NOT_VALID;
}
else if( code == 0x50 )
{
return CALL_TIMEOUT;
}
else if( code == 0x51 )
{
return LANDLINE_TERMINATED_CALL;
}
else if( code == 0x52 )
{
return SUBSCRIBER_UNIT_TERMINATED_CALL;
}
else if( code == 0x5F )
{
return DenyReason.CALL_PREEMPTED;
}
else if( code == 0x60 )
{
return SITE_ACCESS_DENIAL;
}
else if( code == 0xF0 )
{
return CALL_OPTIONS_NOT_VALID_FOR_SERVICE;
}
else if( code == 0xF1 )
{
return PROTECTION_SERVICE_OPTION_NOT_VALID;
}
else if( code == 0xF2 )
{
return DenyReason.DUPLEX_SERVICE_OPTION_NOT_VALID;
}
else if( code == 0xF3 )
{
return CIRCUIT_OR_PACKET_MODE_OPTION_NOT_VALID;
}
else if( code <= 0x5E )
{
return DenyReason.RESERVED;
}
else if( code >= 0x61 )
{
return DenyReason.USER_OR_SYSTEM_DEFINED;
}
return UNKNOWN;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.ltrstandard;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import map.Plottable;
import message.MessageDirection;
import message.MessageType;
import alias.Alias;
import alias.AliasList;
import bits.BinaryMessage;
public class LTRStandardISWMessage extends LTRStandardMessage
{
private static final int sCALL_END = 31;
private static final int sIDLE = 255;
public LTRStandardISWMessage( BinaryMessage message, AliasList list )
{
super( message, MessageDirection.OSW, list );
mMessageType = getType();
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( mDatestampFormatter.format(
new Date( System.currentTimeMillis() ) ) );
sb.append( " LTR OSW [" );
sb.append( mCRC.getAbbreviation() );
sb.append( "] " );
sb.append( getMessage() );
pad( sb, 100 );
sb.append( mMessage.toString() );
return sb.toString();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
switch( mMessageType )
{
case SY_IDLE:
sb.append( "IDLE AREA:" );
sb.append( getArea() );
sb.append( " LCN:" );
sb.append( format( getChannel(), 2 ) );
sb.append( " HOME:" );
sb.append( format( getHomeRepeater(), 2 ) );
sb.append( " GRP:" );
sb.append( format( getGroup(), 3 ) );
sb.append( " FREE:" );
sb.append( format( getFree(), 2 ) );
break;
case CA_STRT:
sb.append( "CALL LCN:" );
sb.append( format( getChannel(), 2 ) );
sb.append( " TG [ " );
sb.append( getTalkgroupID() );
sb.append( "/" );
sb.append( getTalkgroupIDAlias() );
sb.append( " ] FREE:" );
sb.append( format( getFree(), 2 ) );
break;
case CA_ENDD:
sb.append( "END* AREA:" );
sb.append( getArea() );
sb.append( " LCN:" );
sb.append( format( getChannel(), 2 ) );
sb.append( " TG [" );
sb.append( getTalkgroupID() );
sb.append( "/" );
sb.append( getTalkgroupIDAlias() );
sb.append( "] FREE:" );
sb.append( format( getFree(), 2 ) );
break;
default:
sb.append( "UNKNOWN A:" );
sb.append( getArea() );
sb.append( " C:" );
sb.append( format( getChannel(), 2 ) );
sb.append( " H:" );
sb.append( format( getHomeRepeater(), 2 ) );
sb.append( " G:" );
sb.append( format( getGroup(), 3 ) );
sb.append( " F:" );
sb.append( format( getFree(), 2 ) );
}
return sb.toString();
}
public String getTalkgroupID()
{
return getTalkgroupID( true );
}
public String getTalkgroupID( boolean format )
{
StringBuilder sb = new StringBuilder();
sb.append( getArea() );
if( format )
{
sb.append( "-" );
}
sb.append( format( getHomeRepeater(), 2 ) );
if( format )
{
sb.append( "-" );
}
sb.append( format( getGroup(), 3 ) );
return sb.toString();
}
public Alias getTalkgroupIDAlias()
{
StringBuilder sb = new StringBuilder();
sb.append( getArea() );
sb.append( format( getHomeRepeater(), 2 ) );
sb.append( format( getGroup(), 3 ) );
return mAliasList.getTalkgroupAlias( sb.toString() );
}
public MessageType getType()
{
MessageType retVal = MessageType.UN_KNWN;
int group = getGroup();
if( group == sIDLE )
{
retVal = MessageType.SY_IDLE;
}
else
{
int channel = getChannel();
if( channel == sCALL_END )
{
retVal = MessageType.CA_ENDD;
}
else
{
retVal = MessageType.CA_STRT;
}
}
return retVal;
}
@Override
public String getFromID()
{
if( mMessageType == MessageType.CA_STRT ||
mMessageType == MessageType.CA_ENDD )
{
return getTalkgroupID();
}
else
{
return null;
}
}
@Override
public Alias getFromIDAlias()
{
if( mMessageType == MessageType.CA_STRT ||
mMessageType == MessageType.CA_ENDD )
{
return getTalkgroupIDAlias();
}
else
{
return null;
}
}
@Override
public Plottable getPlottable()
{
// TODO Auto-generated method stub
return null;
}
/**
* Provides a listing of aliases contained in the message.
*/
public List<Alias> getAliases()
{
List<Alias> aliases = new ArrayList<Alias>();
Alias from = getFromIDAlias();
if( from != null )
{
aliases.add( from );
}
Alias to = getToIDAlias();
if( to != null )
{
aliases.add( to );
}
return aliases;
}
}
<file_sep>package decode.p25.message.pdu.osp.data;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.pdu.UnitToUnitChannelGrantExtended;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class IndividualDataChannelGrantExtended
extends UnitToUnitChannelGrantExtended
implements IdentifierReceiver
{
public IndividualDataChannelGrantExtended( BinaryMessage message,
DataUnitID duid, AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.INDIVIDUAL_DATA_CHANNEL_GRANT.getDescription();
}
}
<file_sep>package decode.p25;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bits.BinaryMessage;
import dsp.symbol.Dibit;
public class Trellis_3_4_Rate
{
private final static Logger mLog =
LoggerFactory.getLogger( Trellis_3_4_Rate.class );
/* Hamming distance (bit match count) between constellation pairs */
private static final int[][] CONSTELLATION_METRICS =
{ { 4,3,3,2,3,2,2,1,3,2,2,1,2,1,1,0 },
{ 3,4,2,3,2,3,1,2,2,3,1,2,1,2,0,1 },
{ 3,2,4,3,2,1,3,2,2,1,3,2,1,0,2,1 },
{ 2,3,3,4,1,2,2,3,1,2,2,3,0,1,1,2 },
{ 3,2,2,1,4,3,3,2,2,1,1,0,3,2,2,1 },
{ 2,3,1,2,3,4,2,3,1,2,0,1,2,3,1,2 },
{ 2,1,3,2,3,2,4,3,1,0,2,1,2,1,3,2 },
{ 1,2,2,3,2,3,3,4,0,1,1,2,1,2,2,3 },
{ 3,2,2,1,2,1,1,0,4,3,3,2,3,2,2,1 },
{ 2,3,1,2,1,2,0,1,3,4,2,3,2,3,1,2 },
{ 2,1,3,2,1,0,2,1,3,2,4,3,2,1,3,2 },
{ 1,2,2,3,0,1,1,2,2,3,3,4,1,2,2,3 },
{ 2,1,1,0,3,2,2,1,3,2,2,1,4,3,3,2 },
{ 1,2,0,1,2,3,1,2,2,3,1,2,3,4,2,3 },
{ 1,0,2,1,2,1,3,2,2,1,3,2,3,2,4,3 },
{ 0,1,1,2,1,2,2,3,1,2,2,3,2,3,3,4 } };
/* Even valued state tribits can only produce even valued constellations
* and odd valued state tribits can only produce odd constellations. */
public static Con[] EVEN_CONSTELLATIONS = new Con[] { Con.C0,Con.C2,Con.C4,
Con.C6,Con.C8,Con.CA,Con.CC,Con.CE };
public static Con[] ODD_CONSTELLATIONS = new Con[] { Con.C1,Con.C3,Con.C5,
Con.C7,Con.C9,Con.CB,Con.CD,Con.CF };
/* Constellation and state tribit lookup map to find the input tribit */
public static HashMap<Con,Tribit[]> INPUT_FROM_CONSTELLATION_MAP;
private ArrayList<Con> mTransmittedConstellations = new ArrayList<Con>();
private ArrayList<Path> mSurvivorPaths = new ArrayList<Path>();
private ArrayList<Path> mNewPaths = new ArrayList<Path>();
private PathMetrics mPathMetrics = new PathMetrics();
/**
* Implements the Viterbi algorithm to decode 3/4 rate trellis encoded 196-bit
* packet data messages.
*/
public Trellis_3_4_Rate()
{
createConstellationToTribitMap();
}
/**
* Creates a lookup map for state to input tribit values for a given
* constellation. Input tribits are contained in the array using the state
* tribit's value as the lookup index. Null values indicate illegal state
* and input combinations for the specified constellation.
*/
private void createConstellationToTribitMap()
{
INPUT_FROM_CONSTELLATION_MAP = new HashMap<Con,Tribit[]>();
INPUT_FROM_CONSTELLATION_MAP.put( Con.CB, new Tribit[] { null, null, Tribit.T5, Tribit.T3, Tribit.T1, Tribit.T7, null, null } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.CC, new Tribit[] { Tribit.T3, Tribit.T1, null, null, null, null, Tribit.T7, Tribit.T5 } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C0, new Tribit[] { Tribit.T0, Tribit.T6, null, null, null, null, Tribit.T4, Tribit.T2 } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C7, new Tribit[] { null, null, Tribit.T6, Tribit.T4, Tribit.T2, Tribit.T0, null, null } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.CE, new Tribit[] { Tribit.T7, Tribit.T5, null, null, null, null, Tribit.T3, Tribit.T1 } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C9, new Tribit[] { null, null, Tribit.T1, Tribit.T7, Tribit.T5, Tribit.T3, null, null } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C5, new Tribit[] { null, null, Tribit.T2, Tribit.T0, Tribit.T6, Tribit.T4, null, null } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C2, new Tribit[] { Tribit.T4, Tribit.T2, null, null, null, null, Tribit.T0, Tribit.T6 } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.CA, new Tribit[] { Tribit.T5, Tribit.T3, null, null, null, null, Tribit.T1, Tribit.T7 } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.CD, new Tribit[] { null, null, Tribit.T3, Tribit.T1, Tribit.T7, Tribit.T5, null, null } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C1, new Tribit[] { null, null, Tribit.T0, Tribit.T6, Tribit.T4, Tribit.T2, null, null } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C6, new Tribit[] { Tribit.T6, Tribit.T4, null, null, null, null, Tribit.T2, Tribit.T0 } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.CF, new Tribit[] { null, null, Tribit.T7, Tribit.T5, Tribit.T3, Tribit.T1, null, null } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C8, new Tribit[] { Tribit.T1, Tribit.T7, null, null, null, null, Tribit.T5, Tribit.T3 } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C4, new Tribit[] { Tribit.T2, Tribit.T0, null, null, null, null, Tribit.T6, Tribit.T4 } );
INPUT_FROM_CONSTELLATION_MAP.put( Con.C3, new Tribit[] { null, null, Tribit.T4, Tribit.T2, Tribit.T0, Tribit.T6, null, null } );;
}
/**
* Member object cleanup prior to deleting
*/
public void dispose()
{
reset();
}
/**
* Decodes a 196-bit 3/4 rate convolutional encoded message located between
* start and end indexes and returns the decoded 144-bit message overlayed
* upon the original message with the remaining 52 bits cleared to zero.
*
* @return - original message with decoded message bits..
*/
public boolean decode( BinaryMessage message, int start, int end )
{
reset();
/* Load and decode each of the transmitted constellations */
for( int index = 0; index < 49; index++ )
{
Con c = getConstellation( message, start + index * 4 );
add( c );
}
/* The final decoded survivor path should be at path metrics tribit 0 */
Path path = mPathMetrics.getPath( Tribit.T0 );
/* We should have a path with 50 nodes, counting the starting 000 node
* and the flushing 000 node, otherwise there was an error */
if( path != null && path.getNodes().size() == 50 )
{
/* Clear the original message bits */
message.clear( start, end );
List<Node> nodes = path.getNodes();
/* Load each of the nodes' state tribit values into the original message */
for( int x = 1; x < 50; x++ )
{
message.load( start + ( ( x - 1 ) * 3 ), 3,
nodes.get( x ).getState().getValue() );
}
return true;
}
return false;
}
/**
* Resets the decoder before decoding a new data packet.
*/
private void reset()
{
mTransmittedConstellations.clear();
mNewPaths.clear();
mPathMetrics.reset();
mSurvivorPaths.clear();
/* Tribit 000 is the only legal start point */
mSurvivorPaths.add( new Path( new Node( 0, Tribit.T0, Con.C0 ) ) );
}
private void add( Con con )
{
mTransmittedConstellations.add( con );
/* Add in any newly created survivor paths */
mSurvivorPaths.addAll( mNewPaths );
mNewPaths.clear();
/* Set a culling threshold for any path metrics 3 below the best path */
int survivorThreshold = mPathMetrics.getSurvivorThreshold();
/* Reset path metrics */
mPathMetrics.reset();
/* Add constellation to each survivor path. If a survivor path metric
* falls below the culling threshold, remove it */
Iterator<Path> it = mSurvivorPaths.iterator();
Path path;
while( it.hasNext() )
{
path = it.next();
if( path.isDead() || path.getPathMetric() < survivorThreshold )
{
it.remove();
}
else
{
path.add( con );
}
}
}
private Con getConstellation( BinaryMessage message, int index )
{
int value = message.getInt( index, index + 3 );
return Con.fromTransmittedValue( value );
}
/**
* Path metrics maintains a map of the current best path metrics that end
* at each of the 8 valid tribit values. Each new path is evaluated against
* the current best path for retention (survivor) or disposal (dead). A
* best metric is maintained to evaluate the Walking Dead for disposal.
* Walking dead is a path lagging the best path metric by more than 3.
*/
public class PathMetrics
{
private HashMap<Tribit,Path> mMetrics = new HashMap<Tribit,Path>();
private int mBestMetric = 0;
public PathMetrics()
{
}
public int getSurvivorThreshold()
{
return mBestMetric - 3;
}
/**
* Removes all path metrics
*/
public void reset()
{
mMetrics.clear();
mBestMetric = 0;
}
public int getMetric( Tribit tribit )
{
if( mMetrics.containsKey( tribit ) )
{
return mMetrics.get( tribit ).getPathMetric();
}
return 0;
}
public Path getPath( Tribit tribit )
{
return mMetrics.get( tribit );
}
/**
* Evaluates the path's metric against the current best path metric for
* the final state tribit of the path. If the path's metric is higher
* than the current best path metric, the current path is marked for
* termination and the new path is promoted to best path. If the new
* path's metric is less than the best path metric, then the new path
* metric is marked for termination. If the metrics are equal, the new
* path is allowed to survive.
*
* @param path/metric to evaluate
*/
public void evalute( Path path )
{
Node lastNode = path.getLastNode();
Path bestPath = mMetrics.get( lastNode.getState() );
if( bestPath == null )
{
mMetrics.put( lastNode.getState(), path );
}
else
{
if( path.getPathMetric() < bestPath.getPathMetric() )
{
path.setSurvivor( false );
}
else if( path.getPathMetric() > bestPath.getPathMetric() )
{
mMetrics.put( lastNode.getState(), path );
bestPath.setSurvivor( false );
}
/* Equal metric paths are allowed to survive */
}
/* Capture the best path metric */
if( path.getPathMetric() > mBestMetric )
{
mBestMetric = path.getPathMetric();
}
}
}
/**
* Path is a sequence of nodes where the starting node always contains
* tribit 0 and constellation 0. Path maintains a running path metric
* derived from the sum of each of the node's branch metrics.
*/
public class Path
{
private boolean mSurvivor = true;
private int mPathMetric = 0;
private ArrayList<Node> mNodes = new ArrayList<Node>();
public Path( Node first )
{
mNodes.add( first );
mPathMetric = first.getBranchMetric();
mPathMetrics.evalute( this );
}
public Path( ArrayList<Node> nodes, int metric )
{
mNodes = nodes;
mPathMetric = metric;
}
public List<Node> getNodes()
{
return mNodes;
}
public int getBitErrorCount()
{
return ( getLastNode().getIndex() * 4 ) - mPathMetric;
}
public void setSurvivor( boolean survivor )
{
mSurvivor = survivor;
}
public boolean isSurvivor()
{
return mSurvivor;
}
public boolean isDead()
{
return !mSurvivor;
}
@SuppressWarnings( "unchecked" )
public Path copyOf()
{
return new Path( (ArrayList<Node>)mNodes.clone(), mPathMetric );
}
/**
* Adds the constellation and returns any new paths created as a result
* of the constellation being detected as an errant constellation.
*/
public void add( Con con )
{
Node current = getLastNode();
Tribit input = INPUT_FROM_CONSTELLATION_MAP
.get( con )[ current.getState().getValue() ];
/* A non-null input tribit from the lookup table is valid, otherwise
* create 8 alternate branches from the original path to explore
* where the error occurred. */
if( input != null )
{
add( new Node( mNodes.size(), input, con ) );
}
else
{
/* Create new paths for each of the valid constellations that
* correspond to the parity of the current state tribit */
Con[] constellations = current.getState().getType() ==
Type.EVEN ? EVEN_CONSTELLATIONS : ODD_CONSTELLATIONS;
for( int x = 0; x < 8; x++ )
{
/* Get the input tribit corresponding to the state tribit
* and constellation combination */
Tribit tribit = INPUT_FROM_CONSTELLATION_MAP
.get( constellations[ x ] )[ current.getState().getValue() ];
Node candidate = new Node( mNodes.size(), tribit, constellations[ x ] );
/* If the current path metric plus the candidate node's
* branch metric is equal or better than the current best
* metric for the given tribit, add it as a potential path,
* otherwise discard it */
if( this.getPathMetric() + candidate.getBranchMetric() >=
mPathMetrics.getMetric( tribit ) )
{
/* If this is the final constellation of the set, simply
* add it to the existing path ... */
if( x == 7 )
{
add( candidate );
}
/* ... otherwise create a copy of the current path */
else
{
Path path = this.copyOf();
path.add( candidate );
mNewPaths.add( path );
}
}
}
}
}
public void add( Node node )
{
mNodes.add( node );
mPathMetric += node.getBranchMetric();
mPathMetrics.evalute( this );
}
public int getPathMetric()
{
return mPathMetric;
}
public Node getLastNode()
{
return mNodes.get( mNodes.size() - 1 );
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( "PATH [" );
sb.append( mNodes.size() );
sb.append( "-" );
sb.append( mPathMetric );
sb.append( "] " );
for( Node node: mNodes )
{
sb.append( node.getState().name() );
sb.append( "/" );
sb.append( node.getConstellation().name() );
sb.append( " " );
}
sb.append( mSurvivor ? "SURVIVOR" : "DEAD" );
return sb.toString();
}
}
/**
* Trellis node containing the constellation used to produce the node and
* the input tribit for the constellation.
*/
public class Node
{
private int mIndex;
private int mBranchMetric;
private Tribit mTribit;
private Con mConstellation;
public Node( int index, Tribit tribit, Con constellation )
{
mIndex = index;
mTribit = tribit;
mConstellation = constellation;
if( mIndex > 0 )
{
Con transmitted = mTransmittedConstellations.get( index - 1 );
if( transmitted == null )
{
throw new IllegalArgumentException( "Cannot calculate "
+ "metric - transmitted constellation symbol is null" );
}
mBranchMetric = transmitted.getMetricTo( constellation );
}
}
public int getIndex()
{
return mIndex;
}
public Tribit getState()
{
return mTribit;
}
public Con getConstellation()
{
return mConstellation;
}
public int getBranchMetric()
{
return mBranchMetric;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( "Node " );
sb.append( mIndex );
sb.append( " Metric:" );
sb.append( mBranchMetric );
sb.append( " Con:" );
sb.append( mConstellation.name() );
sb.append( " State:" );
if( mTribit == null )
{
sb.append( "null" );
}
else
{
sb.append( mTribit.name() );
}
return sb.toString();
}
}
/**
* Constellation Type. Constellations are classified as even or add based
* on the the composition/comparison of the transmitted (representative)
* dibits:
*
* EVEN: - first dibit differs from second dibit in exactly one bit position
*
* ODD: - first dibit differs from second dibit in zero or two bit positions
* following three patterns:
* 1) repeat (10 10), mirror (01 10), or invert(00 11)
*/
public enum Type { EVEN, ODD };
/**
* Constellations, ordered by transmitted value. Transmitted value is the
* value of the dibit pair that represents the constellation when transmitted.
*/
public enum Con
{
CB( 0 ),
CC( 1 ),
C0( 2 ),
C7( 3 ),
CE( 4 ),
C9( 5 ),
C5( 6 ),
C2( 7 ),
CA( 8 ),
CD( 9 ),
C1( 10 ),
C6( 11 ),
CF( 12 ),
C8( 13 ),
C4( 14 ),
C3( 15 );
private int mTransmittedValue;
private Con( int transmittedValue )
{
mTransmittedValue = transmittedValue;
}
public int getTransmittedValue()
{
return mTransmittedValue;
}
public static Con fromTransmittedValue( int value )
{
if( 0 <= value && value <= 15 )
{
return values()[ value ];
}
return null;
}
public static Con fromTransmittedDibits( Dibit left, Dibit right )
{
return fromTransmittedValue( left.getHighValue() + right.getLowValue() );
}
/**
* Returns the metric or hamming distance to the other constellation
* using the values from the constellation costs table. A perfect match
* has a metric of 4 and a complete miss has a value of 0.
*/
public int getMetricTo( Con other )
{
return CONSTELLATION_METRICS[ getTransmittedValue() ][ other.getTransmittedValue() ];
}
}
/**
* Tribit. Used to define both the state and the input bit sequences that
* produce the transmitted constellation bit sequences. Each tribit is
* either even or odd valued producing a direct correlation to the types
* of valid constellations containing the tribit as the state tribit.
*/
public enum Tribit
{
T0( 0, Type.EVEN ),
T1( 1, Type.EVEN ),
T2( 2, Type.ODD ),
T3( 3, Type.ODD ),
T4( 4, Type.ODD ),
T5( 5, Type.ODD ),
T6( 6, Type.EVEN ),
T7( 7, Type.EVEN );
private int mValue;
private Type mType;
private Tribit( int value, Type type )
{
mValue = value;
mType = type;
}
public Type getType()
{
return mType;
}
public int getValue()
{
return mValue;
}
}
/**
* Test harness
*/
public static void main( String[] args )
{
String raw = "12:58:51.635 DEBUG dsp.fsk.P25MessageFramer - AFTER DEINTERLEAVE: 00100110000011001010010101111101000101010110100111111100101011000111011011000110000000000000000000000111111101011000001000001111000110000000000010101011110110010000000001011011000000010100011110110001000010100100011111000000000100000000000000000000010000000000001100000000000000011010101010101010101010100010001010000110010111111101101000001010000010100000101000001010000010100000101000001010000010100000101000001010000010100000101000001010000010100000010111001001000011100101011010101010101001010011";
BinaryMessage message = BinaryMessage.load( raw );
mLog.debug( "MSG: " + message.toString() );
Trellis_3_4_Rate t = new Trellis_3_4_Rate();
t.decode( message, 0, 196 );
mLog.debug( "DEC: " + message.toString() );
mLog.debug( "Finished!" );
}
}
<file_sep>package source;
import sample.Provider;
public abstract class FloatSource extends Source implements Provider<Float>
{
public FloatSource( String name )
{
super( name, SampleType.REAL );
}
}
<file_sep>package decode.p25;
import java.util.BitSet;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import bits.BinaryMessage;
/**
* Utility class to process interleave of P25 Voice and Data messages.
*/
public class P25Interleave
{
private final static Logger mLog =
LoggerFactory.getLogger( P25Interleave.class );
private static int[] DATA_INTERLEAVE = new int[] { 0,1,2,3,52,53,54,55,100,
101,102,103,148,149,150,151,4,5,6,7,56,57,58,59,104,105,106,107,152,153,
154,155,8,9,10,11,60,61,62,63,108,109,110,111,156,157,158,159,12,13,14,
15,64,65,66,67,112,113,114,115,160,161,162,163,16,17,18,19,68,69,70,71,
116,117,118,119,164,165,166,167,20,21,22,23,72,73,74,75,120,121,122,123,
168,169,170,171,24,25,26,27,76,77,78,79,124,125,126,127,172,173,174,175,
28,29,30,31,80,81,82,83,128,129,130,131,176,177,178,179,32,33,34,35,84,
85,86,87,132,133,134,135,180,181,182,183,36,37,38,39,88,89,90,91,136,
137,138,139,184,185,186,187,40,41,42,43,92,93,94,95,140,141,142,143,188,
189,190,191,44,45,46,47,96,97,98,99,144,145,146,147,192,193,194,195,48,
49,50,51 };
private static int[] DATA_DEINTERLEAVE = new int[] { 0,1,2,3,16,17,18,19,32,
33,34,35,48,49,50,51,64,65,66,67,80,81,82,83,96,97,98,99,112,113,114,115,
128,129,130,131,144,145,146,147,160,161,162,163,176,177,178,179,192,193,
194,195,4,5,6,7,20,21,22,23,36,37,38,39,52,53,54,55,68,69,70,71,84,85,
86,87,100,101,102,103,116,117,118,119,132,133,134,135,148,149,150,151,
164,165,166,167,180,181,182,183,8,9,10,11,24,25,26,27,40,41,42,43,56,57,
58,59,72,73,74,75,88,89,90,91,104,105,106,107,120,121,122,123,136,137,
138,139,152,153,154,155,168,169,170,171,184,185,186,187,12,13,14,15,28,
29,30,31,44,45,46,47,60,61,62,63,76,77,78,79,92,93,94,95,108,109,110,
111,124,125,126,127,140,141,142,143,156,157,158,159,172,173,174,175,188,
189,190,191 };
private static int[] VOICE_INTERLEAVE = new int[] { 0,24,48,72,96,120,25,
1,73,49,121,97,2,26,50,74,98,122,27,3,75,51,123,99,4,28,52,76,100,124,
29,5,77,53,125,101,6,30,54,78,102,126,31,7,79,55,127,103,8,32,56,80,104,
128,33,9,81,57,129,105,10,34,58,82,106,130,35,11,83,59,131,107,12,36,60,
84,108,132,37,13,85,61,133,109,14,38,62,86,110,134,39,87,15,63,135,111,
16,40,64,88,112,136,41,17,89,65,137,113,18,42,66,90,114,138,43,19,91,
67,139,115,20,44,68,92,116,140,45,21,93,69,141,117,22,46,70,94,119,142,
47,23,95,71,143,118 };
private static int[] VOICE_DEINTERLEAVE = new int[] { 0,7,12,19,24,31,36,43,
48,55,60,67,72,79,84,91,96,103,108,115,120,127,132,139,1,6,13,18,25,30,
37,42,49,54,61,66,73,78,85,90,97,102,109,114,121,126,133,138,2,9,14,21,
26,33,38,45,50,57,62,69,74,81,86,93,98,105,110,117,122,129,134,141,3,8,
15,20,27,32,39,44,51,56,63,68,75,80,87,92,99,104,111,116,123,128,135,
140,4,11,16,23,28,35,40,47,52,59,64,71,76,83,88,95,100,107,112,119,124,
131,136,143,5,10,17,22,29,34,41,46,53,58,65,70,77,82,89,94,101,106,113,
118,125,130,137,142 };
/**
* Deinterleaves the 196-bit block in message, identified by start and end
* bit positions. Note: end index (exclusive) should be one more than the
* last bit in the block.
*
* @param message - source message to deinterleave
* @param start - starting bit index for the block
* @param end - ending bit index for the block, plus 1
*/
public static BinaryMessage deinterleaveData( BinaryMessage message,
int start, int end )
{
return deinterleave( DATA_DEINTERLEAVE, message, start, end );
}
public static BinaryMessage deinterleaveVoice( BinaryMessage message,
int start, int end )
{
return deinterleave( VOICE_DEINTERLEAVE, message, start, end );
}
public static BinaryMessage deinterleave( int[] pattern, BinaryMessage message,
int start, int end )
{
BitSet original = message.get( start, end );
/* Clear block bits in source message */
message.clear( start, end );
/* Iterate only the set bits in the original message and apply
* the deinterleave -- we don't have to evaluate the 0 bits */
for (int i = original.nextSetBit( 0 );
i >= 0 && i < pattern.length;
i = original.nextSetBit( i + 1 ) )
{
message.set( start + pattern[ i ] );
}
return message;
}
/**
* Interleaves the 196-bit block in message, identified by start and end
* bit positions. Note: end index (exclusive) should be one more than the
* last bit in the block.
*
* @param message - source message to interleave
* @param start - starting bit index for the block
* @param end - ending bit index for the block, plus 1
*/
public static BinaryMessage interleaveData( BinaryMessage message,
int start, int end )
{
return interleave( DATA_INTERLEAVE, message, start, end );
}
public static BinaryMessage interleaveVoice( BinaryMessage message,
int start, int end )
{
return interleave( VOICE_INTERLEAVE, message, start, end );
}
public static BinaryMessage interleave( int[] pattern, BinaryMessage message,
int start, int end )
{
BitSet original = message.get( start, end );
/* Clear block bits in source message */
message.clear( start, end );
/* Iterate only the set bits in the original message and apply
* the deinterleave -- we don't have to evaluate the 0 bits */
for (int i = original.nextSetBit( 0 );
i >= 0 && i < pattern.length;
i = original.nextSetBit( i + 1 ) )
{
message.set( start + pattern[ i ] );
}
return message;
}
public static void main( String[] args )
{
int start = 0;
int end = 144;
int set = 50;
String interleaved = "000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000";
BinaryMessage b = BinaryMessage.load( interleaved );
b.set( set );
mLog.debug( "INT:" + b.toString() );
P25Interleave.deinterleaveVoice( b, start, end );
mLog.debug( "DEI:" + b.toString() );
mLog.debug( "In: " + set + " Out:" + b.nextSetBit( 0 ) );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.mpt1327;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.BitSet;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;
import map.Plottable;
import message.Message;
import alias.Alias;
import alias.AliasList;
import bits.BinaryMessage;
import edac.CRC;
import edac.CRCFleetsync;
public class MPT1327Message extends Message
{
private static String[] TELEX_LETTERS =
{ "A","B","C","D","E","F","G","H",
"I","J","K","L","M","N","O","P",
"Q","R","S","T","U","V","W","X",
"Y","Z","\n","\n","",""," "," " };
private static String[] TELEX_FIGURES =
{ "-","?",":","WRU","3","{6}","{7}","{8}",
"8","{BEEP}","(",")",".",",","9","0",
"1","4","'","5","7","=","2","/",
"6","+","\n","\n","",""," "," " };
private static String[] BCD = { "0","1","2","3","4","5","6",
"7","8","9"," ","*","#" };
private static int BLOCK_1_START = 20;
private static int BLOCK_2_START = 84;
private static int BLOCK_3_START = 148;
private static int BLOCK_4_START = 212;
private static int BLOCK_5_START = 276;
private static int BLOCK_6_START = 340;
private static int[] REVS = { 0,1,2,3 };
private static int[] SYNC = { 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 };
/* Block 1 Fields */
private static int[] B1_SYSDEF = { 21,22,23,24,25 };
private static int[] B1_PREFIX = { 21,22,23,24,25,26,27 };
private static int[] B1_TRAFFIC_CHANNEL = { 21,22,23,24,25,26,27,28,29,30 };
private static int[] B1_SYSTEM_ID = { 26,27,28,29,30,31,32,33,34,35,36,37,38,39,40 };
private static int[] B1_IDENT1 = { 28,29,30,31,32,33,34,35,36,37,38,39,40 };
private static int[] B1_CONTROL_CHANNEL = { 31,32,33,34,35,36,37,38,39,40 };
private static int[] B1_CHANNEL = { 35,36,37,38,39,40,41,42,43,44 };
private static int[] B1_MESSAGE_TYPE = { 41,42,43,44,45,46,47,48,49 };
private static int[] B1_GTC_CHAN = { 43,44,45,46,47,48,49,50,51,52 };
private static int[] B1_PREFIX2 = { 48,49,50,51,52,53,54 };
private static int[] B1_IDENT2 = { 50,51,52,53,54,55,56,57,58,59,60,61,62 };
private static int[] B1_IDENT2_GTC = { 53,54,55,56,57,58,59,60,61,62,63,64,65 };
private static int[] B1_IDENT2_HEAD = { 55,56,57,58,59,60,61,62,63,64,65,66,67 };
private static int[] B1_ADJSITE = { 49,50,51,52 };
private static int B1_PERIODIC_CALL_MAINT_MESSAGES = 50;
private static int[] B1_MAINT_MESSAGE_INTERVAL = { 51,52,53,54,55 };
private static int[] B1_WAIT_TIME = { 54,55,56 };
private static int B1_PRESSEL_ON_REQUIRED = 56;
private static int[] B1_ALOHA_RSVD = { 57,58 };
private static int[] B1_ALOHA_M = { 59,60,61,62,63 };
private static int[] B1_ALOHA_N = { 64,65,66,67 };
private static int B1_IDENT1_ID_VALUE = 57;
private static int[] B1_SLOTS = { 63,64 };
private static int[] B1_DESCRIPTOR = { 65,66,67 };
private static int[] B1_STATUS_MESSAGE = { 63,64,65,66,67 };
/* Block 2 or First Data Codeword Fields */
private static int[] B2_SYSTEM_ID = { 85,86,87,88,89,90,91,92,93,94,95,96,97,98,99 };
private static int[] B2_PREFIX = { 112,113,114,115,116,117,118 };
private static int[] B2_IDENT2 = { 119,120,121,122,123,124,125,126,127,128,129,130,131 };
private static int B2_SDM_SEGMENT_TRANSACTION_FLAG = 85;
private static int[] B2_SDM_GENERAL_FORMAT = { 86,87,88 };
private static int B2_SDM_INITIAL_SEGMENT_FLAG = 89;
private static int B2_SDM_STF0_START = 86;
private static int B2_SDM_STF0_END = 131;
private static int B2_SDM_STF1_START = 90;
private static int B2_SDM_STF1_END = 131;
/* Block 3 or Second Data Codeword Fields */
private static int B3_SDM_RETURN_SLOT_ACCESS = 149;
private static int B3_SDM_START = 150;
private static int B3_SDM_END = 195;
/* Block 4 or Third Data Codeword Fields */
private static int B4_SDM_SEGMENT_TRANSACTION_FLAG = 213;
private static int[] B4_SDM_NUMBER_SEGMENTS = { 214,215 };
private static int B4_SDM_CONTINUATION_SEGMENT_FLAG = 216;
private static int B4_SDM_RESERVED_FLAG = 217;
private static int B4_SDM_STF0_START = 214;
private static int B4_SDM_STF0_END = 259;
private static int B4_SDM_STF1_START = 218;
private static int B4_SDM_STF1_END = 259;
/* Block 5 or Fourth Data Codeword Fields */
private static int B5_SDM_RETURN_SLOT_ACCESS = 277;
private static int B5_SDM_START = 278;
private static int B5_SDM_END = 323;
private static DecimalFormat mFrequencyFormatter = new DecimalFormat("#.#####");
private static SimpleDateFormat mSDF = new SimpleDateFormat( "yyyyMMdd HHmmss" );
Calendar mCalendar = new GregorianCalendar();
private BinaryMessage mMessage;
private CRC[] mCRC = new CRC[ 5 ];
private AliasList mAliasList;
private MPTMessageType mMessageType;
public MPT1327Message( BinaryMessage message, AliasList list )
{
mMessage = message;
mAliasList = list;
checkParity( 0, BLOCK_1_START, BLOCK_2_START );
if( isValid() )
{
mMessageType = getMessageType();
switch( mMessageType )
{
/* 1 data block messages */
case AHYC:
case CLEAR:
case MAINT:
case MOVE:
break;
/* 2 data block messages */
case AHYQ:
case ALH:
case HEAD_PLUS1:
checkParity( 1, BLOCK_2_START, BLOCK_3_START );
break;
/* 3 data block messages */
case HEAD_PLUS2:
checkParity( 1, BLOCK_2_START, BLOCK_3_START );
checkParity( 2, BLOCK_3_START, BLOCK_4_START );
break;
/* 4 data block messages */
case ACKT:
case HEAD_PLUS3:
checkParity( 1, BLOCK_2_START, BLOCK_3_START );
checkParity( 2, BLOCK_3_START, BLOCK_4_START );
checkParity( 3, BLOCK_4_START, BLOCK_5_START );
break;
/* 5 data block messages */
case HEAD_PLUS4:
checkParity( 1, BLOCK_2_START, BLOCK_3_START );
checkParity( 2, BLOCK_3_START, BLOCK_4_START );
checkParity( 3, BLOCK_4_START, BLOCK_5_START );
checkParity( 4, BLOCK_5_START, BLOCK_6_START );
break;
case ACK:
case ACKB:
case ACKE:
case ACKI:
case ACKQ:
case ACKV:
case ACKX:
case AHOY:
case AHYP:
case AHYX:
case ALHD:
case ALHE:
case ALHF:
case ALHR:
case ALHS:
case ALHX:
case BCAST:
case GTC:
case MARK:
case DACKD:
case DACKZ:
case DACK_DAL:
case DACK_DALG:
case DACK_DALN:
case DACK_GO:
case DAHY:
case DAHYX:
case DAHYZ:
case DRQG:
case DRQX:
case DRQZ:
case GTT:
case RLA:
case SACK:
case SAMIS:
case SAMIU:
case SAMO:
case SITH:
case UNKN:
default:
break;
}
}
else
{
mMessageType = MPTMessageType.UNKN;
}
}
/**
* Performs CRC check against the specified section/block, using the
* message bits between start and end.
*/
private void checkParity( int section, int start, int end )
{
mCRC[ section ] = detectAndCorrect( start, end );
}
/**
* Performs CRC check and corrects some bit errors.
*/
//TODO: move this to the CRC class
private CRC detectAndCorrect( int start, int end )
{
BitSet original = mMessage.get( start, end );
CRC retVal = CRCFleetsync.check( original );
//Attempt to correct single-bit errors
if( retVal == CRC.FAILED_PARITY )
{
int[] errorBitPositions = CRCFleetsync.findBitErrors( original );
if( errorBitPositions != null )
{
for( int errorBitPosition: errorBitPositions )
{
mMessage.flip( start + errorBitPosition );
}
retVal = CRC.CORRECTED;
}
}
return retVal;
}
/**
* String representing results of the parity check
*
* [P] = passes parity check
* [f] = fails parity check
* [C] = corrected message
* [-] = message section not present
*/
public String getParity()
{
return "[" + CRC.format( mCRC ) + "]";
}
/**
* Indicates if Block 1 of the message has passed the CRC check.
*/
public boolean isValid()
{
return mCRC[ 0 ] == CRC.PASSED ||
mCRC[ 0 ] == CRC.CORRECTED;
}
public boolean isValidCall()
{
return getPrefix() != 0 &&
getIdent1() != 0 &&
getIdent2() != 0;
}
/**
* Constructs a decoded message string
*/
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( mSDF.format( new Date() ) );
sb.append( " MPT1327 " );
sb.append( getParity() );
sb.append( " " );
sb.append( getMessage() );
sb.append( getFiller( sb, 100 ) );
sb.append( " [" + mMessage.toString() + "]" );
return sb.toString();
}
/**
* Determines the message type from block 1
*/
public MPTMessageType getMessageType()
{
int value = mMessage.getInt( B1_MESSAGE_TYPE );
return MPTMessageType.fromNumber( value );
}
/**
* MPT1327 Site identifier
*/
public String getSiteID()
{
if( mMessageType == MPTMessageType.BCAST )
{
return String.valueOf( mMessage.getInt( B1_SYSTEM_ID ) );
}
else if( mMessageType == MPTMessageType.ALH )
{
return String.valueOf( mMessage.getInt( B2_SYSTEM_ID ) );
}
else
{
return null;
}
}
/**
* Indicates if this message has a system identifier
*/
public boolean hasSystemID()
{
return getSiteID() != null;
}
public SystemDefinition getSystemDefinition()
{
int sysdef = mMessage.getInt( B1_SYSDEF );
return SystemDefinition.fromNumber( sysdef );
}
public boolean getPeriodicMaintenanceMessagesRequired()
{
return mMessage.get( B1_PERIODIC_CALL_MAINT_MESSAGES );
}
public int getMaintenanceMessageInterval()
{
return mMessage.getInt( B1_MAINT_MESSAGE_INTERVAL );
}
public boolean getPresselOnRequired()
{
return mMessage.get( B1_PRESSEL_ON_REQUIRED );
}
public String getMaintMessageIDENT1Value()
{
return ( mMessage.get( B1_IDENT1_ID_VALUE ) ? "GROUP ADDRESS" :
"INDIVIDUAL ADDRESS" );
}
public int getChannel()
{
switch( mMessageType )
{
case CLEAR:
return mMessage.getInt( B1_TRAFFIC_CHANNEL );
case GTC:
return mMessage.getInt( B1_GTC_CHAN );
default:
return mMessage.getInt( B1_CHANNEL );
}
}
public int getReturnToChannel()
{
if( mMessageType == MPTMessageType.CLEAR )
{
return mMessage.getInt( B1_CONTROL_CHANNEL );
}
else
{
return 0;
}
}
public int getAdjacentSiteSerialNumber()
{
return mMessage.getInt( B1_ADJSITE );
}
public int getPrefix()
{
return mMessage.getInt( B1_PREFIX );
}
public int getBlock2Prefix()
{
return mMessage.getInt( B2_PREFIX );
}
public int getIdent1()
{
return mMessage.getInt( B1_IDENT1 );
}
public IdentType getIdent1Type()
{
return IdentType.fromIdent( getIdent1() );
}
public int getIdent2()
{
MPTMessageType type = getMessageType();
if( type == MPTMessageType.GTC )
{
return mMessage.getInt( B1_IDENT2_GTC );
}
else if( type == MPTMessageType.HEAD_PLUS1 ||
type == MPTMessageType.HEAD_PLUS2 ||
type == MPTMessageType.HEAD_PLUS3 ||
type == MPTMessageType.HEAD_PLUS4 )
{
return mMessage.getInt( B1_IDENT2_HEAD );
}
else
{
return mMessage.getInt( B1_IDENT2 );
}
}
public IdentType getIdent2Type()
{
return IdentType.fromIdent( getIdent2() );
}
public int getBlock2Ident2()
{
return mMessage.getInt( B2_IDENT2 );
}
public String getStatusMessage()
{
int status = mMessage.getInt( B1_STATUS_MESSAGE );
switch( status )
{
case 0:
return "STATUS: Request Speech Call";
case 31:
return "STATUS: Cancel Request Speech Call";
default:
return "STATUS: " + status;
}
}
/**
* Returns spaces to the fill the string builder to ensure length is >= index
*/
public String getFiller( StringBuilder sb, int index )
{
if( sb.length() < index )
{
return String.format( "%" + ( index - sb.length() ) + "s", " " );
}
else
{
return "";
}
}
/**
* Pads spaces onto the end of the value to make it 'places' long
*/
public String pad( String value, int places, String padCharacter )
{
StringBuilder sb = new StringBuilder();
sb.append( value );
while( sb.length() < places )
{
sb.append( padCharacter );
}
return sb.toString();
}
/**
* Pads an integer value with additional zeroes to make it decimalPlaces long
*/
public String format( int number, int decimalPlaces )
{
StringBuilder sb = new StringBuilder();
int paddingRequired = decimalPlaces - ( String.valueOf( number ).length() );
for( int x = 0; x < paddingRequired; x++)
{
sb.append( "0" );
}
sb.append( number );
return sb.toString();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( pad( mMessageType.toString(), 5, " " ) );
switch( mMessageType )
{
case ACK:
sb.append( " ACKNOWLEDGE " );
if( hasFromID() )
{
sb.append( getFromID() );
}
IdentType type = getIdent1Type();
switch( type )
{
case ALLI:
case IPFIXI:
case PABXI:
case PSTNGI:
case PSTNSI1:
case PSTNSI2:
case PSTNSI3:
case PSTNSI4:
case PSTNSI5:
case PSTNSI6:
case PSTNSI7:
case PSTNSI8:
case PSTNSI9:
case PSTNSI10:
case PSTNSI11:
case PSTNSI12:
case PSTNSI13:
case PSTNSI14:
case PSTNSI15:
case USER:
sb.append( type.getLabel() );
sb.append( " CALL REQUEST" );
break;
case TSCI:
sb.append( " RQQ or RQC TRANSACTION" );
break;
case DIVERTI:
sb.append( " CANCELLATION OF CALL DIVERSION REQUEST" );
break;
default:
sb.append( " " );
sb.append( type.getLabel() );
sb.append( " REQUEST" );
}
break;
case ACKI:
sb.append( " MESSAGE ACKNOWLEDGED - MORE TO FOLLOW" );
if( hasFromID() )
{
sb.append( " FROM:" );
sb.append( getFromID() );
}
if( hasToID() )
{
sb.append( " TO:" );
sb.append( getToID() );
}
break;
case ACKT:
sb.append( " SITE:" );
sb.append( getSiteID() );
sb.append( " LONG ACK MESSAGE" );
if( hasFromID() )
{
sb.append( " FROM:" );
sb.append( getFromID() );
}
if( hasToID() )
{
sb.append( " TO:" );
sb.append( getToID() );
}
sb.append( "**********************************" );
break;
case ACKQ:
sb.append( " SYSTEM:" );
sb.append( getSiteID() );
sb.append( " CALL QUEUED FROM:" );
if( hasFromID() )
{
sb.append( " FROM:" );
sb.append( getFromID() );
}
if( hasToID() )
{
sb.append( " TO:" );
sb.append( getToID() );
}
break;
case ACKX:
sb.append( " SYSTEM:" );
sb.append( getSiteID() );
sb.append( " MESSAGE REJECTED FROM:" );
if( hasFromID() )
{
sb.append( " FROM:" );
sb.append( getFromID() );
}
if( hasToID() )
{
sb.append( " TO:" );
sb.append( getToID() );
}
break;
case AHYC:
sb.append( " FM:" );
sb.append( getFromID() );
sb.append( " TO:" );
sb.append( getToID() );
sb.append( " " );
sb.append( getRequestString() );
break;
case AHYQ:
/* Status Message */
sb.append( " STATUS MESSAGE" );
if( hasFromID() )
{
sb.append( " FROM:" );
sb.append( getFromID() );
}
if( hasToID() )
{
sb.append( " TO:" );
sb.append( getToID() );
}
sb.append( " " );
sb.append( getStatusMessage() );
break;
case ALH:
case ALHD:
case ALHS:
case ALHE:
case ALHR:
case ALHX:
case ALHF:
sb.append( " SYSTEM:" );
sb.append( getSiteID() );
if( hasToID() )
{
sb.append( " ID:" );
sb.append( getToID() );
}
sb.append( " WAIT:" );
sb.append( getWaitTime() );
sb.append( " RSVD:" );
sb.append( getAlohaReserved() );
sb.append( " M:" );
sb.append( getAlohaM() );
sb.append( " N:" );
sb.append( getAlohaN() );
break;
case BCAST:
sb.append( " SYSTEM:" );
sb.append( getSiteID() );
SystemDefinition sysdef = getSystemDefinition();
sb.append( " " );
sb.append( sysdef.getLabel() );
switch( sysdef )
{
case ANNOUNCE_CONTROL_CHANNEL:
case WITHDRAW_CONTROL_CHANNEL:
sb.append( " CHAN:" );
sb.append( getChannel() );
break;
case BROADCAST_ADJACENT_SITE_CONTROL_CHANNEL_NUMBER:
sb.append( " CHAN:" );
sb.append( getChannel() );
sb.append( " SER:" );
sb.append( getAdjacentSiteSerialNumber() );
//debug
sb.append( " *************************" );
break;
case SPECIFY_CALL_MAINTENANCE_PARAMETERS:
sb.append( " PERIODIC MAINT MSG REQD:" );
sb.append( getPeriodicMaintenanceMessagesRequired() );
sb.append( " INTERVAL:" );
sb.append( getMaintenanceMessageInterval() );
sb.append( "(sec) PRESSEL ON REQD:" );
sb.append( getPresselOnRequired() );
sb.append( " IDENT1 VALUE:" );
sb.append( getMaintMessageIDENT1Value() );
}
break;
case CLEAR:
sb.append( " TRAFFIC CHANNEL:" );
sb.append( getChannel() );
sb.append( " RETURN TO CONTROL CHANNEL:" );
sb.append( getReturnToChannel() );
break;
case GTC:
if( hasFromID() )
{
sb.append( " FROM:" );
sb.append( getFromID() );
}
if( hasToID() )
{
sb.append( " TO:" );
sb.append( getToID() );
}
sb.append( " CHAN:" );
sb.append( getChannel() );
break;
case MAINT:
if( hasToID() )
{
sb.append( " ID:" );
sb.append( getToID() );
}
break;
case HEAD_PLUS1:
case HEAD_PLUS2:
case HEAD_PLUS3:
case HEAD_PLUS4:
sb.append( " " );
sb.append( getSDM() );
break;
}
return sb.toString();
}
@Override
public String getBinaryMessage()
{
return mMessage.toString();
}
@Override
public String getProtocol()
{
return "MPT-1327";
}
@Override
public String getEventType()
{
// TODO Auto-generated method stub
return null;
}
/**
* Translates the AHYC request from the values in ident1 and ident2
*/
public String getRequestString()
{
StringBuilder sb = new StringBuilder();
IdentType type2 = getIdent2Type();
if( type2 == IdentType.USER )
{
IdentType type1 = getIdent1Type();
Slots slots = getSlots();
switch( type1 )
{
case DIVERTI:
sb.append( "SEND BLOCKED ADDRESS FOR THIRD-PARTY CALL DIVERSION USING " );
sb.append( slots.getLabel() );
break;
case IPFIXI:
sb.append( "SEND INTER-PREFIX CALL EXTENDED ADDRESSING INFORMATION USING " );
sb.append( slots.getLabel() );
break;
case PABXI:
sb.append( "SEND PABX EXTENSION USING" );
sb.append( slots.getLabel() );
break;
case PSTNGI:
if( slots == Slots.SLOTS_1 )
{
sb.append( "SEND UP TO 9 PSTN DIALED DIGITS" );
}
else if( slots == Slots.SLOTS_2 )
{
sb.append( "SEND 10 TO 31 PSTN DIALED DIGITS" );
}
else
{
sb.append( "SEND PSTN DIALED DIGITS USING " );
sb.append( slots.getLabel() );
}
break;
case SDMI:
sb.append( "SEND SHORT DATA MESSAGE USING " );
sb.append( slots.getLabel() );
break;
}
}
else
{
/* MODE 2 */
sb.append( "SEND " );
sb.append( getDescriptor().getMode2Label() );
}
return sb.toString();
}
/**
* Constructs a FROM identifier from the Prefix2 and Ident2 values
*/
@Override
public String getFromID()
{
StringBuilder sb = new StringBuilder();
int ident2 = getIdent2();
IdentType type = IdentType.fromIdent( ident2 );
/* Inter-Prefix - the from and to idents are different prefixes */
if( type == IdentType.IPFIXI )
{
sb.append( format( getBlock2Prefix(), 3 ) );
sb.append( "-" );
sb.append( format( getBlock2Ident2(), 4) );
}
else
{
sb.append( format( getPrefix(), 3 ) );
sb.append( "-" );
sb.append( format( ident2, 4) );
}
return sb.toString();
}
public boolean hasFromID()
{
return getFromID() != null && !getFromID().isEmpty();
}
@Override
public Alias getFromIDAlias()
{
if( mAliasList != null && hasFromID() )
{
return mAliasList.getMPT1327Alias( getFromID() );
}
return null;
}
/**
* Constructs a TO identifier from the Prefix1 and Ident1 fields
*/
@Override
public String getToID()
{
StringBuilder sb = new StringBuilder();
int prefix = getPrefix();
int ident = getIdent1();
switch( IdentType.fromIdent( ident ) )
{
case IPFIXI:
sb.append( "INTER-PREFIX" );
break;
case ALLI:
sb.append( "ALL RADIOS" );
break;
case PABXI:
sb.append( "PABX EXT" );
break;
case PSTNSI1:
case PSTNSI2:
case PSTNSI3:
case PSTNSI4:
case PSTNSI5:
case PSTNSI6:
case PSTNSI7:
case PSTNSI8:
case PSTNSI9:
case PSTNSI10:
case PSTNSI11:
case PSTNSI12:
case PSTNSI13:
case PSTNSI14:
case PSTNSI15:
sb.append( "PRE-DEFINED PSTN" );
break;
case PSTNGI:
sb.append( "PSTN GATEWAY" );
break;
case TSCI:
sb.append( "SYSTEM CONTROLLER" );
break;
case DIVERTI:
sb.append( "CALL DIVERT" );
break;
case USER:
default:
if( prefix != 0 || ident != 0 )
{
sb.append( format( prefix, 3 ) );
sb.append( "-" );
sb.append( format( ident, 4) );
}
break;
}
return sb.toString();
}
public boolean hasToID()
{
return getToID() != null && !getToID().isEmpty();
}
/**
* Data message codeword descriptor. Indicates the type of data message
* that the radio unit shall respond with.
*/
public Descriptor getDescriptor()
{
return Descriptor.fromNumber( mMessage.getInt( B1_DESCRIPTOR ) );
}
/**
* Indicates the number of data codeword slots that are appended to a HEAD
* message
*/
public Slots getSlots()
{
return Slots.fromNumber( mMessage.getInt( B1_SLOTS ) );
}
@Override
public Alias getToIDAlias()
{
if( hasToID() )
{
return mAliasList.getMPT1327Alias( getToID() );
}
else
{
return null;
}
}
/**
* Aloha wait time - random access protocol
*/
public int getWaitTime()
{
return mMessage.getInt( B1_WAIT_TIME );
}
/**
* Aloha reserved field
*/
public int getAlohaReserved()
{
return mMessage.getInt( B1_ALOHA_RSVD );
}
/**
* Aloha M field
*/
public int getAlohaM()
{
return mMessage.getInt( B1_ALOHA_M );
}
/**
* Aloha N field
*/
public int getAlohaN()
{
return mMessage.getInt( B1_ALOHA_N );
}
/**
* String representation of the CRC check for each 64-bit message block in
* this message.
*/
@Override
public String getErrorStatus()
{
return getParity();
}
/**
* Used by the map to get a plottable version of this event
*/
@Override
public Plottable getPlottable()
{
return null;
}
/**
* Indicates if the received SDM is formatted according to the MPT-1327 or
* the MPT-1343 ICD.
*/
public SDMFormat getSDMFormat()
{
return SDMFormat.valueOf( mMessage.get( B2_SDM_SEGMENT_TRANSACTION_FLAG ),
mMessage.getInt( B2_SDM_GENERAL_FORMAT ) );
}
public String getSDM()
{
StringBuilder sb = new StringBuilder();
sb.append( "SDM:" );
MPTMessageType type = getMessageType();
switch( type )
{
case HEAD_PLUS1:
case HEAD_PLUS2:
case HEAD_PLUS3:
case HEAD_PLUS4:
SDMFormat format = getSDMFormat();
switch( format )
{
case MPT1327:
sb.append( "MPT1327 " );
sb.append( getSDMBinary( type, format ) );
break;
case MPT1343_BINARY:
sb.append( "BINARY " );
sb.append( getSDMBinary( type, format ) );
break;
case MPT1343_COMMAND:
sb.append( "COMMAND " );
sb.append( getSDMBinary( type, format ) );
break;
case MPT1343_MAP27:
sb.append( "MAP27 " );
sb.append( getSDMBinary( type, format ) );
break;
case MPT1343_RESERVED:
sb.append( "RESERVED " );
sb.append( getSDMBinary( type, format ) );
break;
case MPT1343_SPARE:
sb.append( "SPARE " );
sb.append( getSDMBinary( type, format ) );
break;
case MPT1343_ASCII:
sb.append( "ASCII " );
sb.append( getSDMASCII( type ) );
break;
case MPT1343_BCD:
sb.append( "BCD " );
sb.append( getSDMBCD( type ) );
break;
case MPT1343_TELEX:
sb.append( "TELEX " );
sb.append( getSDMTelex( type ) );
break;
case UNKNOWN:
default:
sb.append( "UNKNOWN " );
break;
}
break;
case SAMO:
sb.append( "SAMO " );
break;
case SAMIS:
sb.append( "SAMIS " );
break;
case SAMIU:
sb.append( "SAMIU " );
break;
default:
break;
}
return sb.toString();
}
public String getSDMBinary( MPTMessageType type, SDMFormat format )
{
StringBuilder sb = new StringBuilder();
switch( type )
{
case HEAD_PLUS1:
if( format == SDMFormat.MPT1327 )
{
sb.append( mMessage.getHex( B2_SDM_STF0_START,
B2_SDM_STF0_END,
12 ) );
}
else
{
sb.append( mMessage.getHex( B2_SDM_STF1_START,
B2_SDM_STF1_END,
12 ) );
}
break;
case HEAD_PLUS2:
if( format == SDMFormat.MPT1327 )
{
sb.append( mMessage.getHex( B2_SDM_STF0_START,
B2_SDM_STF0_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B3_SDM_START,
B3_SDM_END,
12 ) );
}
else
{
sb.append( mMessage.getHex( B2_SDM_STF1_START,
B2_SDM_STF1_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B3_SDM_START,
B3_SDM_END,
12 ) );
}
break;
case HEAD_PLUS3:
if( format == SDMFormat.MPT1327 )
{
sb.append( mMessage.getHex( B2_SDM_STF0_START,
B2_SDM_STF0_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B3_SDM_START,
B3_SDM_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B4_SDM_STF0_START,
B4_SDM_STF0_END,
12 ) );
}
else
{
sb.append( mMessage.getHex( B2_SDM_STF1_START,
B2_SDM_STF1_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B3_SDM_START,
B3_SDM_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B4_SDM_STF1_START,
B4_SDM_STF1_END,
12 ) );
}
break;
case HEAD_PLUS4:
if( format == SDMFormat.MPT1327 )
{
sb.append( mMessage.getHex( B2_SDM_STF0_START,
B2_SDM_STF0_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B3_SDM_START,
B3_SDM_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B4_SDM_STF0_START,
B4_SDM_STF0_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B5_SDM_START,
B5_SDM_END,
12 ) );
}
else
{
sb.append( mMessage.getHex( B2_SDM_STF1_START,
B2_SDM_STF1_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B3_SDM_START,
B3_SDM_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B4_SDM_STF1_START,
B4_SDM_STF1_END,
12 ) );
sb.append( " " );
sb.append( mMessage.getHex( B5_SDM_START,
B5_SDM_END,
12 ) );
}
break;
}
return sb.toString();
}
public String getSDMASCII( MPTMessageType type )
{
StringBuilder sb = new StringBuilder();
int blocks = 0;
switch( type )
{
case HEAD_PLUS1:
blocks = 1;
break;
case HEAD_PLUS2:
blocks = 2;
break;
case HEAD_PLUS3:
blocks = 3;
break;
case HEAD_PLUS4:
blocks = 4;
break;
}
if( blocks >= 1 )
{
sb.append( (char)mMessage.getInt( 91, 97 ) );
sb.append( (char)mMessage.getInt( 98, 104 ) );
sb.append( (char)mMessage.getInt( 105, 111 ) );
sb.append( (char)mMessage.getInt( 112, 118 ) );
sb.append( (char)mMessage.getInt( 119, 125 ) );
}
if( blocks >= 2 )
{
sb.append( (char)mMessage.getInt(
new int[] { 126,127,128,129,130,131,150 } ) );
sb.append( (char)mMessage.getInt( 151, 157 ) );
sb.append( (char)mMessage.getInt( 158, 164 ) );
sb.append( (char)mMessage.getInt( 165, 171 ) );
sb.append( (char)mMessage.getInt( 172, 178 ) );
sb.append( (char)mMessage.getInt( 179, 185 ) );
sb.append( (char)mMessage.getInt( 186, 192 ) );
}
if( blocks >= 3 )
{
sb.append( (char)mMessage.getInt(
new int[] { 193,194,195,218,219,220,221 } ) );
sb.append( (char)mMessage.getInt( 222, 228 ) );
sb.append( (char)mMessage.getInt( 229, 235 ) );
sb.append( (char)mMessage.getInt( 236, 242 ) );
sb.append( (char)mMessage.getInt( 243, 249 ) );
sb.append( (char)mMessage.getInt( 250, 256 ) );
}
if( blocks == 4 )
{
sb.append( (char)mMessage.getInt(
new int[] { 257,258,259,278,279,280,281 } ) );
sb.append( (char)mMessage.getInt( 282, 288 ) );
sb.append( (char)mMessage.getInt( 289, 295 ) );
sb.append( (char)mMessage.getInt( 296, 302 ) );
sb.append( (char)mMessage.getInt( 303, 309 ) );
sb.append( (char)mMessage.getInt( 310, 316 ) );
sb.append( (char)mMessage.getInt( 317, 323 ) );
}
return sb.toString();
}
public String getSDMBCD( MPTMessageType type )
{
StringBuilder sb = new StringBuilder();
int blocks = 0;
switch( type )
{
case HEAD_PLUS1:
blocks = 1;
break;
case HEAD_PLUS2:
blocks = 2;
break;
case HEAD_PLUS3:
blocks = 3;
break;
case HEAD_PLUS4:
blocks = 4;
break;
}
if( blocks >= 1 )
{
sb.append( getBCD( mMessage.getInt( 90, 93 ) ) );
sb.append( getBCD( mMessage.getInt( 94, 97 ) ) );
sb.append( getBCD( mMessage.getInt( 98, 101 ) ) );
sb.append( getBCD( mMessage.getInt( 102, 105 ) ) );
sb.append( getBCD( mMessage.getInt( 106, 109 ) ) );
sb.append( getBCD( mMessage.getInt( 110, 113 ) ) );
sb.append( getBCD( mMessage.getInt( 114, 117 ) ) );
sb.append( getBCD( mMessage.getInt( 118, 121 ) ) );
sb.append( getBCD( mMessage.getInt( 122, 125 ) ) );
sb.append( getBCD( mMessage.getInt( 126, 129 ) ) );
}
if( blocks >= 2 )
{
sb.append( getBCD( mMessage.getInt(
new int[] { 130,131,150,151 } ) ) );
sb.append( getBCD( mMessage.getInt( 152, 155 ) ) );
sb.append( getBCD( mMessage.getInt( 156, 159 ) ) );
sb.append( getBCD( mMessage.getInt( 160, 163 ) ) );
sb.append( getBCD( mMessage.getInt( 164, 167 ) ) );
sb.append( getBCD( mMessage.getInt( 168, 171 ) ) );
sb.append( getBCD( mMessage.getInt( 172, 175 ) ) );
sb.append( getBCD( mMessage.getInt( 176, 179 ) ) );
sb.append( getBCD( mMessage.getInt( 180, 183 ) ) );
sb.append( getBCD( mMessage.getInt( 184, 187 ) ) );
sb.append( getBCD( mMessage.getInt( 188, 191 ) ) );
sb.append( getBCD( mMessage.getInt( 192, 195 ) ) );
}
if( blocks >= 3 )
{
sb.append( getBCD( mMessage.getInt( 218, 221 ) ) );
sb.append( getBCD( mMessage.getInt( 222, 225 ) ) );
sb.append( getBCD( mMessage.getInt( 226, 229 ) ) );
sb.append( getBCD( mMessage.getInt( 230, 233 ) ) );
sb.append( getBCD( mMessage.getInt( 234, 237 ) ) );
sb.append( getBCD( mMessage.getInt( 238, 241 ) ) );
sb.append( getBCD( mMessage.getInt( 242, 245 ) ) );
sb.append( getBCD( mMessage.getInt( 246, 249 ) ) );
sb.append( getBCD( mMessage.getInt( 250, 253 ) ) );
sb.append( getBCD( mMessage.getInt( 254, 257 ) ) );
}
if( blocks == 4 )
{
sb.append( getBCD( mMessage.getInt(
new int[] { 258,259,278,279 } ) ) );
sb.append( getBCD( mMessage.getInt( 280, 283 ) ) );
sb.append( getBCD( mMessage.getInt( 284, 287 ) ) );
sb.append( getBCD( mMessage.getInt( 288, 291 ) ) );
sb.append( getBCD( mMessage.getInt( 292, 295 ) ) );
sb.append( getBCD( mMessage.getInt( 296, 299 ) ) );
sb.append( getBCD( mMessage.getInt( 300, 303 ) ) );
sb.append( getBCD( mMessage.getInt( 304, 307 ) ) );
sb.append( getBCD( mMessage.getInt( 308, 311 ) ) );
sb.append( getBCD( mMessage.getInt( 312, 315 ) ) );
sb.append( getBCD( mMessage.getInt( 316, 319 ) ) );
sb.append( getBCD( mMessage.getInt( 320, 232 ) ) );
}
return sb.toString();
}
private String getBCD( int value )
{
if( 0 <= value && value <= 12 )
{
return BCD[ value ];
}
else
{
return "?";
}
}
public String getSDMTelex( MPTMessageType type )
{
ArrayList<Integer> values = new ArrayList<Integer>();
int blocks = 0;
switch( type )
{
case HEAD_PLUS1:
blocks = 1;
break;
case HEAD_PLUS2:
blocks = 2;
break;
case HEAD_PLUS3:
blocks = 3;
break;
case HEAD_PLUS4:
blocks = 4;
break;
}
if( blocks >= 1 )
{
values.add( mMessage.getInt( 91, 95 ) );
values.add( mMessage.getInt( 96, 100 ) );
values.add( mMessage.getInt( 101, 105 ) );
values.add( mMessage.getInt( 106, 110 ) );
values.add( mMessage.getInt( 111, 115 ) );
values.add( mMessage.getInt( 116, 120 ) );
values.add( mMessage.getInt( 121, 125 ) );
values.add( mMessage.getInt( 126, 130 ) );
}
if( blocks >= 2 )
{
values.add( mMessage.getInt(
new int[] { 131,150,151,152,153 } ) );
values.add( mMessage.getInt( 154, 158 ) );
values.add( mMessage.getInt( 159, 163 ) );
values.add( mMessage.getInt( 164, 168 ) );
values.add( mMessage.getInt( 169, 173 ) );
values.add( mMessage.getInt( 174, 178 ) );
values.add( mMessage.getInt( 179, 183 ) );
values.add( mMessage.getInt( 184, 188 ) );
values.add( mMessage.getInt( 189, 193 ) );
}
if( blocks >= 3 )
{
values.add( mMessage.getInt(
new int[] { 194,195,218,219,220 } ) );
values.add( mMessage.getInt( 221, 225 ) );
values.add( mMessage.getInt( 226, 230 ) );
values.add( mMessage.getInt( 231, 235 ) );
values.add( mMessage.getInt( 236, 240 ) );
values.add( mMessage.getInt( 241, 245 ) );
values.add( mMessage.getInt( 246, 250 ) );
}
if( blocks == 4 )
{
values.add( mMessage.getInt(
new int[] { 251,252,253,254,278 } ) );
values.add( mMessage.getInt( 279, 283 ) );
values.add( mMessage.getInt( 284, 288 ) );
values.add( mMessage.getInt( 289, 293 ) );
values.add( mMessage.getInt( 294, 298 ) );
values.add( mMessage.getInt( 299, 303 ) );
values.add( mMessage.getInt( 304, 308 ) );
values.add( mMessage.getInt( 309, 313 ) );
values.add( mMessage.getInt( 314, 318 ) );
values.add( mMessage.getInt( 319, 323 ) );
}
StringBuilder sb = new StringBuilder();
/* Decode the numeric values. 28 and 29 are used to shift the decoder
* to use the figures alphabet or the letters alphabet */
boolean figure = false;
for( Integer value: values )
{
if( 0 <= value && value < 32 )
{
if( value == 28 )
{
figure = false;
}
else if( value == 29 )
{
figure = true;
}
else
{
if( figure )
{
sb.append( TELEX_FIGURES[ value ] );
}
else
{
sb.append( TELEX_LETTERS[ value ] );
}
}
}
}
return sb.toString();
}
/**
* Provides a listing of aliases contained in the message.
*/
public List<Alias> getAliases()
{
List<Alias> aliases = new ArrayList<Alias>();
Alias from = getFromIDAlias();
if( from != null )
{
aliases.add( from );
}
Alias to = getToIDAlias();
if( to != null )
{
aliases.add( to );
}
return aliases;
}
/**
* SDM Message format ICDs
*/
public enum SDMFormat
{
MPT1327,
MPT1343_BINARY,
MPT1343_BCD,
MPT1343_TELEX,
MPT1343_ASCII,
MPT1343_RESERVED,
MPT1343_SPARE,
MPT1343_COMMAND,
MPT1343_MAP27,
UNKNOWN;
public static SDMFormat valueOf( boolean stf, int gfi )
{
if( stf ) //MPT1343
{
switch( gfi )
{
case 0:
return MPT1343_BINARY;
case 1:
return MPT1343_BCD;
case 2:
return MPT1343_TELEX;
case 3:
return MPT1343_ASCII;
case 4:
return MPT1343_RESERVED;
case 5:
return MPT1343_SPARE;
case 6:
return MPT1343_COMMAND;
case 7:
return MPT1343_MAP27;
default:
return UNKNOWN;
}
}
else
{
return MPT1327;
}
}
}
public enum IdentType
{
ALLI( "SYSTEM-WIDE" ),
DIVERTI( "DIVERT" ),
DNI( "DATA NETWORK GATEWAY" ),
DUMMYI( "DUMMY IDENT" ),
INCI( "INCLUDE IN CALL" ),
IPFIXI( "INTER-PREFIX" ),
PABXI( "PABX GATEWAY" ),
PSTNGI( "PSTN GATEWAY" ),
PSTNSI1( "PSTN OR NETWORK 1" ),
PSTNSI2( "PSTN OR NETWORK 2" ),
PSTNSI3( "PSTN OR NETWORK 3" ),
PSTNSI4( "PSTN OR NETWORK 4" ),
PSTNSI5( "PSTN OR NETWORK 5" ),
PSTNSI6( "PSTN OR NETWORK 6" ),
PSTNSI7( "PSTN OR NETWORK 7" ),
PSTNSI8( "PSTN OR NETWORK 8" ),
PSTNSI9( "PSTN OR NETWORK 9" ),
PSTNSI10( "PSTN OR NETWORK 10" ),
PSTNSI11( "PSTN OR NETWORK 11" ),
PSTNSI12( "PSTN OR NETWORK 12" ),
PSTNSI13( "PSTN OR NETWORK 13" ),
PSTNSI14( "PSTN OR NETWORK 14" ),
PSTNSI15( "PSTN OR NETWORK 15" ),
REGI( "REGISTRATION" ),
RESERVED( "RESERVED" ),
SDMI( "SHORT DATA MESSAGE" ),
SPARE( "SPARE" ),
TSCI( "SYSTEM CONTROLLER" ),
USER( "COMMON-PREFIX IDENT" ),
UNKNOWN( "UNKNOWN" );
private String mLabel;
private IdentType( String label )
{
mLabel = label;
}
public String getLabel()
{
return mLabel;
}
public static IdentType fromIdent( int ident )
{
switch( ident )
{
case 0:
return DUMMYI;
case 8101:
return PSTNGI;
case 8102:
return PABXI;
case 8103:
return DNI;
case 8121:
return PSTNSI1;
case 8122:
return PSTNSI2;
case 8123:
return PSTNSI3;
case 8124:
return PSTNSI4;
case 8125:
return PSTNSI5;
case 8126:
return PSTNSI6;
case 8127:
return PSTNSI7;
case 8128:
return PSTNSI8;
case 8129:
return PSTNSI9;
case 8130:
return PSTNSI10;
case 8131:
return PSTNSI11;
case 8132:
return PSTNSI12;
case 8133:
return PSTNSI13;
case 8134:
return PSTNSI14;
case 8135:
return PSTNSI15;
case 8181:
case 8182:
case 8183:
case 8184:
return RESERVED;
case 8185:
return REGI;
case 8186:
return INCI;
case 8187:
return DIVERTI;
case 8188:
return SDMI;
case 8189:
return IPFIXI;
case 8190:
return TSCI;
case 8191:
return ALLI;
default:
if( 1 <= ident && ident <= 8100 )
{
return USER;
}
else if( ( 8104 <= ident && ident <= 8120 ) ||
( 8136 <= ident && ident <= 8180 ) )
{
return SPARE;
}
else
{
return UNKNOWN;
}
}
}
}
public enum Descriptor
{
DESC0( "EXTENDED ADDRESSING INFORMATION",
"ESN",
"SINGLE SEGMENT TRANSACTIONS (SST) ONLY" ),
DESC1( "PSTN DIALED DIGITS", "RESERVED", "N/A" ),
DESC2( "PABX EXTENSION", "RESERVED", "N/A" ),
DESC3( "N/A", "N/A", "N/A" ),
DESC4( "N/A", "N/A", "FIRST MST SEGMENT OR SINGLE SST" ),
DESC5( "N/A", "N/A", "SECOND MST SEGMENT OR SINGLE SST" ),
DESC6( "N/A", "N/A", "THIRD MST SEGMENT OR SINGLE SST" ),
DESC7( "RESERVED", "RESERVED", "FOURTH MST SEGMENT OR SINGLE SST" ),
UNKNOWN( "UNKNOWN", "UNKNOWN", "UNKNOWN" );
private String mMode1Label;
private String mMode2Label;
private String mSDMLabel;
private Descriptor( String mode1Label, String mode2Label, String sdmLabel )
{
mMode1Label = mode1Label;
mMode2Label = mode2Label;
mSDMLabel = sdmLabel;
}
/* Label that applies to AHYC Mode 1 responses */
public String getMode1Label()
{
return mMode1Label;
}
/* Label that applies to AHYC Mode 2 responses */
public String getMode2Label()
{
return mMode2Label;
}
/* Label that applies to Short Data Messages (SDM) */
public String getSDMLabel()
{
return mSDMLabel;
}
public static Descriptor fromNumber( int number )
{
switch( number )
{
case 0:
return DESC0;
case 1:
return DESC1;
case 2:
return DESC2;
case 3:
return DESC3;
case 4:
return DESC4;
case 5:
return DESC5;
case 6:
return DESC6;
case 7:
return DESC7;
default:
return UNKNOWN;
}
}
}
/**
* Indicates the number of data codeword slots appended to a HEAD message
*/
public enum Slots
{
SLOTS_0( "RESERVED" ),
SLOTS_1( "ADDRESS CODEWORD ONLY" ),
SLOTS_2( "ADDRESS CODEWORD & 1-2 DATA CODEWORDS" ),
SLOTS_3( "ADDRESS CODEWORD & 3-4 DATA CODEWORDS" ),
UNKNOWN( "UNKNOWN" );
private String mLabel;
private Slots( String label )
{
mLabel = label;
}
public String getLabel()
{
return mLabel;
}
public static Slots fromNumber( int number )
{
switch( number )
{
case 0:
return SLOTS_0;
case 1:
return SLOTS_1;
case 2:
return SLOTS_2;
case 3:
return SLOTS_3;
default:
return UNKNOWN;
}
}
}
public enum SystemDefinition
{
UNKNOWN( "UNKNOWN" ),
ANNOUNCE_CONTROL_CHANNEL( "ANNOUNCE CONTROL CHANNEL" ),
WITHDRAW_CONTROL_CHANNEL( "WITHDRAW CONTROL CHANNEL" ),
SPECIFY_CALL_MAINTENANCE_PARAMETERS( "CALL MAINT PARAMETERS" ),
SPECIFY_REGISTRATION_PARAMETERS( "REGISTRATION PARAMETERS" ),
BROADCAST_ADJACENT_SITE_CONTROL_CHANNEL_NUMBER( "NEIGHBOR" ),
VOTE_NOW_ADVICE( "VOTE NOW" );
private String mLabel;
private SystemDefinition( String label )
{
mLabel = label;
}
public String getLabel()
{
return mLabel;
}
public static SystemDefinition fromNumber( int number )
{
switch( number )
{
case 0:
return ANNOUNCE_CONTROL_CHANNEL;
case 1:
return WITHDRAW_CONTROL_CHANNEL;
case 2:
return SPECIFY_CALL_MAINTENANCE_PARAMETERS;
case 3:
return SPECIFY_REGISTRATION_PARAMETERS;
case 4:
return BROADCAST_ADJACENT_SITE_CONTROL_CHANNEL_NUMBER;
case 5:
return VOTE_NOW_ADVICE;
default:
return UNKNOWN;
}
}
}
public enum MPTMessageType
{
UNKN( "Unknown" ),
GTC( "GTC - Goto Channel" ), //0
ALH( "ALH - Aloha" ), //256
ALHS( "ALHS - Standard Data Excluded" ), //257
ALHD( "ALHD - Simple Calls Excluded" ), //258
ALHE( "ALHE - Emergency Calls Only" ), //259
ALHR( "ALHR - Emergency or Registration" ), //260
ALHX( "ALHX - Registration Excluded" ), //261
ALHF( "ALHF - Fallback Mode" ), //262
//263
ACK( "ACK - Acknowledge" ), //264
ACKI( "ACKI - More To Follow" ), //265
ACKQ( "ACKQ - Call Queued" ), //266
ACKX( "ACKX - Message Rejected" ), //267
ACKV( "ACKV - Called Unit Unavailable" ), //268
ACKE( "ACKE - Emergency" ), //269
ACKT( "ACKT - Try On Given Address" ), //270
ACKB( "ACKB - Call Back/Negative Ack" ), //271
AHOY( "AHOY - General Availability Check" ), //272
AHYX( "AHYX - Cancel Alert/Waiting Status" ), //274
AHYP( "AHYP - Called Unit Presence Monitoring" ),//277
AHYQ( "AHYQ - Status Message" ), //278
AHYC( "AHYC - Short Data Message" ), //279
MARK( "MARK - Control Channel Marker" ), //280
MAINT( "MAINT - Call Maintenance Message"), //281
CLEAR( "CLEAR - Down From Allocated Channel" ), //282
MOVE( "MOVE - To Specified Channel" ), //283
BCAST( "BCAST - System Parameters" ), //284
//285 - 287
SAMO( "SAMO - Outbound Single Address" ), //288 - 303
SAMIS( "SAMIS - Inbound Solicited Single Address" ), //288 - 295
SAMIU( "SAMIU - Inbound Unsolicited Single Address" ), //296 - 303
HEAD_PLUS1( "HEAD - 1 DATA CODEWORD" ), //304 - 307
HEAD_PLUS2( "HEAD - 2 DATA CODEWORDS" ), //308 - 311
HEAD_PLUS3( "HEAD - 3 DATA CODEWORDS" ), //312 - 315
HEAD_PLUS4( "HEAD - 4 DATA CODEWORDS" ), //316 - 319
GTT( "GTT - Go To Transaction" ), //320 - 335
SACK( "SACK - Standard Data Selective Ack Header" ), //416 - 423
DACK_DAL( "DACK - Data Ack + DAL" ), //416
DACK_DALG( "DACK - Data Ack + DALG" ), //417
DACK_DALN( "DACK - Data Ack + DALN" ), //418
DACK_GO( "DACK - GO Fragment Transmit Invitation" ), //419
DACKZ( "DACKZ - Data Ack For Expedited Data"), //420
DACKD( "DACKD - Data Ack For Standard Data" ), //421
DAHY( "DAHY - Standard Data Ahoy" ), //424
DRQG( "DRQG - Repeat Group Message" ), //426
DRQZ( "DRQZ - Request Containing Expedited Data" ), //428
DAHYZ( "DAHYZ - Expedited Data Ahoy" ), //428
DAHYX( "DAHYX - Standard Data For Closing TRANS" ),//430
DRQX( "DRQX - Request To Close A Transaction" ), //430
RLA( "RLA - Repeat Last ACK" ), //431
SITH( "SITH - Standard Data Address Codeword Data Item" ); //440 - 443
private String mDescription;
private MPTMessageType( String description )
{
mDescription = description;
}
public String getDescription()
{
return mDescription;
}
public String toString()
{
return getDescription();
}
public static MPTMessageType fromNumber( int number )
{
if( number < 256 )
{
return GTC;
}
switch( number )
{
case 256:
return ALH;
case 257:
return ALHS;
case 258:
return ALHD;
case 259:
return ALHE;
case 260:
return ALHR;
case 261:
return ALHX;
case 262:
return ALHF;
case 264:
return ACK;
case 265:
return ACKI;
case 266:
return ACKQ;
case 267:
return ACKX;
case 268:
return ACKV;
case 269:
return ACKE;
case 270:
return ACKT;
case 271:
return ACKB;
case 272:
return AHOY;
case 274:
return AHYX;
case 277:
return AHYP;
case 278:
return AHYQ;
case 279:
return AHYC;
case 280:
return MARK;
case 281:
return MAINT;
case 282:
return CLEAR;
case 283:
return MOVE;
case 284:
return BCAST;
case 288:
case 289:
case 290:
case 291:
case 292:
case 293:
case 294:
case 295:
case 296:
case 297:
case 298:
case 299:
case 300:
case 301:
case 302:
case 303:
return SAMO;
case 304:
case 305:
case 306:
case 307:
return HEAD_PLUS1;
case 308:
case 309:
case 310:
case 311:
return HEAD_PLUS2;
case 312:
case 313:
case 314:
case 315:
return HEAD_PLUS3;
case 316:
case 317:
case 318:
case 319:
return HEAD_PLUS4;
case 320:
case 321:
case 322:
case 323:
case 324:
case 325:
case 326:
case 327:
case 328:
case 329:
case 330:
case 331:
case 332:
case 333:
case 334:
case 335:
return GTT;
case 416:
return DACK_DAL;
case 417:
return DACK_DALG;
case 418:
return DACK_DALN;
case 419:
return DACK_GO;
case 420:
return DACKZ;
case 421:
return DACKD;
case 424:
return DAHY;
case 426:
return DRQG;
case 428:
return DAHYZ;
case 430:
return DAHYX;
case 440:
case 441:
case 442:
case 443:
return SITH;
default:
return UNKN;
}
}
}
}
<file_sep>package bits;
public class SyncDetector implements ISyncProcessor
{
private long mPattern;
private ISyncDetectListener mListener;
public SyncDetector( long pattern )
{
mPattern = pattern;
}
public SyncDetector( long pattern, ISyncDetectListener listener )
{
this( pattern );
mListener = listener;
}
public void setListener( ISyncDetectListener listener )
{
mListener = listener;
}
@Override
public void checkSync( long value )
{
if( value == mPattern && mListener != null )
{
mListener.syncDetected();
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.passport;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.TreeSet;
import message.Message;
import sample.Listener;
import alias.Alias;
import alias.AliasList;
import controller.activity.ActivitySummaryProvider;
public class PassportActivitySummary implements ActivitySummaryProvider,
Listener<Message>
{
private static final int sINT_NULL_VALUE = -1;
private DecimalFormat mDecimalFormatter = new DecimalFormat("0.00000");
private AliasList mAliasList;
private HashSet<String> mTalkgroupsFirstHeard = new HashSet<String>();
private TreeSet<String> mTalkgroups = new TreeSet<String>();
private TreeSet<String> mMobileIDs = new TreeSet<String>();
private HashMap<Integer,String> mSiteLCNs = new HashMap<Integer,String>();
private HashMap<Integer,String> mNeighborLCNs = new HashMap<Integer,String>();
/**
* Compiles a summary of active talkgroups, unique radio ids encountered
* in the decoded messages. Talkgroups have to be heard a minimum of twice
* to be considered valid ... in order to weed out the invalid ones.
*
* Returns a textual summary of the activity
*/
public PassportActivitySummary( AliasList list )
{
mAliasList = list;
}
@Override
public void receive( Message message )
{
if( message instanceof PassportMessage )
{
PassportMessage passport = ((PassportMessage)message);
if( passport.isValid() )
{
switch( passport.getMessageType() )
{
case CA_STRT:
mSiteLCNs.put( passport.getLCN(),
passport.getLCNFrequencyFormatted() );
case CA_ENDD:
String talkgroup =
String.valueOf( passport.getTalkgroupID() );
if( mTalkgroupsFirstHeard.contains( talkgroup ) )
{
mTalkgroups.add( talkgroup );
}
else
{
mTalkgroupsFirstHeard.add( talkgroup );
}
break;
case ID_RDIO:
String min = passport.getMobileID();
if( min != null )
{
mMobileIDs.add( min );
}
break;
case SY_IDLE:
if( passport.getFree() != 0 )
{
mNeighborLCNs.put( passport.getFree(),
passport.getFreeFrequencyFormatted() );
}
break;
default:
break;
}
}
}
}
@Override
public String getSummary()
{
StringBuilder sb = new StringBuilder();
sb.append( "Activity Summary\n" );
sb.append( "Decoder:\tPassport\n\n" );
sb.append( "Site Channels\n" );
if( mSiteLCNs.isEmpty() )
{
sb.append( " None\n" );
}
else
{
ArrayList<Integer> channels = new ArrayList( mSiteLCNs.keySet() );
Collections.sort( channels );
for( Integer channel: channels )
{
sb.append( " " + channel );
sb.append( "\t" + mSiteLCNs.get( channel ) );
sb.append( "\n" );
}
}
sb.append( "\nNeighbor Channels\n" );
if( mNeighborLCNs.isEmpty() )
{
sb.append( " None\n" );
}
else
{
ArrayList<Integer> channels = new ArrayList( mNeighborLCNs.keySet() );
Collections.sort( channels );
for( Integer channel: channels )
{
sb.append( " " + channel );
sb.append( "\t" + mNeighborLCNs.get( channel ) );
sb.append( "\n" );
}
}
sb.append( "\nTalkgroups\n" );
if( mTalkgroups.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<String> it = mTalkgroups.iterator();
while( it.hasNext() )
{
String tgid = it.next();
sb.append( " " );
sb.append( tgid );
sb.append( " " );
Alias alias = mAliasList.getTalkgroupAlias( tgid );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
sb.append( "\nMobile ID Numbers\n" );
if( mMobileIDs.isEmpty() )
{
sb.append( " None\n" );
}
else
{
Iterator<String> it = mMobileIDs.iterator();
while( it.hasNext() )
{
String min = it.next();
sb.append( " " );
sb.append( min );
sb.append( " " );
Alias alias = mAliasList.getMobileIDNumberAlias( min );
if( alias != null )
{
sb.append( alias.getName() );
}
sb.append( "\n" );
}
}
return sb.toString();
}
public static String formatTalkgroup( String talkgroup )
{
StringBuilder sb = new StringBuilder();
if( talkgroup.length() == 6 )
{
sb.append( talkgroup.substring( 0, 1 ) );
sb.append( "-" );
sb.append( talkgroup.substring( 1, 3 ) );
sb.append( "-" );
sb.append( talkgroup.substring( 3, 6 ) );
return sb.toString();
}
else
{
return talkgroup;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 record;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import properties.SystemProperties;
import record.config.RecordConfiguration;
import record.wave.ComplexWaveRecorder;
import record.wave.FloatWaveRecorder;
import util.TimeStamp;
import controller.channel.ProcessingChain;
public class RecorderManager
{
public static final int sSAMPLE_RATE = 48000;
public RecorderManager()
{
}
public List<Recorder> getRecorder( ProcessingChain channel )
{
/* Note: the file suffix (ie .wav) gets added by the recorder */
//Get the base recording filename
StringBuilder sb = new StringBuilder();
sb.append( SystemProperties.getInstance()
.getApplicationFolder( "recordings" ) );
sb.append( File.separator );
sb.append( TimeStamp.getTimeStamp( "_" ) );
sb.append( "_" );
sb.append( channel.getChannel().getName() );
ArrayList<Recorder> retVal = new ArrayList<Recorder>();
RecordConfiguration config = channel.getChannel().getRecordConfiguration();
for( RecorderType recorder: config.getRecorders() )
{
switch( recorder )
{
case AUDIO:
retVal.add( new FloatWaveRecorder( sSAMPLE_RATE,
sb.toString() + "_audio" ) );
break;
case BASEBAND:
retVal.add( new ComplexWaveRecorder( sSAMPLE_RATE,
sb.toString() + "_baseband" ) );
break;
}
}
return retVal;
}
}
<file_sep>package decode.p25.message.pdu.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.pdu.PDUMessage;
import decode.p25.message.tsbk.osp.control.SystemService;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import edac.CRCP25;
public class AdjacentStatusBroadcastExtended extends PDUMessage
implements IdentifierReceiver
{
public static final int[] LRA = { 88,89,90,91,92,93,94,95 };
public static final int[] SYSTEM_ID = { 100,101,102,103,104,105,106,107,108,
109,110,111 };
public static final int[] RF_SUBSYSTEM_ID = { 128,129,130,131,132,133,134,
135 };
public static final int[] SITE_ID = { 136,137,138,139,140,141,142,143 };
public static final int[] TRANSMIT_IDENTIFIER = { 160,161,162,163 };
public static final int[] TRANSMIT_CHANNEL = { 164,165,166,167,168,169,170,
171,172,173,174,175 };
public static final int[] RECEIVE_IDENTIFIER = { 176,177,178,179 };
public static final int[] RECEIVE_CHANNEL = { 180,181,182,183,184,185,186,
187,188,189,190,191 };
public static final int[] SYSTEM_SERVICE_CLASS = { 192,193,194,195,196,197,
198,199 };
public static final int[] MULTIPLE_BLOCK_CRC = { 224,225,226,227,228,229,
230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255 };
private IBandIdentifier mTransmitIdentifierProvider;
private IBandIdentifier mReceiveIdentifierProvider;
public AdjacentStatusBroadcastExtended( BinaryMessage message,
DataUnitID duid, AliasList aliasList )
{
super( message, duid, aliasList );
/* Header block is already error detected/corrected - perform error
* detection correction on the intermediate and final data blocks */
mMessage = CRCP25.correctPDU1( mMessage );
mCRC[ 1 ] = mMessage.getCRC();
}
@Override
public String getEventType()
{
return Opcode.ADJACENT_STATUS_BROADCAST.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " LRA:" + getLocationRegistrationArea() );
sb.append( " SYS:" + getSystemID() );
sb.append( " RFSS:" + getRFSubsystemID() );
sb.append( " SITE:" + getSiteID() );
sb.append( " CTRL CHAN:" + getReceiveIdentifier() + "-" + getReceiveChannel() );
sb.append( " DN:" + getDownlinkFrequency() );
sb.append( " " + getTransmitIdentifier() + "-" + getTransmitChannel() );
sb.append( " UP:" + getUplinkFrequency() );
sb.append( " SYS SVC CLASS:" +
SystemService.toString( getSystemServiceClass() ) );
return sb.toString();
}
public String getLocationRegistrationArea()
{
return mMessage.getHex( LRA, 2 );
}
public String getSystemID()
{
return mMessage.getHex( SYSTEM_ID, 3 );
}
public String getRFSubsystemID()
{
return mMessage.getHex( RF_SUBSYSTEM_ID, 2 );
}
public String getSiteID()
{
return mMessage.getHex( SITE_ID, 2 );
}
public int getTransmitIdentifier()
{
return mMessage.getInt( TRANSMIT_IDENTIFIER );
}
public int getTransmitChannel()
{
return mMessage.getInt( TRANSMIT_CHANNEL );
}
public int getReceiveIdentifier()
{
return mMessage.getInt( RECEIVE_IDENTIFIER );
}
public int getReceiveChannel()
{
return mMessage.getInt( RECEIVE_CHANNEL );
}
public int getSystemServiceClass()
{
return mMessage.getInt( SYSTEM_SERVICE_CLASS );
}
public long getDownlinkFrequency()
{
return calculateDownlink( mTransmitIdentifierProvider, getTransmitChannel() );
}
public long getUplinkFrequency()
{
return calculateUplink( mReceiveIdentifierProvider, getReceiveChannel() );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
if( identifier == getTransmitIdentifier() )
{
mTransmitIdentifierProvider = message;
}
if( identifier == getReceiveIdentifier() )
{
mReceiveIdentifierProvider = message;
}
}
public int[] getIdentifiers()
{
int[] idens = new int[ 2 ];
idens[ 0 ] = getTransmitIdentifier();
idens[ 1 ] = getReceiveIdentifier();
return idens;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.passport;
public enum PassportBand
{
BAND_800( "800", 800000000 ),
BAND_900( "900", 900000000 ),
BAND_400( "400", 400000000 ),
BAND_420( "420", 420000000 ),
BAND_440( "440", 440000000 ),
BAND_450( "450", 450000000 ),
BAND_460( "460", 460000000 ),
BAND_470( "470", 470000000 ),
BAND_480( "480", 480000000 ),
BAND_490( "490", 490000000 ),
BAND_CANADA( "CAN", 0 ),
BAND_NTIA( "NTIA", 0 ),
BAND_RESERVED12( "RESVD", 0 ),
BAND_216( "216", 216000000 ),
BAND_RESERVED14( "RESVD", 0 ),
BAND_700( "700", 700000000 ),
BAND_VHF( "VHF", 0 ),
BAND_UNKNOWN( "UNK", 0 );
public static int CHANNEL_BANDWIDTH = 12500; //Hertz
private String mDescription;
private int mBase;
private PassportBand( String description, int base )
{
mDescription = description;
mBase = base;
}
public static PassportBand lookup( int band )
{
if( band >= 0 && band < 16 )
{
return PassportBand.values()[ band ];
}
else
{
return PassportBand.BAND_UNKNOWN;
}
}
public long getFrequency( int channel )
{
return ( mBase + ( channel * CHANNEL_BANDWIDTH ) );
}
public int getChannel( long frequency )
{
return Math.round( (float)( frequency - mBase ) /
(float)CHANNEL_BANDWIDTH );
}
public String getDescription()
{
return mDescription;
}
public int getBase()
{
return mBase;
}
}
<file_sep>package decode.p25.reference;
public class P25NetworkCallsign
{
public static final String[] RADIX_50 = new String[]
{ " ", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O",
"P", "Q", "R", "S", "T", "U", "V", "W",
"X", "Y", "Z", "$", ".", "?", "0", "1",
"2", "3", "4", "5", "6", "7", "8", "9" };
/**
* Decodes the string callsign from which the WACN and System identifiers
* were derived.
*
* Based on code by <NAME> at:
* http://www.ericcarlson.net/project-25-callsign.html
*
* @param wacn
* @param systemID
* @return
*/
public static String getCallsign( int wacn, int systemID )
{
int n1 = wacn / 16;
int n2 = 4096 * ( wacn % 16 ) + systemID;
StringBuilder sb = new StringBuilder();
sb.append( getLetter( (int)( n1 / 1600 ) ) );
sb.append( getLetter( (int)( ( n1 / 40 ) % 40 ) ) );
sb.append( getLetter( (int)( n1 % 40 ) ) );
sb.append( getLetter( (int)( n2 / 1600 ) ) );
sb.append( getLetter( (int)( ( n2 / 40 ) % 40 ) ) );
sb.append( getLetter( (int)( n2 % 40 ) ) );
return sb.toString();
}
private static String getLetter( int value )
{
if( 0 <= value && value < 40 )
{
return RADIX_50[ value ];
}
return " ";
}
}
<file_sep>package decode.p25.message.pdu.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.pdu.PDUMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import edac.CRCP25;
public class MessageUpdateExtended extends PDUMessage
{
public static final int[] TARGET_ADDRESS = { 88,89,90,91,92,93,94,95,96,97,
98,99,100,101,102,103,104,105,106,107,108,109,110,111 };
public static final int[] SOURCE_WACN = { 128,129,130,131,132,133,134,135,136,137,
138,139,140,141,142,143,160,161,162,163 };
public static final int[] SOURCE_SYSTEM_ID = { 164,165,166,167,168,169,170,171,172,
173,174,175 };
public static final int[] SOURCE_ID = { 176,177,178,179,180,181,182,183,184,
185,186,187,188,189,190,191,192,193,194,195,196,197,198,199 };
public static final int[] SHORT_DATA_MESSAGE = { 200,201,202,203,204,205,
206,207,208,209,210,211,212,213,214,215 };
public static final int[] MULTIPLE_BLOCK_CRC = { 224,225,226,227,228,229,
230,231,232,233,234,235,236,237,238,239,240,241,242,243,244,245,246,247,
248,249,250,251,252,253,254,255 };
public MessageUpdateExtended( BinaryMessage message,
DataUnitID duid, AliasList aliasList )
{
super( message, duid, aliasList );
/* Header block is already error detected/corrected - perform error
* detection correction on the intermediate and final data blocks */
mMessage = CRCP25.correctPDU1( mMessage );
mCRC[ 1 ] = mMessage.getCRC();
}
@Override
public String getEventType()
{
return Opcode.CALL_ALERT.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " TO:" );
sb.append( getTargetAddress() );
sb.append( " MSG:" );
sb.append( getShortDataMessage() );
sb.append( " FROM:" );
sb.append( getSourceID() );
sb.append( " WACN:" );
sb.append( getSourceWACN() );
sb.append( " SYS:" );
sb.append( getSourceSystemID() );
return sb.toString();
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
public String getSourceWACN()
{
return mMessage.getHex( SOURCE_WACN, 5 );
}
public String getSourceSystemID()
{
return mMessage.getHex( SOURCE_SYSTEM_ID, 3 );
}
public String getSourceID()
{
return mMessage.getHex( SOURCE_ID, 6 );
}
public String getShortDataMessage()
{
return mMessage.getHex( SHORT_DATA_MESSAGE, 4 );
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class StatusUpdate extends TSBKMessage
{
public static final int[] USER_STATUS = { 72,73,74,75,88,89,90,91 };
public static final int[] UNIT_STATUS = { 92,93,94,95,96,97,98,99 };
public static final int[] TARGET_ADDRESS = { 112,113,114,115,116,117,118,
119,120,121,122,123,136,137,138,139,140,141,142,143,144,145,146,147 };
public static final int[] SOURCE_ADDRESS = { 160,161,162,163,164,165,166,
167,168,169,170,171,184,185,186,187,188,189,190,190,192,193,194,195 };
public StatusUpdate( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.STATUS_UPDATE.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " STATUS USER:" + getUserStatus() );
sb.append( " UNIT:" + getUnitStatus() );
sb.append( " SRC ADDR: " + getSourceAddress() );
sb.append( " TGT ADDR: " + getTargetAddress() );
return sb.toString();
}
public String getUserStatus()
{
return mMessage.getHex( USER_STATUS, 2 );
}
public String getUnitStatus()
{
return mMessage.getHex( UNIT_STATUS, 2 );
}
public String getSourceAddress()
{
return mMessage.getHex( SOURCE_ADDRESS, 6 );
}
@Override
public String getFromID()
{
return getSourceAddress();
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
@Override
public String getToID()
{
return getTargetAddress();
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.reference.LinkControlOpcode;
public class StatusUpdate extends TDULinkControlMessage
{
private final static Logger mLog =
LoggerFactory.getLogger( StatusUpdate.class );
public static final int[] USER_STATUS = { 80,81,82,83,84,85,86,87 };
public static final int[] UNIT_STATUS = { 88,89,90,91,92,93,94,95 };
public static final int[] TARGET_ADDRESS = { 112,113,114,115,116,117,118,
119,120,121,122,123,136,137,138,139,140,141,142,143,144,145,146,147 };
public static final int[] SOURCE_ADDRESS = { 160,161,162,163,164,165,166,
167,168,169,170,171,184,185,186,187,188,189,190,191,192,193,194,195 };
public StatusUpdate( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.STATUS_UPDATE.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " STATUS USER:" + getUserStatus() );
sb.append( " UNIT:" + getUnitStatus() );
sb.append( " FROM:" + getSourceAddress() );
sb.append( " TO:" + getTargetAddress() );
return sb.toString();
}
public String getUserStatus()
{
return mMessage.getHex( USER_STATUS, 2 );
}
public String getUnitStatus()
{
return mMessage.getHex( UNIT_STATUS, 2 );
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
public String getSourceAddress()
{
return mMessage.getHex( SOURCE_ADDRESS, 6 );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 spectrum;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.geom.GeneralPath;
import java.awt.geom.Line2D;
import javax.swing.JPanel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import settings.ColorSetting;
import settings.ColorSetting.ColorSettingName;
import settings.Setting;
import settings.SettingChangeListener;
import buffer.FloatArrayCircularAveragingBuffer;
import controller.ResourceManager;
public class SpectrumPanel extends JPanel
implements DFTResultsListener,
SettingChangeListener,
SpectralDisplayAdjuster
{
private static final long serialVersionUID = 1L;
private final static Logger mLog =
LoggerFactory.getLogger( SpectrumPanel.class );
/* Set display bins size to 1, so that we're guaranteed a reset to the
* correct width once the first sample set arrives */
private float[] mDisplayFFTBins = new float[ 1 ];
private FloatArrayCircularAveragingBuffer mFFTAveragingBuffer;
private int mAveraging = 4;
private int mDBScale = -100; //dBm
/**
* Spectral Display Color Settings
*/
private static final String SPECTRUM_BACKGROUND = "spectrum_background";
private static final String SPECTRUM_GRADIENT_TOP = "spectrum_gradient_top";
private static final String SPECTRUM_GRADIENT_BOTTOM = "spectrum_gradient_bottom";
private static final String SPECTRUM_LINE = "spectrum_line";
private static final String SPECTRUM_AVERAGING_SIZE = "spectrum_averaging_size";
private static final int SPECTRUM_TRANSLUCENCY = 128;
private Color mColorSpectrumBackground;
private Color mColorSpectrumGradientTop;
private Color mColorSpectrumGradientBottom;
private Color mColorSpectrumLine;
private float mSpectrumInset = 20.0f;
private ResourceManager mResourceManager;
public SpectrumPanel( ResourceManager resourceManager )
{
mResourceManager = resourceManager;
getSettings();
setAveraging( mAveraging );
}
public void dispose()
{
mResourceManager = null;
}
public void setAveraging( int size )
{
mAveraging = size;
mFFTAveragingBuffer =
new FloatArrayCircularAveragingBuffer( mAveraging );
}
public int getAveraging()
{
return mAveraging;
}
/**
* Sets the lowest decibel scale value to show on the display
*/
public void setDBScale( int dbScale )
{
mDBScale = dbScale;
}
public int getDBScale()
{
return mDBScale;
}
public void clearSpectrum()
{
mDisplayFFTBins = null;
repaint();
}
private void getSettings()
{
mColorSpectrumBackground =
getColor( ColorSettingName.SPECTRUM_BACKGROUND );
mColorSpectrumGradientBottom =
getColor( ColorSettingName.SPECTRUM_GRADIENT_BOTTOM );
mColorSpectrumGradientTop =
getColor( ColorSettingName.SPECTRUM_GRADIENT_TOP );
mColorSpectrumLine = getColor( ColorSettingName.SPECTRUM_LINE );
mAveraging = 4;
}
private Color getColor( ColorSettingName name )
{
ColorSetting setting =
mResourceManager.getSettingsManager().getColorSetting( name );
return setting.getColor();
}
@Override
public void settingChanged( Setting setting )
{
if( setting instanceof ColorSetting )
{
ColorSetting colorSetting = (ColorSetting)setting;
switch( ( (ColorSetting) setting ).getColorSettingName() )
{
case SPECTRUM_BACKGROUND:
mColorSpectrumBackground = colorSetting.getColor();
break;
case SPECTRUM_GRADIENT_BOTTOM:
mColorSpectrumGradientBottom = colorSetting.getColor();
break;
case SPECTRUM_GRADIENT_TOP:
mColorSpectrumGradientTop = colorSetting.getColor();
break;
case SPECTRUM_LINE:
mColorSpectrumLine = colorSetting.getColor();
break;
}
}
}
/**
* DFTResultsListener interface method - for receiving the processed data
* to display
*/
public void receive( float[] currentFFTBins )
{
//Construct and/or resize our fft results variables
if( mDisplayFFTBins == null ||
mDisplayFFTBins.length != currentFFTBins.length )
{
mDisplayFFTBins = new float[ currentFFTBins.length ];
}
/**
* Store the new FFT bins in the buffer and get the average of the FFT
* bin buffer contents into the display fft bins variable
*/
mDisplayFFTBins = mFFTAveragingBuffer.get( currentFFTBins );
repaint();
}
@Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Graphics2D graphics = (Graphics2D) g;
graphics.setBackground( mColorSpectrumBackground );
RenderingHints renderHints =
new RenderingHints( RenderingHints.KEY_ANTIALIASING,
RenderingHints.VALUE_ANTIALIAS_ON );
renderHints.put( RenderingHints.KEY_RENDERING,
RenderingHints.VALUE_RENDER_QUALITY );
graphics.setRenderingHints( renderHints );
drawSpectrum( graphics );
}
/**
* Draws the current fft spectrum with a line and a gradient fill.
*/
private void drawSpectrum( Graphics2D graphics )
{
Dimension size = getSize();
//Draw the background
Rectangle background = new Rectangle( 0, 0, size.width, size.height );
graphics.setColor( mColorSpectrumBackground );
graphics.draw( background );
graphics.fill( background );
//Define the gradient
GradientPaint gradient = new GradientPaint( 0,
0,
mColorSpectrumGradientTop,
0,
getSize().height,
mColorSpectrumGradientBottom );
graphics.setBackground( mColorSpectrumBackground );
GeneralPath spectrumShape = new GeneralPath();
//Start at the lower right inset point
spectrumShape.moveTo( size.getWidth(),
size.getHeight() - mSpectrumInset );
//Draw to the lower left
spectrumShape.lineTo( 0, size.getHeight() - mSpectrumInset );
//If we have FFT data to display ...
if( mDisplayFFTBins != null )
{
float insideHeight = size.height - mSpectrumInset;
float scalor = insideHeight / ( -mDBScale );
float insideWidth = size.width;
int binCount = mDisplayFFTBins.length;
float binSize = insideWidth / ( binCount );
for( int x = 0; x < binCount; x++ )
{
float height;
if( mDisplayFFTBins[ x ] > 0 )
{
height = 0;
}
else
{
height = (float)( Math.abs( mDisplayFFTBins[ x ] ) * scalor );
if( height > insideHeight )
{
height = insideHeight;
}
if( height < 0 )
{
height = 0;
}
}
spectrumShape.lineTo( ( x * binSize ), height );
}
}
//Otherwise show an empty spectrum
else
{
//Draw Left Size
graphics.setPaint( gradient );
spectrumShape.lineTo( 0, size.getHeight() - mSpectrumInset );
//Draw Middle
spectrumShape.lineTo( size.getWidth(),
size.getHeight() - mSpectrumInset );
}
//Draw Right Side
spectrumShape.lineTo( size.getWidth(),
size.getHeight() - mSpectrumInset );
graphics.setPaint( gradient );
graphics.draw( spectrumShape );
graphics.fill( spectrumShape );
graphics.setPaint( mColorSpectrumLine );
//Draw the bottom line under the spectrum
graphics.draw( new Line2D.Float( 0,
size.height - mSpectrumInset,
size.width,
size.height - mSpectrumInset ) );
}
@Override
public void settingDeleted( Setting setting ) {}
}
<file_sep>package decode.tait;
import java.util.Collections;
import java.util.List;
import message.Message;
import filter.Filter;
import filter.FilterElement;
public class Tait1200MessageFilter extends Filter<Message>
{
public Tait1200MessageFilter()
{
super( "Tait-1200 Message Filter" );
}
@Override
public boolean passes( Message message )
{
return mEnabled && canProcess( message );
}
@Override
public boolean canProcess( Message message )
{
return message instanceof Tait1200GPSMessage;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return Collections.EMPTY_LIST;
}
}
<file_sep>package decode.p25.message.pdu.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.pdu.PDUMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Encryption;
import decode.p25.reference.Opcode;
import edac.CRCP25;
public class ProtectionParameterBroadcast extends PDUMessage
{
public static final int[] TARGET_ADDRESS = { 88,89,90,91,92,93,94,95,96,97,
98,99,100,101,102,103,104,105,106,107,108,109,110,111 };
public static final int[] ENCRYPTION_TYPE = { 128,129,130,131,132,133,134,
135 };
public static final int[] ALGORITHM_ID = { 136,137,138,139,140,141,142,143 };
public static final int[] KEY_ID = { 160,161,162,163,164,165,166,167,168,
169,170,171,172,173,174,175 };
public static final int[] INBOUND_INITIALIZATION_VECTOR_A = { 176,177,178,
179,180,181,182,183,184,185,186,187,188,189,190,191,192,193,194,195,196,
197,198,199,200,201,202,203,204,205,206,207,208,209,210,211,212,213,214,
215 };
public static final int[] INBOUND_INITIALIZATION_VECTOR_B = { 216,217,218,
219,220,221,222,223,224,225,226,227,228,229,230,231,232,233,234,235,236,
237,238,239,240,241,242,243,244,245,246,247 };
public static final int[] OUTBOUND_INITIALIZATION_VECTOR_A = { 248,249,250,
251,252,253,254,255,256,257,258,259,260,261,262,263,264,265,266,267,268,
269,270,271,272,273,274,275,276,277,278,279,280,281,282,283,284,285,286,
287 };
public static final int[] OUTBOUND_INITIALIZATION_VECTOR_B = { 288,289,290,
291,292,293,294,295,296,297,298,299,300,301,302,303,304,305,306,307,308,
309,310,311,312,313,314,315,316,317,318,319 };
public static final int[] MULTIPLE_BLOCK_CRC = { 320,321,322,323,324,325,
326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,
343,344,345,346,347,348,349,350,351 };
public ProtectionParameterBroadcast( BinaryMessage message,
DataUnitID duid, AliasList aliasList )
{
super( message, duid, aliasList );
/* Header block is already error detected/corrected - perform error
* detection correction on the intermediate and final data blocks */
mMessage = CRCP25.correctPDU1( mMessage );
mCRC[ 1 ] = mMessage.getCRC();
}
@Override
public String getEventType()
{
return Opcode.PROTECTION_PARAMETER_BROADCAST.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " TO:" );
sb.append( getTargetAddress() );
sb.append( " ENCRYPTION:" );
sb.append( getEncryptionType().name() );
sb.append( " ALGORITHM ID:" );
sb.append( getAlgorithmID() );
sb.append( " KEY ID:" );
sb.append( getKeyID() );
sb.append( " INBOUND IV:" );
sb.append( getInboundInitializationVector() );
sb.append( " OUTBOUND IV:" );
sb.append( getOutboundInitializationVector() );
return sb.toString();
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
public Encryption getEncryptionType()
{
return Encryption.fromValue( mMessage.getInt( ENCRYPTION_TYPE ) );
}
public String getAlgorithmID()
{
return mMessage.getHex( ALGORITHM_ID, 2 );
}
public String getKeyID()
{
return mMessage.getHex( KEY_ID, 4 );
}
public String getInboundInitializationVector()
{
return mMessage.getHex( INBOUND_INITIALIZATION_VECTOR_A, 10 ) +
mMessage.getHex( INBOUND_INITIALIZATION_VECTOR_B, 8 );
}
public String getOutboundInitializationVector()
{
return mMessage.getHex( OUTBOUND_INITIALIZATION_VECTOR_A, 10 ) +
mMessage.getHex( OUTBOUND_INITIALIZATION_VECTOR_B, 8 );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 map;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import org.jdesktop.swingx.painter.Painter;
/**
* Paints a selection rectangle
* @author <NAME>
*/
public class SelectionPainter implements Painter<Object>
{
private Color fillColor = new Color(128, 192, 255, 128);
private Color frameColor = new Color(0, 0, 255, 128);
private SelectionAdapter adapter;
/**
* @param adapter the selection adapter
*/
public SelectionPainter(SelectionAdapter adapter)
{
this.adapter = adapter;
}
@Override
public void paint(Graphics2D g, Object t, int width, int height)
{
Rectangle rc = adapter.getRectangle();
if (rc != null)
{
g.setColor(frameColor);
g.draw(rc);
g.setColor(fillColor);
g.fill(rc);
}
}
}
<file_sep>package decode.p25.reference;
public enum VendorLinkControlOpcode
{
RESERVED_00( "OPCODE_00", "RESERVED", 0 ),
RESERVED_01( "OPCODE_01", "RESERVED", 1 ),
RESERVED_02( "OPCODE_02", "RESERVED", 2 ),
RESERVED_03( "OPCODE_03", "RESERVED", 3 ),
RESERVED_04( "OPCODE_04", "RESERVED", 4 ),
RESERVED_05( "OPCODE_05", "RESERVED", 5 ),
RESERVED_06( "OPCODE_06", "RESERVED", 6 ),
RESERVED_07( "OPCODE_07", "RESERVED", 7 ),
RESERVED_08( "OPCODE_0B", "RESERVED", 8 ),
RESERVED_09( "OPCODE_0B", "RESERVED", 9 ),
RESERVED_0A( "OPCODE_0B", "RESERVED", 10 ),
RESERVED_0B( "OPCODE_0B", "RESERVED", 11 ),
RESERVED_0C( "OPCODE_0C", "RESERVED", 12 ),
RESERVED_0D( "OPCODE_0D", "RESERVED", 13 ),
RESERVED_0E( "OPCODE_0E", "RESERVED", 14 ),
RESERVED_0F( "OPCODE_0F", "RESERVED", 15 ),
RESERVED_10( "OPCODE_10", "RESERVED", 16 ),
RESERVED_11( "OPCODE_11", "RESERVED", 17 ),
RESERVED_12( "OPCODE_12", "RESERVED", 18 ),
RESERVED_13( "OPCODE_13", "RESERVED", 19 ),
RESERVED_14( "OPCODE_14", "RESERVED", 20 ),
RESERVED_15( "OPCODE_15", "RESERVED", 21 ),
RESERVED_16( "OPCODE_16", "RESERVED", 22 ),
RESERVED_17( "OPCODE_17", "RESERVED", 23 ),
RESERVED_18( "OPCODE_18", "RESERVED", 24 ),
RESERVED_19( "OPCODE_19", "RESERVED", 25 ),
RESERVED_1A( "OPCODE_1A", "RESERVED", 26 ),
RESERVED_1B( "OPCODE_1B", "RESERVED", 27 ),
RESERVED_1C( "OPCODE_1C", "RESERVED", 28 ),
RESERVED_1D( "OPCODE_1D", "RESERVED", 29 ),
RESERVED_1E( "OPCODE_1E", "RESERVED", 30 ),
RESERVED_1F( "OPCODE_1F", "RESERVED", 31 ),
RESERVED_20( "OPCODE_20", "RESERVED", 32 ),
RESERVED_21( "OPCODE_21", "RESERVED", 33 ),
RESERVED_22( "OPCODE_22", "RESERVED", 34 ),
RESERVED_23( "OPCODE_23", "RESERVED", 35 ),
RESERVED_24( "OPCODE_24", "RESERVED", 36 ),
RESERVED_25( "OPCODE_25", "RESERVED", 37 ),
RESERVED_26( "OPCODE_26", "RESERVED", 38 ),
RESERVED_27( "OPCODE_27", "RESERVED", 39 ),
RESERVED_28( "OPCODE_28", "RESERVED", 40 ),
RESERVED_29( "OPCODE_29", "RESERVED", 41 ),
RESERVED_2A( "OPCODE_2A", "RESERVED", 42 ),
RESERVED_2B( "OPCODE_2B", "RESERVED", 43 ),
RESERVED_2C( "OPCODE_2C", "RESERVED", 44 ),
RESERVED_2D( "OPCODE_2D", "RESERVED", 45 ),
RESERVED_2E( "OPCODE_2E", "RESERVED", 46 ),
RESERVED_2F( "OPCODE_2F", "RESERVED", 47 ),
RESERVED_30( "OPCODE_30", "RESERVED", 48 ),
RESERVED_31( "OPCODE_31", "RESERVED", 49 ),
RESERVED_32( "OPCODE_32", "RESERVED", 50 ),
RESERVED_33( "OPCODE_33", "RESERVED", 51 ),
RESERVED_34( "OPCODE_34", "RESERVED", 52 ),
RESERVED_35( "OPCODE_35", "RESERVED", 53 ),
RESERVED_36( "OPCODE_36", "RESERVED", 54 ),
RESERVED_37( "OPCODE_37", "RESERVED", 55 ),
RESERVED_38( "OPCODE_38", "RESERVED", 56 ),
RESERVED_39( "OPCODE_39", "RESERVED", 57 ),
RESERVED_3A( "OPCODE_3A", "RESERVED", 58 ),
RESERVED_3B( "OPCODE_3B", "RESERVED", 59 ),
RESERVED_3C( "OPCODE_3C", "RESERVED", 60 ),
RESERVED_3D( "OPCODE_3D", "RESERVED", 61 ),
RESERVED_3E( "OPCODE_3E", "RESERVED", 62 ),
RESERVED_3F( "OPCODE_3F", "RESERVED", 63 ),
UNKNOWN( "UNKNOWN OPCODE", "UNKNOWN", -1 );
private String mLabel;
private String mDescription;
private int mCode;
private VendorLinkControlOpcode( String label, String description, int code )
{
mLabel = label;
mDescription = description;
mCode = code;
}
public String getLabel()
{
return mLabel;
}
public String getDescription()
{
return mDescription;
}
public int getCode()
{
return mCode;
}
public static VendorLinkControlOpcode fromValue( int value )
{
if( 0 <= value && value <= 63 )
{
return values()[ value ];
}
return UNKNOWN;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner;
import javax.usb.UsbDeviceDescriptor;
public enum TunerClass
{
GENERIC_2832( TunerType.RTL2832_VARIOUS, "0BDA", "2832", "RTL2832", "SDR" ),
GENERIC_2838( TunerType.RTL2832_VARIOUS, "0BDA", "2838", "RTL2832", "SDR" ),
COMPRO_VIDEOMATE_U620F( TunerType.ELONICS_E4000, "185B", "0620", "Compro", "Videomate U620F" ),
COMPRO_VIDEOMATE_U650F( TunerType.ELONICS_E4000, "185B", "0650", "Compro", "Videomate U620F" ),
COMPRO_VIDEOMATE_U680F( TunerType.ELONICS_E4000, "185B", "0680", "Compro", "Videomate U620F" ),
DEXATEK_LOGILINK_VG002A( TunerType.FCI_FC2580, "1D19", "1101", "Dexatek", "Logilink VG0002A" ),
DEXATEK_DIGIVOX_MINI_II_REV3( TunerType.FCI_FC2580, "1D19", "1102", "Dexatek", "MSI Digivox Mini II v3.0" ),
DEXATEK_5217_DVBT( TunerType.FCI_FC2580, "1D19", "1103", "Dexatek", "5217 DVB-T" ),
ETTUS_USRP_B100( TunerType.ETTUS_VARIOUS, "2500", "0002", "Ettus Research", "USRP B100" ),
FUNCUBE_DONGLE_PRO( TunerType.FUNCUBE_DONGLE_PRO, "04D8", "FB56", "Hamlincrest", "Funcube Dongle Pro" ),
FUNCUBE_DONGLE_PRO_PLUS( TunerType.FUNCUBE_DONGLE_PRO_PLUS, "04D8", "FB31", "Hamlincrest", "Funcube Dongle Pro Plus" ),
GIGABYTE_GTU7300( TunerType.FITIPOWER_FC0012, "1B80", "D393", "Gigabyte", "GT-U7300" ),
GTEK_T803( TunerType.FITIPOWER_FC0012, "1F4D", "B803", "GTek", "T803" ),
HACKRF_ONE( TunerType.HACKRF, "1D50", "6089", "Great Scott Gadgets", "HackRF One" ),
LIFEVIEW_LV5T_DELUXE( TunerType.FITIPOWER_FC0012, "1F4D", "C803", "Liveview", "LV5T Deluxe" ),
MYGICA_TD312( TunerType.FITIPOWER_FC0012, "1F4D", "D286", "MyGica", "TD312" ),
PEAK_102569AGPK( TunerType.FITIPOWER_FC0012, "1B80", "D395", "Peak", "102569AGPK" ),
PROLECTRIX_DV107669( TunerType.FITIPOWER_FC0012, "1F4D", "D803", "Prolectrix", "DV107669" ),
SVEON_STV20( TunerType.FITIPOWER_FC0012, "1B80", "D39D", "Sveon", "STV20 DVB-T USB & FM" ),
TERRATEC_CINERGY_T_REV1( TunerType.FITIPOWER_FC0012, "0CCD", "00A9", "Terratec", "Cinergy T R1" ),
TERRATEC_CINERGY_T_REV3( TunerType.ELONICS_E4000, "0CCD", "00D3", "Terratec", "Cinergy T R3" ),
TERRATEC_NOXON_REV1_B3( TunerType.FITIPOWER_FC0013, "0CCD", "00B3", "Terratec", "NOXON R1 (B3)" ),
TERRATEC_NOXON_REV1_B4( TunerType.FITIPOWER_FC0013, "0CCD", "00B4", "Terratec", "NOXON R1 (B4)" ),
TERRATEC_NOXON_REV1_B7( TunerType.FITIPOWER_FC0013, "0CCD", "00B7", "Terratec", "NOXON R1 (B7)" ),
TERRATEC_NOXON_REV1_C6( TunerType.FITIPOWER_FC0013, "0CCD", "00C6", "Terratec", "NOXON R1 (C6)" ),
TERRATEC_NOXON_REV2( TunerType.ELONICS_E4000, "0CCD", "00E0", "Terratec", "NOXON R2" ),
TERRATEC_T_STICK_PLUS( TunerType.ELONICS_E4000, "0CCD", "00D7", "Terratec", "T Stick Plus" ),
TWINTECH_UT40( TunerType.FITIPOWER_FC0013, "1B80", "D3A4", "Twintech", "UT-40" ),
ZAAPA_ZTMINDVBZP( TunerType.FITIPOWER_FC0012, "1B80", "D398", "Zaapa", "ZT-MINDVBZP" ),
UNKNOWN( TunerType.UNKNOWN, "0", "0", "Unknown Manufacturer", "Unknown Device" );
private TunerType mTunerType;
private String mVendorID;
private String mDeviceID;
private String mVendorDescription;
private String mDeviceDescription;
private TunerClass( TunerType tunerType,
String vendorID,
String deviceID,
String vendorDescription,
String deviceDescription )
{
mTunerType = tunerType;
mVendorID = vendorID;
mDeviceID = deviceID;
mVendorDescription = vendorDescription;
mDeviceDescription = deviceDescription;
}
public String toString()
{
return "USB" +
" Tuner:" + mTunerType.toString() +
" Vendor:" + mVendorDescription +
" Device:" + mDeviceDescription +
" Address:" + mVendorID + ":" + mDeviceID;
}
public String getVendorDeviceLabel()
{
return mVendorDescription + " " + mDeviceDescription;
}
public TunerType getTunerType()
{
return mTunerType;
}
public static TunerClass valueOf( UsbDeviceDescriptor descriptor )
{
return valueOf( descriptor.idVendor(), descriptor.idProduct() );
}
public static TunerClass valueOf( short vendor, short product )
{
TunerClass retVal = TunerClass.UNKNOWN;
//Cast the short to integer so that we can switch on unsigned numbers
int vendorID = vendor & 0xFFFF;
int productID = product & 0xFFFF;
switch( vendorID )
{
case 1240: //04DA
if( productID == 64305 ) //FB31
{
retVal = FUNCUBE_DONGLE_PRO_PLUS;
}
else if( productID == 64342 ) //FB56
{
retVal = FUNCUBE_DONGLE_PRO;
}
break;
case 3034: //0BDA
if( productID == 10290 ) //2832
{
retVal = GENERIC_2832;
}
else if( productID == 10296 ) //2838
{
retVal = GENERIC_2838;
}
break;
case 6235: //185B
if( productID == 1568 ) //0620
{
retVal = COMPRO_VIDEOMATE_U620F;
}
else if( productID == 1616 ) //0650
{
retVal = COMPRO_VIDEOMATE_U650F;
}
else if( productID == 1664 ) //0680
{
retVal = COMPRO_VIDEOMATE_U680F;
}
break;
case 7040: //1B80
if( productID == 54163 ) //D393
{
retVal = GIGABYTE_GTU7300;
}
else if( productID == 54165 ) //D395
{
retVal = PEAK_102569AGPK;
}
else if( productID == 54168 ) //D398
{
retVal = ZAAPA_ZTMINDVBZP;
}
else if( productID == 54173 ) //D39D
{
retVal = SVEON_STV20;
}
else if( productID == 54180 ) //D3A4
{
retVal = TWINTECH_UT40;
}
break;
case 7449: //1D19
if( productID == 4353 ) //1101
{
retVal = DEXATEK_LOGILINK_VG002A;
}
else if( productID == 4354 ) //1102
{
retVal = DEXATEK_DIGIVOX_MINI_II_REV3;
}
else if( productID == 4355 ) //1103
{
retVal = DEXATEK_5217_DVBT;
}
break;
case 7504: //1D50
if( productID == 24713 ) //6089
{
retVal = HACKRF_ONE;
}
break;
case 8013: //1F4D
if( productID == 47107 ) //B803
{
retVal = GTEK_T803;
}
else if( productID == 51203 ) //C803
{
retVal = LIFEVIEW_LV5T_DELUXE;
}
else if( productID == 53894 ) //D286
{
retVal = MYGICA_TD312;
}
else if( productID == 55299 ) //D803
{
retVal = PROLECTRIX_DV107669;
}
break;
case 3277: //0CCD
if( productID == 169 ) //00A9
{
retVal = TERRATEC_CINERGY_T_REV1;
}
else if( productID == 179 ) //00B3
{
retVal = TERRATEC_NOXON_REV1_B3;
}
else if( productID == 180 ) //00B4
{
retVal = TERRATEC_NOXON_REV1_B4;
}
else if( productID == 181 ) //00B5
{
retVal = TERRATEC_NOXON_REV1_B7;
}
else if( productID == 198 ) //00C6
{
retVal = TERRATEC_NOXON_REV1_C6;
}
else if( productID == 211 ) //00D3
{
retVal = TERRATEC_CINERGY_T_REV3;
}
else if( productID == 215 ) //00D7
{
retVal = TERRATEC_T_STICK_PLUS;
}
else if( productID == 224) //00E0
{
retVal = TERRATEC_NOXON_REV2;
}
break;
case 9472: //2500
if( productID == 2 ) //0002
{
retVal = ETTUS_USRP_B100;
}
break;
default:
}
return retVal;
}
public String getVendorID()
{
return mVendorID;
}
public String getDeviceID()
{
return mDeviceID;
}
public String getVendorDescription()
{
return mVendorDescription;
}
public String getDeviceDescription()
{
return mDeviceDescription;
}
}
<file_sep>package decode.p25.message.tsbk.osp.data;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.UnitChannelGrant;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class IndividualDataChannelGrant extends UnitChannelGrant
{
public IndividualDataChannelGrant( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.INDIVIDUAL_DATA_CHANNEL_GRANT.getDescription();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 alias;
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.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.tree.TreePath;
import net.miginfocom.swing.MigLayout;
import controller.ConfigurableNode;
public class GroupEditor extends JPanel implements ActionListener
{
private static final long serialVersionUID = 1L;
private GroupNode mGroupNode;
private JLabel mLabelName;
private JTextField mTextGroup;
public GroupEditor( GroupNode groupNode )
{
mGroupNode = groupNode;
initGUI();
}
private void initGUI()
{
setLayout( new MigLayout() );
setBorder( BorderFactory.createTitledBorder( "Group" ) );
mLabelName = new JLabel( "Name:" );
add( mLabelName, "align right" );
mTextGroup = new JTextField( mGroupNode.getGroup().getName() );
add( mTextGroup, "grow, wrap" );
JButton btnSave = new JButton( "Save" );
btnSave.addActionListener( GroupEditor.this );
add( btnSave );
JButton btnReset = new JButton( "Reset" );
btnReset.addActionListener( GroupEditor.this );
add( btnReset, "wrap" );
}
@Override
public void actionPerformed( ActionEvent e )
{
String command = e.getActionCommand();
if( command.contentEquals( "Save" ) )
{
String group = mTextGroup.getText();
if( group != null )
{
boolean expanded = mGroupNode.getModel().getTree()
.isExpanded( new TreePath( mGroupNode ) );
mGroupNode.getGroup().setName( group );
((ConfigurableNode)mGroupNode.getParent()).sort();
mGroupNode.save();
mGroupNode.show();
if( expanded )
{
mGroupNode.getModel().getTree()
.expandPath( new TreePath( mGroupNode ) );
}
}
else
{
JOptionPane.showMessageDialog( GroupEditor.this, "Please enter a group name" );
}
}
else if( command.contentEquals( "Reset" ) )
{
mTextGroup.setText( mGroupNode.getGroup().getName() );
}
mGroupNode.refresh();
}
}
<file_sep>package audio;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import audio.AudioPacket.Type;
/**
* Audio output with automatic flow control based on the availability of
* audio data packets.
*/
public class MonoAudioOutput implements Listener<AudioPacket>
{
private final static Logger mLog = LoggerFactory.getLogger( MonoAudioOutput.class );
/* Output line buffer size is set at one second of audio at 48 kHz and
* two bytes per sample */
private final static int BUFFER_SIZE = 48000;
/* The queue processor will run every 20 milliseconds checking for inbound
* audio and automatically starting or stopping audio playback. We set the
* data line available space threshold to start when we're 20 ms away from
* being full, and the stop threshold when 20 ms away from being empty */
private final static int SAMPLE_SIZE_40_MS = 48000 / 25;
private final static int START_THRESHOLD = SAMPLE_SIZE_40_MS;
private final static int STOP_THRESHOLD = BUFFER_SIZE - SAMPLE_SIZE_40_MS;
private LinkedTransferQueue<AudioPacket> mBuffer = new LinkedTransferQueue<>();
private ScheduledExecutorService mExecutorService;
private SourceDataLine mOutput;
private boolean mCanProcessAudio;
private AtomicBoolean mMuted = new AtomicBoolean( true );
private AtomicBoolean mSquelched = new AtomicBoolean( false );
public MonoAudioOutput()
{
try
{
mOutput = AudioSystem.getSourceDataLine(
AudioFormats.PCM_SIGNED_48KHZ_16BITS );
if( mOutput != null )
{
mOutput.open( AudioFormats.PCM_SIGNED_48KHZ_16BITS, BUFFER_SIZE );
mCanProcessAudio = true;
mExecutorService = Executors.newSingleThreadScheduledExecutor();
/* Run the queue processor task every 40 milliseconds */
mExecutorService.scheduleAtFixedRate( new QueueProcessor(),
0, 40, TimeUnit.MILLISECONDS );
}
}
catch ( LineUnavailableException e )
{
mLog.error( "Couldn't obtain source data line for 48kHz PCM mono "
+ "audio output" );
}
}
public void setMuted( boolean muted )
{
mMuted.set( muted );
}
public void setSquelched( boolean squelched )
{
mSquelched.set( squelched );
}
public void dispose()
{
mCanProcessAudio = false;
mBuffer.clear();
if( mExecutorService != null )
{
mExecutorService.shutdown();
}
if( mOutput != null )
{
mOutput.close();
}
}
@Override
public void receive( AudioPacket packet )
{
if( mCanProcessAudio )
{
mBuffer.add( packet );
}
}
public class QueueProcessor implements Runnable
{
private AtomicBoolean mProcessing = new AtomicBoolean();
public QueueProcessor()
{
}
@Override
public void run()
{
/* The mProcessing flag ensures that only one instance of the
* processor can run at any given time */
if( mProcessing.compareAndSet( false, true ) )
{
List<AudioPacket> packets = new ArrayList<AudioPacket>();
mBuffer.drainTo( packets );
if( packets.size() > 0 )
{
for( AudioPacket packet: packets )
{
if( mCanProcessAudio )
{
if( mMuted.get() || mSquelched.get() )
{
checkStop();
}
else if( packet.getType() == Type.AUDIO )
{
mOutput.write( packet.getAudioData(), 0,
packet.getAudioData().length );
checkStart();
}
}
}
}
else
{
checkStop();
}
mProcessing.set( false );
}
}
private void checkStart()
{
if( mCanProcessAudio && !mMuted.get() && !mSquelched.get() &&
!mOutput.isRunning() && mOutput.available() <= START_THRESHOLD )
{
mOutput.start();
}
}
private void checkStop()
{
if( mCanProcessAudio && mOutput.isRunning() &&
( mOutput.available() >= STOP_THRESHOLD || mMuted.get() || mSquelched.get() ) )
{
mOutput.drain();
mOutput.stop();
}
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 map;
import java.awt.Component;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
public class MapIconListCellRenderer extends JLabel
implements ListCellRenderer<MapIcon>
{
private static final long serialVersionUID = 1L;
public MapIconListCellRenderer()
{
setOpaque( true );
}
@Override
public Component getListCellRendererComponent(
JList<? extends MapIcon> list, MapIcon value, int index,
boolean isSelected, boolean cellHasFocus )
{
setIcon( value.getImageIcon() );
setText( value.toString() );
if ( isSelected )
{
setBackground( list.getSelectionBackground() );
setForeground( list.getSelectionForeground() );
}
else
{
setBackground( list.getBackground() );
setForeground( list.getForeground() );
}
return this;
}
}
<file_sep>package decode.p25.reference;
public enum StackOperation
{
CLEAR,
WRITE,
DELETE,
READ,
UNKNOWN;
public static StackOperation fromValue( int value )
{
if( 0 <= value && value <= 3 )
{
return values()[ value ];
}
return UNKNOWN;
}
}
<file_sep>package decode.p25.message.tsbk.vendor;
public enum VendorOpcode
{
OP00( "OPCODE 00 ", "VENDOR OPCODE 0x00", 0x00 ),
OP01( "OPCODE 01 ", "VENDOR OPCODE 0x01", 0x01 ),
OP02( "OPCODE 02 ", "VENDOR OPCODE 0x02", 0x02 ),
OP03( "OPCODE 03 ", "VENDOR OPCODE 0x03", 0x03 ),
OP04( "OPCODE 04 ", "VENDOR OPCODE 0x04", 0x04 ),
OP05( "OPCODE 05 ", "VENDOR OPCODE 0x05", 0x05 ),
OP06( "OPCODE 06 ", "VENDOR OPCODE 0x06", 0x06 ),
OP07( "OPCODE 07 ", "VENDOR OPCODE 0x07", 0x07 ),
OP08( "OPCODE 08 ", "VENDOR OPCODE 0x08", 0x08 ),
OP09( "OPCODE 09 ", "VENDOR OPCODE 0x09", 0x09 ),
OP0A( "OPCODE 0A ", "VENDOR OPCODE 0x0A", 0x0A ),
OP0B( "OPCODE 0B ", "VENDOR OPCODE 0x0B", 0x0B ),
OP0C( "OPCODE 0C ", "VENDOR OPCODE 0x0C", 0x0C ),
OP0D( "OPCODE 0D ", "VENDOR OPCODE 0x0D", 0x0D ),
OP0E( "OPCODE 0E ", "VENDOR OPCODE 0x0E", 0x0E ),
OP0F( "OPCODE 0F ", "VENDOR OPCODE 0x0F", 0x0F ),
OP10( "OPCODE 10 ", "VENDOR OPCODE 0x10", 0x10 ),
OP11( "OPCODE 11 ", "VENDOR OPCODE 0x11", 0x11 ),
OP12( "OPCODE 12 ", "VENDOR OPCODE 0x12", 0x12 ),
OP13( "OPCODE 13 ", "VENDOR OPCODE 0x13", 0x13 ),
OP14( "OPCODE 14 ", "VENDOR OPCODE 0x14", 0x14 ),
OP15( "OPCODE 15 ", "VENDOR OPCODE 0x15", 0x15 ),
OP16( "OPCODE 16 ", "VENDOR OPCODE 0x16", 0x16 ),
OP17( "OPCODE 17 ", "VENDOR OPCODE 0x17", 0x17 ),
OP18( "OPCODE 18 ", "VENDOR OPCODE 0x18", 0x18 ),
OP19( "OPCODE 19 ", "VENDOR OPCODE 0x19", 0x19 ),
OP1A( "OPCODE 1A ", "VENDOR OPCODE 0x1A", 0x1A ),
OP1B( "OPCODE 1B ", "VENDOR OPCODE 0x1B", 0x1B ),
OP1C( "OPCODE 1C ", "VENDOR OPCODE 0x1C", 0x1C ),
OP1D( "OPCODE 1D ", "VENDOR OPCODE 0x1D", 0x1D ),
OP1E( "OPCODE 1E ", "VENDOR OPCODE 0x1E", 0x1E ),
OP1F( "OPCODE 1F ", "VENDOR OPCODE 0x1F", 0x1F ),
OP20( "OPCODE 20 ", "VENDOR OPCODE 0x20", 0x20 ),
OP21( "OPCODE 21 ", "VENDOR OPCODE 0x21", 0x21 ),
OP22( "OPCODE 22 ", "VENDOR OPCODE 0x22", 0x22 ),
OP23( "OPCODE 23 ", "VENDOR OPCODE 0x23", 0x23 ),
OP24( "OPCODE 24 ", "VENDOR OPCODE 0x24", 0x24 ),
OP25( "OPCODE 25 ", "VENDOR OPCODE 0x25", 0x25 ),
OP26( "OPCODE 26 ", "VENDOR OPCODE 0x26", 0x26 ),
OP27( "OPCODE 27 ", "VENDOR OPCODE 0x27", 0x27 ),
OP28( "OPCODE 28 ", "VENDOR OPCODE 0x28", 0x28 ),
OP29( "OPCODE 29 ", "VENDOR OPCODE 0x29", 0x29 ),
OP2A( "OPCODE 2A ", "VENDOR OPCODE 0x2A", 0x2A ),
OP2B( "OPCODE 2B ", "VENDOR OPCODE 0x2B", 0x2B ),
OP2C( "OPCODE 2C ", "VENDOR OPCODE 0x2C", 0x2C ),
OP2D( "OPCODE 2D ", "VENDOR OPCODE 0x2D", 0x2D ),
OP2E( "OPCODE 2E ", "VENDOR OPCODE 0x2E", 0x2E ),
OP2F( "OPCODE 2F ", "VENDOR OPCODE 0x2F", 0x2F ),
OP30( "OPCODE 30 ", "VENDOR OPCODE 0x30", 0x30 ),
OP31( "OPCODE 31 ", "VENDOR OPCODE 0x31", 0x31 ),
OP32( "OPCODE 32 ", "VENDOR OPCODE 0x32", 0x32 ),
OP33( "OPCODE 33 ", "VENDOR OPCODE 0x33", 0x33 ),
OP34( "OPCODE 34 ", "VENDOR OPCODE 0x34", 0x34 ),
OP35( "OPCODE 35 ", "VENDOR OPCODE 0x35", 0x35 ),
OP36( "OPCODE 36 ", "VENDOR OPCODE 0x36", 0x36 ),
OP37( "OPCODE 37 ", "VENDOR OPCODE 0x37", 0x37 ),
OP38( "OPCODE 38 ", "VENDOR OPCODE 0x38", 0x38 ),
OP39( "OPCODE 39 ", "VENDOR OPCODE 0x39", 0x39 ),
OP3A( "OPCODE 3A ", "VENDOR OPCODE 0x3A", 0x3A ),
OP3B( "OPCODE 3B ", "VENDOR OPCODE 0x3B", 0x3B ),
OP3C( "OPCODE 3C ", "VENDOR OPCODE 0x3C", 0x3C ),
OP3D( "OPCODE 3D ", "VENDOR OPCODE 0x3D", 0x3D ),
OP3E( "OPCODE 3E ", "VENDOR OPCODE 0x3E", 0x3E ),
OP3F( "OPCODE 3F ", "VENDOR OPCODE 0x3F", 0x3F ),
UNKNOWN( "UNKNOWN ", "Unknown", -1 );
private String mLabel;
private String mDescription;
private int mCode;
private VendorOpcode( String label, String description, int code )
{
mLabel = label;
mDescription = description;
mCode = code;
}
public String getLabel()
{
return mLabel;
}
public String toString()
{
return getLabel();
}
public String getDescription()
{
return mDescription;
}
public int getCode()
{
return mCode;
}
public static VendorOpcode fromValue( int value )
{
if( 0 <= value && value <= 0x3F )
{
return VendorOpcode.values()[ value ];
}
return UNKNOWN;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 audio;
import java.nio.ByteBuffer;
import javax.sound.sampled.AudioFormat;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.SourceDataLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.real.RealSampleListener;
import audio.inverted.AudioAdapter;
import audio.inverted.AudioType;
import audio.inverted.IAudioTypeListener;
import buffer.FloatSampleBufferAssembler;
public class AudioOutputImpl implements RealSampleListener,
SquelchListener, IAudioTypeListener, IAudioOutput
{
private final static Logger mLog =
LoggerFactory.getLogger( AudioOutputImpl.class );
private static final int sAUDIO_BLOCK_SIZE = 24000;
private static final AudioFormat sAUDIO_FORMAT =
new AudioFormat( 48000, //SampleRate
16, //Sample Size
1, //Channels
true, //Signed
false ); //Little Endian
private AudioAdapter mAdapter = new AudioAdapter( 48000 );
private FloatSampleBufferAssembler mBuffer =
new FloatSampleBufferAssembler( sAUDIO_BLOCK_SIZE );
private SourceDataLine mOutput;
private boolean mEnabled = false;
private SquelchState mSquelchState = SquelchState.SQUELCH;
public AudioOutputImpl( String channelName )
{
try
{
mOutput = AudioSystem.getSourceDataLine( sAUDIO_FORMAT );
mOutput.open( sAUDIO_FORMAT, (int)( sAUDIO_FORMAT.getSampleRate() ) );
mOutput.start();
}
catch ( LineUnavailableException e )
{
mLog.error( "AudioOutput - couldn't open audio speakers "
+ "for playback", e );
}
}
@Override
public void setSquelch( SquelchState state )
{
mSquelchState = state;
}
@Override
public void setAudioPlaybackEnabled( boolean enabled )
{
mEnabled = enabled;
}
@Override
public void dispose()
{
mOutput.stop();
mOutput.close();
mOutput = null;
}
@Override
public void receive( float sample )
{
float outputSample = mAdapter.get( sample );
if( mEnabled && mSquelchState == SquelchState.UNSQUELCH )
{
mBuffer.put( outputSample );
}
else
{
/* Use 0-valued samples when we're disabled or squelched */
mBuffer.put( 0.0f );
}
if( !mBuffer.hasRemaining() )
{
ByteBuffer buffer = mBuffer.get();
mOutput.write( buffer.array(), 0, buffer.array().length );
mBuffer.reset();
}
}
@Override
public void setAudioType( AudioType type )
{
mAdapter.setAudioType( type );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.config;
import source.SourceType;
public class SourceConfigFactory
{
public static SourceConfiguration getDefaultSourceConfiguration()
{
return getSourceConfiguration( SourceType.NONE );
}
public static SourceConfiguration
getSourceConfiguration( SourceType source )
{
SourceConfiguration retVal;
switch( source )
{
case MIXER:
retVal = new SourceConfigMixer();
break;
case TUNER:
retVal = new SourceConfigTuner();
break;
case RECORDING:
retVal = new SourceConfigRecording();
break;
case NONE:
default:
retVal = new SourceConfigNone();
break;
}
return retVal;
}
}
<file_sep>package decode.am;
import audio.AudioOutputImpl;
import audio.IAudioOutput;
import sample.real.RealSampleListener;
import source.Source.SampleType;
import decode.Decoder;
import decode.DecoderType;
import dsp.am.AMDemodulator;
import dsp.filter.ComplexFIRFilter;
import dsp.filter.DCRemovalFilter2;
import dsp.filter.FilterFactory;
import dsp.filter.FloatFIRFilter;
import dsp.filter.Window.WindowType;
import dsp.gain.ComplexAutomaticGainControl;
import dsp.gain.RealAutomaticGainControl;
public class AMDecoder extends Decoder
{
/**
* This value determines how quickly the DC remove filter responds to
* changes in frequency.
*/
private static final double DC_REMOVAL_RATIO = 0.003;
private ComplexFIRFilter mIQFilter;
private ComplexAutomaticGainControl mBasebandAGC =
new ComplexAutomaticGainControl();
private AMDemodulator mDemodulator = new AMDemodulator();
private DCRemovalFilter2 mDCRemovalFilter =
new DCRemovalFilter2( DC_REMOVAL_RATIO );
private RealAutomaticGainControl mAudioAGC = new RealAutomaticGainControl();
private FloatFIRFilter mLowPassFilter;
private AudioOutputImpl mAudioOutput = new AudioOutputImpl( "AM Decoder Audio Output" );
public AMDecoder( SampleType sampleType )
{
super( sampleType );
/**
* Only setup a demod chain if we're receiving complex samples. If
* we're receiving demodulated samples, they'll be handled the same
* was as we handle the output of the demodulator.
*/
if( mSourceSampleType == SampleType.COMPLEX )
{
mIQFilter = new ComplexFIRFilter(
FilterFactory.getLowPass( 48000, 6500, 73, WindowType.HAMMING ),
1.0 );
/**
* The Decoder super class is both a Complex listener and a float
* listener. So, we add the demod to listen to the incoming
* quadrature samples, and we wire the output of the demod right
* back to this class, so we can receive the demodulated output
* to process
*/
this.addComplexListener( mIQFilter );
mIQFilter.setListener( mBasebandAGC );
mBasebandAGC.setListener( mDemodulator );
/**
* Remove the DC component that is present when we're mistuned
*/
mDemodulator.setListener( mDCRemovalFilter );
/**
* Route the demodulated, filtered samples back to this class to send
* to all registered listeners
*/
mLowPassFilter = new FloatFIRFilter(
FilterFactory.getLowPass( 48000, 3000, 31, WindowType.COSINE ), 1.0 );
mDCRemovalFilter.setListener( mLowPassFilter );
mLowPassFilter.setListener( mAudioAGC );
mAudioAGC.setListener( this.getRealReceiver() );
addRealSampleListener( mAudioOutput );
}
}
@Override
public IAudioOutput getAudioOutput()
{
return mAudioOutput;
}
@Override
public DecoderType getType()
{
return DecoderType.AM;
}
@Override
public void addUnfilteredRealSampleListener( RealSampleListener listener )
{
throw new IllegalArgumentException( "cannot add real sample "
+ "listener to AM demodulator - not implemented" );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.system;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import controller.ConfigurableNode;
public class SystemListNode extends ConfigurableNode
{
private static final long serialVersionUID = 1L;
public SystemListNode( SystemList list )
{
super( list );
}
public SystemList getSystemList()
{
return (SystemList)getUserObject();
}
public void init()
{
for( System system: getSystemList().getSystem() )
{
SystemNode node = new SystemNode( system );
getModel().addNode( node, SystemListNode.this, getChildCount() );
node.init();
}
sort();
}
public String toString()
{
return "Systems [" + this.getChildCount() + "]";
}
public JPopupMenu getContextMenu()
{
JPopupMenu retVal = new JPopupMenu();
JMenuItem addSystemItem = new JMenuItem( "Add System" );
addSystemItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
System system = new System();
getSystemList().addSystem( system );
getModel().addNode( new SystemNode( system ),
SystemListNode.this,
SystemListNode.this.getChildCount() );
}
} );
retVal.add( addSystemItem );
return retVal;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.site;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Enumeration;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSeparator;
import javax.swing.tree.DefaultMutableTreeNode;
import controller.ConfigurableNode;
import controller.channel.Channel;
import controller.channel.ChannelNode;
import controller.system.System;
import controller.system.SystemNode;
public class SiteNode extends ConfigurableNode
{
private static final long serialVersionUID = 1L;
public SiteNode( Site site )
{
super( site );
}
public void init()
{
for( Channel channel: getSite().getChannel() )
{
ChannelNode node = new ChannelNode( channel );
getModel().insertNodeInto( node, SiteNode.this, getChildCount() );
node.init();
}
sort();
}
public String getIconPath()
{
return "images/site.png";
}
@Override
public Color getBackgroundColor()
{
@SuppressWarnings( "unchecked" )
Enumeration<DefaultMutableTreeNode> nodes = children();
while( nodes.hasMoreElements() )
{
ChannelNode child = (ChannelNode)nodes.nextElement();
if( child.getBackgroundColor() != null )
{
return Color.CYAN;
}
}
return null;
}
@Override
public JPanel getEditor()
{
return new SiteEditor( this );
}
public Site getSite()
{
return (Site)getUserObject();
}
public String toString()
{
return getSite().getName();
}
public void delete()
{
for( int x = 0; x < getChildCount(); x++ )
{
((ChannelNode)getChildAt( x )).delete();
}
((SystemNode)getParent()).getSystem().removeSite( getSite() );
save();
getModel().removeNodeFromParent( SiteNode.this );
}
public JPopupMenu getContextMenu()
{
JPopupMenu retVal = new JPopupMenu();
JMenuItem addChannelItem = new JMenuItem( "Add Channel" );
addChannelItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
System system = ((SystemNode)getParent()).getSystem();
Channel channel = new Channel();
channel.setSystem( system, false );
channel.setSite( getSite(), false );
getSite().addChannel( channel );
ChannelNode node = new ChannelNode( channel );
getModel().addNode( node,
SiteNode.this,
SiteNode.this.getChildCount() );
sort();
save();
node.show();
/* Give channel reference to the resource manager and the
* channel will register the listeners and send a channel
* add event */
channel.setResourceManager( getModel().getResourceManager() );
}
} );
retVal.add( addChannelItem );
retVal.add( new JSeparator() );
JMenuItem deleteItem = new JMenuItem( "Delete" );
deleteItem.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent e )
{
delete();
}
} );
retVal.add( deleteItem );
return retVal;
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.reference.ExtendedFunction;
import decode.p25.reference.LinkControlOpcode;
public class ExtendedFunctionCommand extends TDULinkControlMessage
{
private final static Logger mLog =
LoggerFactory.getLogger( ExtendedFunctionCommand.class );
public static final int[] EXTENDED_FUNCTION = { 72,73,74,75,88,89,90,91,92,
93,94,95,96,97,98,99 };
public static final int[] ARGUMENT = { 112,113,114,115,116,117,118,119,120,
121,122,123,136,137,138,139,140,141,142,143,144,145,145,147 };
public static final int[] TARGET_ADDRESS = { 160,161,162,163,164,165,166,
167,168,169,170,171,184,185,186,187,188,189,190,190,192,193,194,195 };
public ExtendedFunctionCommand( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.EXTENDED_FUNCTION_COMMAND.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " EXTENDED FUNCTION:" + getExtendedFunction().getLabel() );
sb.append( " ARGUMENT: " + getTargetAddress() );
sb.append( " TGT ADDR: " + getTargetAddress() );
return sb.toString();
}
public ExtendedFunction getExtendedFunction()
{
return ExtendedFunction.fromValue( mMessage.getInt( EXTENDED_FUNCTION ) );
}
public String getArgument()
{
return mMessage.getHex( ARGUMENT, 6 );
}
public String getSourceAddress()
{
switch( getExtendedFunction() )
{
case RADIO_CHECK:
case RADIO_CHECK_ACK:
case RADIO_DETACH:
case RADIO_DETACH_ACK:
case RADIO_INHIBIT:
case RADIO_INHIBIT_ACK:
case RADIO_UNINHIBIT:
case RADIO_UNINHIBIT_ACK:
return getArgument();
default:
break;
}
return null;
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
@Override
public String getToID()
{
return getTargetAddress();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.channel;
import java.util.ArrayList;
import alias.action.AliasActionManager;
import message.Message;
import sample.Listener;
import controller.ResourceManager;
public class ChannelManager implements ChannelEventListener
{
private ArrayList<Channel> mChannels = new ArrayList<Channel>();
private ArrayList<ChannelEventListener> mChannelListeners =
new ArrayList<ChannelEventListener>();
private ArrayList<Listener<Message>> mMessageListeners =
new ArrayList<Listener<Message>>();
private AliasActionManager mAliasActionManager;
public ChannelManager( ResourceManager resourceManager )
{
mAliasActionManager = new AliasActionManager( resourceManager );
mChannelListeners.add( this );
/* Add alias action manager as listener to all channels/messages */
mMessageListeners.add( mAliasActionManager );
}
/**
* Notification that a channel has been added or deleted, so that we can
* keep track of all channels and manage system-wide listeners for each
* of those channels
*/
@SuppressWarnings( "incomplete-switch" )
@Override
public void channelChanged( ChannelEvent event )
{
switch( event.getEvent() )
{
case CHANNEL_ADDED:
if( !mChannels.contains( event.getChannel() ) )
{
mChannels.add( event.getChannel() );
}
break;
case CHANNEL_DELETED:
mChannels.remove( event.getChannel() );
break;
}
}
/**
* Adds a channel listener that will be added to all channels to receive
* any channel change events. This listener will automatically receive
* a channel add event as it is added to each of the existing channels.
*/
public void addListener( ChannelEventListener listener )
{
mChannelListeners.add( listener );
for( Channel channel: mChannels )
{
channel.addListener( listener );
}
}
/**
* Removes a channel listener from being automatically added to all channels
* to receive channel change events.
*/
public void removeListener( ChannelEventListener listener )
{
mChannelListeners.remove( listener );
for( Channel channel: mChannels )
{
channel.removeListener( listener );
}
}
/**
* Returns the list of channel change listeners that will be automatically
* added to all channels to receive channel change events
*/
public ArrayList<ChannelEventListener> getChannelListeners()
{
return mChannelListeners;
}
/**
* Returns the list of channel change listeners that will be automatically
* added to all channels to receive channel change events
*/
public ArrayList<Listener<Message>> getMessageListeners()
{
return mMessageListeners;
}
/**
* Adds a message listener that will be added to all channels to receive
* any messages.
*/
public void addListener( Listener<Message> listener )
{
mMessageListeners.add( listener );
}
/**
* Removes a message listener.
*/
public void removeListener( Listener<Message> listener )
{
mMessageListeners.remove( listener );
}
}
<file_sep>package dsp.filter.interpolator;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.complex.ComplexSample;
public class QPSKInterpolator extends Interpolator
{
private final static Logger mLog = LoggerFactory.getLogger( QPSKInterpolator.class );
private float mGain;
public QPSKInterpolator( float gain )
{
mGain = gain;
}
/**
* Calculates an interpolated value from the 8 samples beginning at the
* offset index. Uses the mu value to determine which of 128 filter kernels
* to use in order to closely approximate the ideal frequency response for
* the value of mu, ranging from 0.0 to 1.0, indicating the interpolated
* position in the sample set ranging from offset to offset + 7.
*
* @param samples - sample array of length at least offset + 7
*
* @param mu - interpolated sample position between 0 and 1.0
*
* @return - interpolated sample value
*/
public ComplexSample filter( ComplexSample[] samples, int offset, float mu )
{
/* Ensure we have enough samples in the array */
assert( samples.length >= offset + 7 );
/* Identify the filter bank that corresponds to mu */
int index = (int)( NSTEPS * mu );
float realAccumulator = ( TAPS[ index ][ 7 ] * samples[ offset ].real() );
realAccumulator += ( TAPS[ index ][ 6 ] * samples[ offset + 1 ].real() );
realAccumulator += ( TAPS[ index ][ 5 ] * samples[ offset + 2 ].real() );
realAccumulator += ( TAPS[ index ][ 4 ] * samples[ offset + 3 ].real() );
realAccumulator += ( TAPS[ index ][ 3 ] * samples[ offset + 4 ].real() );
realAccumulator += ( TAPS[ index ][ 2 ] * samples[ offset + 5 ].real() );
realAccumulator += ( TAPS[ index ][ 1 ] * samples[ offset + 6 ].real() );
realAccumulator += ( TAPS[ index ][ 0 ] * samples[ offset + 7 ].real() );
float imaginaryAccumulator = ( TAPS[ index ][ 7 ] * samples[ offset ].imaginary() );
imaginaryAccumulator += ( TAPS[ index ][ 6 ] * samples[ offset + 1 ].imaginary() );
imaginaryAccumulator += ( TAPS[ index ][ 5 ] * samples[ offset + 2 ].imaginary() );
imaginaryAccumulator += ( TAPS[ index ][ 4 ] * samples[ offset + 3 ].imaginary() );
imaginaryAccumulator += ( TAPS[ index ][ 3 ] * samples[ offset + 4 ].imaginary() );
imaginaryAccumulator += ( TAPS[ index ][ 2 ] * samples[ offset + 5 ].imaginary() );
imaginaryAccumulator += ( TAPS[ index ][ 1 ] * samples[ offset + 6 ].imaginary() );
imaginaryAccumulator += ( TAPS[ index ][ 0 ] * samples[ offset + 7 ].imaginary() );
return new ComplexSample( realAccumulator * mGain, imaginaryAccumulator * mGain );
}
}
<file_sep>package dsp.gain;
import sample.Listener;
import sample.complex.ComplexSample;
public class ComplexGain implements Listener<ComplexSample>
{
private float mGain;
private Listener<ComplexSample> mListener;
public ComplexGain( float gain )
{
mGain = gain;
}
@Override
public void receive( ComplexSample sample )
{
if( mListener != null )
{
sample.multiply( mGain );
mListener.receive( sample );
}
}
public void setListener( Listener<ComplexSample> listener )
{
mListener = listener;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.fleetsync2;
import alias.Alias;
import alias.AliasList;
import controller.activity.CallEvent;
import decode.DecoderType;
public class FleetsyncCallEvent extends CallEvent
{
public FleetsyncCallEvent( CallEventType callEventType,
AliasList aliasList,
String fromID,
String toID,
String details )
{
super( DecoderType.FLEETSYNC2, callEventType,
aliasList, fromID, toID, details );
}
private Alias getAlias( String ident )
{
if( hasAliasList() )
{
return getAliasList().getFleetsyncAlias( ident );
}
return null;
}
@Override
public Alias getFromIDAlias()
{
return getAlias( getFromID() );
}
@Override
public Alias getToIDAlias()
{
return getAlias( getToID() );
}
@Override
public String getChannel()
{
return null;
}
@Override
public long getFrequency()
{
return 0;
}
public static class Builder
{
/* Required parameters */
private CallEventType mCallEventType;
/* Optional parameters */
private AliasList mAliasList;
private String mFromID;
private String mToID;
private String mDetails;
public Builder( CallEventType callEventType )
{
mCallEventType = callEventType;
}
public Builder aliasList( AliasList aliasList )
{
mAliasList = aliasList;
return this;
}
public Builder from( String val )
{
mFromID = val;
return this;
}
public Builder details( String details )
{
mDetails = details;
return this;
}
public Builder to( String toID )
{
mToID = toID;
return this;
}
public FleetsyncCallEvent build()
{
return new FleetsyncCallEvent( this );
}
}
/**
* Private constructor for the builder
*/
private FleetsyncCallEvent( Builder builder )
{
this( builder.mCallEventType,
builder.mAliasList,
builder.mFromID,
builder.mToID,
builder.mDetails );
}
public static FleetsyncCallEvent
getFleetsync2Event( FleetsyncMessage message )
{
CallEventType type = CallEventType.UNKNOWN;
StringBuilder sbDetails = new StringBuilder();
sbDetails.append( "Fleetsync " );
switch( message.getMessageType() )
{
case ACKNOWLEDGE:
type = CallEventType.RESPONSE;
sbDetails.append( "ACK" );
break;
case ANI:
type = CallEventType.ID_ANI;
break;
case EMERGENCY:
type = CallEventType.EMERGENCY;
break;
case GPS:
type = CallEventType.GPS;
sbDetails.append( message.getGPSLocation() );
break;
case LONE_WORKER_EMERGENCY:
type = CallEventType.EMERGENCY;
sbDetails.append( "LONE WORKER EMERGENCY ALERT" );
break;
case PAGING:
type = CallEventType.PAGE;
break;
case STATUS:
type = CallEventType.STATUS;
sbDetails.append( "Status: " );
sbDetails.append( message.getStatus() );
if( message.getStatusAlias() != null )
{
sbDetails.append( "/" );
sbDetails.append( message.getStatusAlias().getName() );
}
break;
}
if( type == CallEventType.ID_ANI ||
type == CallEventType.EMERGENCY )
{
return new FleetsyncCallEvent.Builder( type )
.details( sbDetails.toString() )
.from( message.getFromID() )
.build();
}
else
{
return new FleetsyncCallEvent.Builder( type )
.details( sbDetails.toString() )
.from( message.getFromID() )
.to( message.getToID() )
.build();
}
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.reference.Encryption;
import decode.p25.reference.LinkControlOpcode;
public class ProtectionParameterBroadcast extends TDULinkControlMessage
{
private final static Logger mLog =
LoggerFactory.getLogger( ProtectionParameterBroadcast.class );
public final static int[] ALGORITHM_ID = { 112,113,114,115,116,117,118,119 };
public final static int[] KEY_ID = { 120,121,122,123,136,137,138,139,140,
141,142,143,144,145,146,147 };
public static final int[] TARGET_ADDRESS = { 160,161,162,163,164,165,166,
167,168,169,170,171,184,185,186,187,188,189,190,190,192,193,194,195 };
public ProtectionParameterBroadcast( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.PROTECTION_PARAMETER_BROADCAST.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " ENCRYPTION:" + getEncryption().name() );
sb.append( " KEY:" + getEncryptionKey() );
sb.append( " ADDRESSS:" + getTargetAddress() );
return sb.toString();
}
public Encryption getEncryption()
{
return Encryption.fromValue( mMessage.getInt( ALGORITHM_ID ) );
}
public int getEncryptionKey()
{
return mMessage.getInt( KEY_ID );
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
}
<file_sep>package gui.control;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.geom.Ellipse2D;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JSlider;
import javax.swing.SwingUtilities;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import sample.complex.ComplexSample;
import buffer.CircularBuffer;
public class ConstellationViewer extends JPanel
implements Listener<ComplexSample>
{
private static final long serialVersionUID = 1L;
private final static Logger mLog =
LoggerFactory.getLogger( ConstellationViewer.class );
private int mSampleRate;
private int mSymbolRate;
private float mSamplesPerSymbol;
private float mCounter = 0;
private float mOffset = 0;
private CircularBuffer<ComplexSample> mBuffer =
new CircularBuffer<ComplexSample>( 5000 );
private ComplexSample mPrevious = new ComplexSample( 1, 1 );
public ConstellationViewer( int sampleRate, int symbolRate )
{
mSampleRate = sampleRate;
mSymbolRate = symbolRate;
mSamplesPerSymbol = (float)mSampleRate / (float)mSymbolRate;
initGui();
}
private void initGui()
{
setPreferredSize( new Dimension( 200,200 ) );
addMouseListener( new MouseListener()
{
@Override
public void mouseClicked( MouseEvent e )
{
if( SwingUtilities.isRightMouseButton( e ) )
{
JPopupMenu menu = new JPopupMenu();
menu.add( new TimingOffsetItem( (int)( mSamplesPerSymbol * 10 ), (int)( mOffset * 10 ) ) );
menu.show( ConstellationViewer.this, e.getX(), e.getY() );
}
}
public void mouseReleased( MouseEvent e ) {}
public void mousePressed( MouseEvent e ) {}
public void mouseExited( MouseEvent e ) {}
public void mouseEntered( MouseEvent e ) {}
} );
}
@Override
public void receive( ComplexSample sample )
{
mBuffer.receive( sample );
ComplexSample angle = ComplexSample.multiply( sample, mPrevious.conjugate() );
repaint();
}
/**
* Sets the timing offset ( 0 <> SamplesPerSymbol ) for selecting which
* sample to plot, within the symbol timeframe. Values greater than the
* samples per symbol value will simply wrap or delay into the next symbol
* period.
*
* @param offset
*/
public void setOffset( float offset )
{
mOffset = offset;
repaint();
}
@Override
public void paintComponent( Graphics g )
{
super.paintComponent( g );
Graphics2D graphics = (Graphics2D) g;
graphics.setColor( Color.BLUE );
List<ComplexSample> samples = mBuffer.getElements();
double centerX = (double)getHeight() / 2.0d;
double centerY = (double)getWidth() / 2.0d;
double scale = 0.5d;
mCounter = 0;
for( ComplexSample sample: samples )
{
if( mCounter > ( mOffset + mSamplesPerSymbol ) )
{
/**
* Multiply the current sample against the complex conjugate of the
* previous sample to derive the phase delta between the two samples
*
* Negating the previous sample quadrature produces the conjugate
*/
double i = ( sample.inphase() * mPrevious.inphase() ) -
( sample.quadrature() * -mPrevious.quadrature() );
double q = ( sample.quadrature() * mPrevious.inphase() ) +
( sample.inphase() * -mPrevious.quadrature() );
double angle;
//Check for divide by zero
if( i == 0 )
{
angle = 0.0;
}
else
{
/**
* Use the arcus tangent of imaginary (q) divided by real (i) to
* get the phase angle (+/-) which was directly manipulated by the
* original message waveform during the modulation. This value now
* serves as the instantaneous amplitude of the demodulated signal
*/
double denominator = 1.0d / i;
angle = Math.atan( (double)q * denominator );
}
Ellipse2D.Double ellipse =
new Ellipse2D.Double( centerX - ( i * scale ),
centerY - ( q * scale ), 4, 4 );
graphics.draw( ellipse );
mCounter -= mSamplesPerSymbol;
}
mCounter++;
}
}
public class TimingOffsetItem extends JSlider implements ChangeListener
{
private static final long serialVersionUID = 1L;
public TimingOffsetItem( int maxValue, int currentValue )
{
super( JSlider.HORIZONTAL, 0, maxValue, currentValue );
setMajorTickSpacing( 10 );
setMinorTickSpacing( 5 );
setPaintTicks( true );
setPaintLabels( true );
addChangeListener( this );
}
@Override
public void stateChanged( ChangeEvent event )
{
int value = ((JSlider)event.getSource()).getValue();
setOffset( (float)value / 10.0f );
}
}
}
<file_sep>package decode.p25.message.filter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import message.Message;
import decode.p25.message.pdu.PDUMessage;
import decode.p25.reference.Opcode;
import filter.Filter;
import filter.FilterElement;
public class PDUMessageFilter extends Filter<Message>
{
private HashMap<Opcode,FilterElement<Opcode>> mOpcodeFilterElements =
new HashMap<Opcode,FilterElement<Opcode>>();
public PDUMessageFilter()
{
super( "PDU - Packet Data Unit" );
for( Opcode opcode: Opcode.values() )
{
mOpcodeFilterElements.put( opcode, new FilterElement<Opcode>( opcode ) );
}
}
@Override
public boolean passes( Message message )
{
if( mEnabled && message instanceof PDUMessage )
{
PDUMessage pdu = (PDUMessage)message;
Opcode opcode = pdu.getOpcode();
return mOpcodeFilterElements.get( opcode ).isEnabled();
}
return false;
}
@Override
public boolean canProcess( Message message )
{
return message instanceof PDUMessage;
}
@Override
public List<FilterElement<?>> getFilterElements()
{
return new ArrayList<FilterElement<?>>( mOpcodeFilterElements.values() );
}
}
<file_sep>package decode.p25.reference;
public enum IPProtocol
{
HOPOPT( 0, "IPV6 HOP-BY-HOP" ),
ICMP( 1, "ICMP" ),
IGMP( 2, "IGMP" ),
GGP( 3, "GGP" ),
IPinIP( 4, "IPinIP" ),
ST( 5, "ST" ),
TCP( 6, "TCP" ),
CBT( 7, "CBT" ),
EGP( 8, "EGP" ),
IGP( 9, "IGP" ),
BBN( 10, "BBN" ),
NVP( 11, "NVP" ),
PUP( 12, "PUP" ),
ARGUS( 13, "ARGUS" ),
EMCON( 14, "EMCON" ),
XNET( 15, "XNET" ),
CHAOS( 16, "CHAOS" ),
UDP( 17, "UDP" ),
MUX( 18, "MUX" ),
DCN( 19, "DCN" ),
HMP( 20, "HMP" ),
PRM( 21, "PRM" ),
XNS_IDP( 22, "XNS-IDP" ),
TRUNK_1( 23, "TRUNK-1" ),
TRUNK_2( 24, "TRUNK-2" ),
LEAF_1( 25, "LEAF-1" ),
LEAF_2( 26, "LEAF-2" ),
RDP( 27, "RDP" ),
IRTP( 28, "IRTP" ),
ISO_TP4( 29, "ISO-TP4" ),
NETBLT( 30, "NETBLT" ),
MFE_NSP( 31, "MFE-NSP" ),
MERIT_INP( 32, "MERIT-INP" ),
DCCP( 33, "DCCP" ),
_3PC( 34, "3PC" ),
IDPR( 35, "IDPR" ),
XTP( 36, "XTP" ),
DDP( 37, "DDP" ),
IDPR_CMTP( 38, "IDPR-CMTP" ),
TPPP( 39, "TP++" ),
IL( 40, "IL" ),
IPV6( 41, "IPV6" ),
SDRP( 42, "SDRP" ),
IPV6_ROUTE( 43, "IPV6-ROUTE" ),
IPV6_FRAG( 44, "IPV6-FRAG" ),
IDRP( 45, "IDRP" ),
RSVP( 46, "RSVP" ),
GRE( 47, "GRE" ),
MHRP( 48, "MHRP" ),
BNA( 49, "BNA" ),
ESP( 50, "ESP" ),
AH( 51, "AH" ),
INLSP( 52, "I-NLSP" ),
SWIPE( 53, "SWIPE" ),
NARP( 54, "NARP" ),
MOBILE( 55, "MOBILE" ),
TLSP( 56, "TLSP" ),
SKIP( 57, "SKIP" ),
IPV6_ICMP( 58, "IPV6-ICMP" ),
IPV6_NONXT( 59, "IPV6-NoNXT" ),
IPV6_OPTS( 60, "IPV6-OPTS" ),
ANY_HOST( 61, "ANY HOST" ),
CFTP( 62, "CFTP" ),
ANY_NETWORK( 63, "ANY NETWORK" ),
SAT_EXPAK( 64, "SAT_EXPAK" ),
KRYPTOLAN( 65, "KRYPTOLAN" ),
RVD( 66, "RVD" ),
IPPC( 67, "IPPC" ),
ANY_DIST( 68, "ANY DISTRIBUTED" ),
SAT_MON( 69, "SAT-MON" ),
VISA( 70, "VISA" ),
IPCU( 71, "IPCU" ),
CPNX( 72, "CPNX" ),
CPHB( 73, "CPHB" ),
WSN( 74, "WSN" ),
PVP( 75, "PVP" ),
BR_SAT_MON( 76, "BR-SAT-MON" ),
SUN_ND( 77, "SUN-ND" ),
WB_MON( 78, "WB-MON" ),
WB_EXPAK( 79, "WB-EXPAK" ),
ISO_IP( 80, "ISO-IP" ),
VMTP( 81, "VMTP" ),
SECURE_VMTP( 82, "SECURE-VMTP" ),
VINES( 83, "VINES" ),
TTP( 84, "TTP" ),
NSFNET_IGP( 85, "NSFNET-IGP" ),
DGP( 86, "DGP" ),
TCF( 87, "TCF" ),
EIGRP( 88, "EIGRP" ),
OSPF( 89, "OSPF" ),
SPRITE_RPC( 90, "SPRITE-RPC" ),
LARP( 91, "LARP" ),
MTP( 92, "MTP" ),
AX25( 93, "AX-25" ),
IPIP( 94, "IPIP" ),
MICP( 95, "MICP" ),
SCC_SP( 96, "SCC-SP" ),
ETHERIP( 97, "ETHER-IP" ),
ENCAP( 98, "ENCAP" ),
ANY_PRIVATE( 99, "ANY PRIVATE" ),
GMTP( 100, "GMTP" ),
IFMP( 101, "IFMP" ),
PNNI( 102, "PNNI" ),
PIM( 103, "PIM" ),
ARIS( 104, "ARIS" ),
SCPS( 105, "SCPS" ),
QNX( 106, "QNX" ),
A_N( 107, "A-N" ),
IPCOMP( 108, "IPCOMP" ),
SNP( 109, "SNP" ),
COMPAQ_PEER( 110, "COMPAQ-PEER" ),
IPXinIP( 111, "IPX-in-IP" ),
VRRP( 112, "VRRP" ),
PGM( 113, "PGM" ),
ANY_0_HOP( 114, "ANY 0-HOP" ),
L2TP( 115, "L2TP" ),
DDX( 116, "DDX" ),
IATP( 117, "IATP" ),
STP( 118, "STP" ),
SRP( 119, "SRP" ),
UTI( 120, "UTI" ),
SMP( 121, "SMP" ),
SM( 122, "SM" ),
PTP( 123, "PTP" ),
ISIS( 124, "IS-IS OVER IPV4" ),
FIRE( 125, "FIRE" ),
CRTP( 126, "CRTP" ),
CRUDP( 127, "CRUDP" ),
SSCOPMCE( 128, "SSCOPMCE" ),
IPLT( 129, "IPLT" ),
SPS( 130, "SPS" ),
PIPE( 131, "PIPE" ),
SCTP( 132, "SCTP" ),
FC( 133, "FC" ),
RSVP_E2E( 134, "RSVP E2E" ),
MOBILITY( 135, "MOBILITY HDR" ),
UDPLITE( 136, "UDP LITE" ),
MPLSinIP( 137, "MPLS-IN-IP" ),
MANET( 138, "MANET" ),
HIP( 139, "HIP" ),
SHIM6( 140, "SHIM6" ),
WESP( 141, "WESP" ),
ROHC( 142, "ROHC" ),
UNKNOWN( -1, "UNKNOWN" );
private int mValue;
private String mLabel;
private IPProtocol( int value, String label )
{
mValue = value;
mLabel = label;
}
public int getValue()
{
return mValue;
}
public String getLabel()
{
return mLabel;
}
public static IPProtocol fromValue( int value )
{
if( 0 <= value && value <= 142 )
{
return values()[ value ];
}
return IPProtocol.UNKNOWN;
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.ExtendedFunction;
import decode.p25.reference.Opcode;
public class ExtendedFunctionCommand extends TSBKMessage
{
public static final int[] EXTENDED_FUNCTION = { 80,81,82,83,84,85,86,87,
88,89,90,91,92,93,94,95 };
public static final int[] ARGUMENT = { 96,97,98,99,100,101,102,103,104,105,
106,107,108,109,110,111,112,113,114,115,116,117,118,119 };
public static final int[] TARGET_ADDRESS = { 120,121,122,123,124,125,126,
127,128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143 };
public ExtendedFunctionCommand( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.EXTENDED_FUNCTION_COMMAND.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " EXTENDED FUNCTION:" + getExtendedFunction().getLabel() );
sb.append( " ARGUMENT: " + getTargetAddress() );
sb.append( " TGT ADDR: " + getTargetAddress() );
return sb.toString();
}
public ExtendedFunction getExtendedFunction()
{
return ExtendedFunction.fromValue( mMessage.getInt( EXTENDED_FUNCTION ) );
}
public String getArgument()
{
return mMessage.getHex( ARGUMENT, 6 );
}
public String getSourceAddress()
{
switch( getExtendedFunction() )
{
case RADIO_CHECK:
case RADIO_CHECK_ACK:
case RADIO_DETACH:
case RADIO_DETACH_ACK:
case RADIO_INHIBIT:
case RADIO_INHIBIT_ACK:
case RADIO_UNINHIBIT:
case RADIO_UNINHIBIT_ACK:
return getArgument();
default:
break;
}
return null;
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
@Override
public String getToID()
{
return getTargetAddress();
}
}
<file_sep>package decode.p25.message.tsbk.osp.voice;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.UnitChannelGrant;
import decode.p25.message.tsbk.osp.control.IdentifierUpdate;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
public class UnitToUnitVoiceChannelGrant extends UnitChannelGrant
{
public UnitToUnitVoiceChannelGrant( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.UNIT_TO_UNIT_VOICE_CHANNEL_GRANT.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
if( isEmergency() )
{
sb.append( " EMERGENCY" );
}
sb.append( " SOURCE UNIT:" );
sb.append( getSourceAddress() );
sb.append( " TARGET UNIT:" );
sb.append( getTargetAddress() );
sb.append( " CHAN:" + getChannelIdentifier() + "-" + getChannelNumber() );
sb.append( " DN:" + getDownlinkFrequency() );
sb.append( " UP:" + getUplinkFrequency() );
return sb.toString();
}
}
<file_sep>package decode.p25.message.ldu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.ldu.LDU1Message;
import decode.p25.reference.LinkControlOpcode;
public class AdjacentSiteStatusBroadcastExplicit extends LDU1Message
{
private final static Logger mLog =
LoggerFactory.getLogger( AdjacentSiteStatusBroadcastExplicit.class );
public static final int[] LRA = { 364,365,366,367,372,373,374,375 };
public static final int[] TRANSMIT_IDENTIFIER = { 376,377,382,383 };
public static final int[] TRANSMIT_CHANNEL = { 384,385,386,387,536,537,538,
539,540,541,546,547 };
public static final int[] RFSS_ID = { 548,549,550,551,556,557,558,559 };
public static final int[] SITE_ID = { 560,561,566,567,568,569,570,571 };
public static final int[] RECEIVE_IDENTIFIER = { 720,721,722,723 };
public static final int[] RECEIVE_CHANNEL = { 724,725,730,731,732,733,734,
735,740,741,742,743 };
public AdjacentSiteStatusBroadcastExplicit( LDU1Message message )
{
super( message );
}
@Override
public String getEventType()
{
return LinkControlOpcode.ADJACENT_SITE_STATUS_BROADCAST_EXPLICIT.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " LRA:" + getLocationRegistrationArea() );
sb.append( " SITE:" + getRFSubsystemID() + "-" + getSiteID() );
sb.append( " DNLINK:" + getTransmitChannelNumber() );
sb.append( " UPLINK:" + getReceiveChannelNumber() );
return sb.toString();
}
public String getLocationRegistrationArea()
{
return mMessage.getHex( LRA, 2 );
}
public String getRFSubsystemID()
{
return mMessage.getHex( RFSS_ID, 2 );
}
public String getSiteID()
{
return mMessage.getHex( SITE_ID, 2 );
}
public int getTransmitIdentifier()
{
return mMessage.getInt( TRANSMIT_IDENTIFIER );
}
public int getTransmitChannel()
{
return mMessage.getInt( TRANSMIT_CHANNEL );
}
public String getTransmitChannelNumber()
{
return getTransmitIdentifier() + "-" + getTransmitChannel();
}
public int getReceiveIdentifier()
{
return mMessage.getInt( RECEIVE_IDENTIFIER );
}
public int getReceiveChannel()
{
return mMessage.getInt( RECEIVE_CHANNEL );
}
public String getReceiveChannelNumber()
{
return getReceiveIdentifier() + "-" + getReceiveChannel();
}
}
<file_sep>package bits;
public class SoftSyncDetector implements ISyncProcessor
{
private ISyncDetectListener mListener;
private long mPattern;
private int mThreshold;
public SoftSyncDetector( ISyncDetectListener listener, long pattern, int threshold )
{
this( pattern, threshold );
mListener = listener;
}
public SoftSyncDetector( long pattern, int threshold )
{
mPattern = pattern;
mThreshold = threshold;
}
@Override
public void checkSync( long value )
{
long difference = value ^ mPattern;
if( ( difference == 0 || Long.bitCount( difference ) <= mThreshold ) &&
mListener != null )
{
mListener.syncDetected();
}
}
public void setThreshold( int threshold )
{
mThreshold = threshold;
}
public void setListener( ISyncDetectListener listener )
{
mListener = listener;
}
}
<file_sep>package decode.p25.message.tdu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.P25Message.DuplexMode;
import decode.p25.message.P25Message.SessionMode;
import decode.p25.reference.LinkControlOpcode;
public class GroupVoiceChannelUpdateExplicit extends TDULinkControlMessage
implements IdentifierReceiver
{
private final static Logger mLog =
LoggerFactory.getLogger( GroupVoiceChannelUpdateExplicit.class );
public static final int EMERGENCY_FLAG = 92;
public static final int ENCRYPTED_CHANNEL_FLAG = 93;
public static final int DUPLEX_MODE = 94;
public static final int SESSION_MODE = 95;
public static final int[] GROUP_ADDRESS = { 112,113,114,115,116,117,118,
119,120,121,122,123,136,137,138,139 };
public static final int[] TRANSMIT_IDENTIFIER = { 140,141,142,143 };
public static final int[] TRANSMIT_CHANNEL = { 144,145,146,147,160,161,162,
163,164,165,166,167 };
public static final int[] RECEIVE_IDENTIFIER = { 168,169,170,171 };
public static final int[] RECEIVE_CHANNEL = { 184,185,186,187,188,189,190,
191,192,193,194,195,196,197,198,199 };
private IBandIdentifier mTransmitIdentifierUpdate;
private IBandIdentifier mReceiveIdentifierUpdate;
public GroupVoiceChannelUpdateExplicit( TDULinkControlMessage source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.GROUP_VOICE_CHANNEL_UPDATE_EXPLICIT.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
if( isEmergency() )
{
sb.append( " EMERGENCY" );
}
if( isEncryptedChannel() )
{
sb.append( " ENCRYPTED CHANNEL" );
}
return sb.toString();
}
public boolean isEmergency()
{
return mMessage.get( EMERGENCY_FLAG );
}
public boolean isEncryptedChannel()
{
return mMessage.get( ENCRYPTED_CHANNEL_FLAG );
}
public DuplexMode getDuplexMode()
{
return mMessage.get( DUPLEX_MODE ) ? DuplexMode.FULL : DuplexMode.HALF;
}
public SessionMode getSessionMode()
{
return mMessage.get( SESSION_MODE ) ?
SessionMode.CIRCUIT : SessionMode.PACKET;
}
public int getTransmitChannelIdentifier()
{
return mMessage.getInt( TRANSMIT_IDENTIFIER );
}
public int getTransmitChannelNumber()
{
return mMessage.getInt( TRANSMIT_CHANNEL );
}
public String getTransmitChannel()
{
return getTransmitChannelIdentifier() + "-" + getTransmitChannelNumber();
}
public int getReceiveChannelIdentifier()
{
return mMessage.getInt( RECEIVE_IDENTIFIER );
}
public int getReceiveChannelNumber()
{
return mMessage.getInt( RECEIVE_CHANNEL );
}
public String getReceiveChannel()
{
return getReceiveChannelIdentifier() + "-" + getReceiveChannelNumber();
}
public String getGroupAddress()
{
return mMessage.getHex( GROUP_ADDRESS, 4 );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
if( identifier == getTransmitChannelIdentifier() )
{
mTransmitIdentifierUpdate = message;
}
if( identifier == getReceiveChannelIdentifier() )
{
mReceiveIdentifierUpdate = message;
}
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 2 ];
identifiers[ 0 ] = getTransmitChannelIdentifier();
identifiers[ 1 ] = getReceiveChannelIdentifier();
return identifiers;
}
public long getDownlinkFrequency()
{
return calculateDownlink( mTransmitIdentifierUpdate,
getTransmitChannelNumber() );
}
public long getUplinkFrequency()
{
return calculateUplink( mReceiveIdentifierUpdate,
getReceiveChannelNumber() );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 controller.activity;
import java.awt.EventQueue;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.LinkedList;
import javax.swing.table.AbstractTableModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Broadcaster;
import sample.Listener;
import controller.activity.CallEvent.CallEventType;
public class CallEventModel extends AbstractTableModel
{
private static final long serialVersionUID = 1L;
private final static Logger mLog =
LoggerFactory.getLogger( CallEventModel.class );
private static DecimalFormat mFrequencyFormatter =
new DecimalFormat( "0.000000" );
private static final int DEFAULT_ICON_HEIGHT = 14;
public static final int TIME = 0;
public static final int EVENT = 1;
public static final int FROM_ID = 2;
public static final int FROM_ALIAS = 3;
public static final int TO_ID = 4;
public static final int TO_ALIAS = 5;
public static final int CHANNEL = 6;
public static final int FREQUENCY = 7;
public static final int DETAILS = 8;
protected int mMaxMessages = 500;
protected LinkedList<CallEvent> mEvents = new LinkedList<CallEvent>();
protected String[] mHeaders = new String[] { "Time",
"Event",
"From",
"Alias",
"To",
"Alias",
"Channel",
"Frequency",
"Details" };
private SimpleDateFormat mSDFTime = new SimpleDateFormat( "HH:mm:ss" );
private Broadcaster<CallEvent> mBroadcaster = new Broadcaster<CallEvent>();
private boolean mNewMessagesFirst = true;
public CallEventModel()
{
}
public void dispose()
{
synchronized( mEvents )
{
mEvents.clear();
}
mBroadcaster.dispose();
}
public void flush()
{
/* Flush all events to listeners ( normally the call event logger ) */
synchronized( mEvents )
{
for( CallEvent event: mEvents )
{
mBroadcaster.receive( event );
}
}
}
public int getMaxMessageCount()
{
return mMaxMessages;
}
public void setMaxMessageCount( int count )
{
mMaxMessages = count;
}
public void add( final CallEvent event )
{
try
{
synchronized ( mEvents )
{
mEvents.addFirst( event );
}
fireTableRowsInserted( 0, 0 );
prune();
}
catch( Exception e )
{
e.printStackTrace();
}
}
public void remove( final CallEvent event )
{
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
synchronized ( mEvents )
{
final int row = mEvents.indexOf( event );
mEvents.remove( event );
if( row != -1 )
{
fireTableRowsDeleted( row, row );
}
}
}
} );
}
public int indexOf( CallEvent event )
{
return mEvents.indexOf( event );
}
public void setEnd( final CallEvent event )
{
try
{
EventQueue.invokeAndWait( new Runnable()
{
@Override
public void run()
{
if( event != null )
{
event.setEnd( System.currentTimeMillis() );
synchronized ( mEvents )
{
int row = indexOf( event );
if( row != -1 )
{
fireTableCellUpdated( row, TIME );
}
}
}
else
{
mLog.error( "CallEventModel - couldn't log end time - event was null" );
}
}
} );
}
catch( Exception e )
{
e.printStackTrace();
}
}
public void setFromID( final CallEvent event, final String from )
{
EventQueue.invokeLater( new Runnable()
{
@Override
public void run()
{
try
{
if( event != null )
{
event.setFromID( from );
synchronized ( mEvents )
{
int row = indexOf( event );
if( row != -1 )
{
fireTableCellUpdated( row, FROM_ID );
fireTableCellUpdated( row, FROM_ALIAS );
}
else
{
mLog.error( "CallEventModel - tried to set from ID on "
+ "call event - couldn't find index of event" );
}
}
}
}
catch( Exception e )
{
e.printStackTrace();
}
}
} );
}
private void prune()
{
synchronized( mEvents )
{
while( mEvents.size() > mMaxMessages )
{
CallEvent event = mEvents.removeLast();
mBroadcaster.receive( event );
fireTableRowsDeleted( mEvents.size(), mEvents.size() );
}
}
}
@Override
public int getRowCount()
{
return mEvents.size();
}
@Override
public int getColumnCount()
{
return mHeaders.length;
}
public String getColumnName( int column )
{
return mHeaders[ column ];
}
@Override
public Object getValueAt( int rowIndex, int columnIndex )
{
synchronized( mEvents )
{
switch( columnIndex )
{
case TIME:
StringBuilder sb = new StringBuilder();
sb.append( mSDFTime.format(
mEvents.get( rowIndex ).getEventStartTime() ) );
if( mEvents.get( rowIndex ).getEventEndTime() != 0 )
{
sb.append( " - " );
sb.append( mSDFTime.format(
mEvents.get( rowIndex ).getEventEndTime() ) );
}
else if( mEvents.get( rowIndex )
.getCallEventType() == CallEventType.CALL )
{
sb.append( " - In Progress" );
}
return sb.toString();
case EVENT:
return mEvents.get( rowIndex ).getCallEventType();
case FROM_ID:
return mEvents.get( rowIndex ).getFromID();
case FROM_ALIAS:
return mEvents.get( rowIndex ).getFromIDAlias();
case TO_ID:
return mEvents.get( rowIndex ).getToID();
case TO_ALIAS:
return mEvents.get( rowIndex ).getToIDAlias();
case CHANNEL:
return mEvents.get( rowIndex ).getChannel();
case FREQUENCY:
long frequency = mEvents.get( rowIndex ).getFrequency();
if( frequency != 0 )
{
return mFrequencyFormatter.format( (double)frequency / 1E6d );
}
else
{
return null;
}
case DETAILS:
return mEvents.get( rowIndex ).getDetails();
}
}
return null;
}
public void addListener( Listener<CallEvent> listener )
{
mBroadcaster.addListener( listener );
}
public void removeListener( Listener<CallEvent> listener )
{
mBroadcaster.removeListener( listener );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 settings;
import java.awt.Color;
import java.awt.Image;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import javax.swing.ImageIcon;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import map.DefaultIcon;
import map.MapIcon;
import org.jdesktop.swingx.mapviewer.GeoPosition;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import properties.SystemProperties;
import settings.ColorSetting.ColorSettingName;
import source.recording.RecordingConfiguration;
import source.tuner.TunerConfiguration;
import source.tuner.TunerConfigurationAssignment;
import source.tuner.TunerType;
import source.tuner.fcd.proV1.FCD1TunerConfiguration;
import source.tuner.fcd.proplusV2.FCD2TunerConfiguration;
import source.tuner.hackrf.HackRFTunerConfiguration;
import source.tuner.rtl.e4k.E4KTunerConfiguration;
import source.tuner.rtl.r820t.R820TTunerConfiguration;
public class SettingsManager
{
private final static Logger mLog =
LoggerFactory.getLogger( SettingsManager.class );
private Settings mSettings = new Settings();
private ArrayList<SettingChangeListener> mListeners =
new ArrayList<SettingChangeListener>();
public static final String DEFAULT_ICON = "No Icon";
public String mCurrentDefaultIconName = DEFAULT_ICON;
private HashMap<String,MapIcon> mIcons = new HashMap<String,MapIcon>();
private HashMap<String,ImageIcon> mResizedIcons =
new HashMap<String,ImageIcon>();
public SettingsManager()
{
init();
}
/**
* Loads settings from the current settings file, or the default settings file,
* as specified in the current SDRTrunk system settings
*/
private void init()
{
SystemProperties props = SystemProperties.getInstance();
Path settingsFolder = props.getApplicationFolder( "settings" );
String defaultSettingsFile =
props.get( "settings.defaultFilename", "settings.xml" );
String settingsFile =
props.get( "settings.currentFilename", defaultSettingsFile );
load( settingsFolder.resolve( settingsFile ) );
refreshIcons();
}
/**
* Reloads the icon hash map, and sets up the default iconology. If the
* saved default icon name is not part of the current set of icons, we
* set the default icon to the standard system default name, which should
* be guaranteed to be available.
*/
public void refreshIcons()
{
mIcons.clear();
mCurrentDefaultIconName = DEFAULT_ICON;
DefaultIcon defaultIcon = getDefaultIcon();
ArrayList<MapIcon> icons = mSettings.getMapIcons();
icons.addAll( getStandardIcons() );
for( MapIcon icon: icons )
{
mIcons.put( icon.getName(), icon );
if( icon.getName().contentEquals( defaultIcon.getName() ) )
{
mCurrentDefaultIconName = defaultIcon.getName();
icon.setDefaultIcon( true );
}
else
{
icon.setDefaultIcon( false );
}
}
}
public Settings getSettings()
{
return mSettings;
}
public void setSettings( Settings settings )
{
mSettings = settings;
}
public Setting getSetting( String name )
{
return mSettings.getSetting( name );
}
/**
* Returns the current setting, or if the setting doesn't exist
* returns a newly created setting with the specified parameters
*/
public ColorSetting getColorSetting( ColorSettingName name )
{
ColorSetting setting = mSettings.getColorSetting( name );
if( setting == null )
{
setting = new ColorSetting( name );
addSetting( setting );
}
return setting;
}
/**
* Fetches the current setting and applies the parameter(s) to it. Creates
* the setting if it does not exist
*/
public void setColorSetting( ColorSettingName name, Color color )
{
ColorSetting setting = getColorSetting( name );
setting.setColor( color );
broadcastSettingChange( setting );
save();
}
public void resetColorSetting( ColorSettingName name )
{
setColorSetting( name, name.getDefaultColor() );
}
public void resetAllColorSettings()
{
for( ColorSetting color: mSettings.getColorSettings() )
{
resetColorSetting( color.getColorSettingName() );
}
}
/**
* Returns the current setting, or if the setting doesn't exist
* returns a newly created setting with the specified parameters
*/
public FileSetting getFileSetting( String name, String defaultPath )
{
FileSetting setting = mSettings.getFileSetting( name );
if( setting == null )
{
setting = new FileSetting( name, defaultPath );
addSetting( setting );
}
return setting;
}
/**
* Fetches the current setting and applies the parameter(s) to it. Creates
* the setting if it does not exist
*/
public void setFileSetting( String name, String path )
{
FileSetting setting = getFileSetting( name, path );
setting.setPath( path );
broadcastSettingChange( setting );
save();
}
public MapIcon[] getMapIcons()
{
MapIcon[] returnIcons = new MapIcon[mIcons.values().size() ];
return mIcons.values().toArray( returnIcons );
}
private ArrayList<MapIcon> getStandardIcons()
{
ArrayList<MapIcon> icons = new ArrayList<MapIcon>();
MapIcon defaultIcon = new MapIcon( DEFAULT_ICON, "images/no_icon.png", false );
icons.add( defaultIcon );
MapIcon ambulance =
new MapIcon( "Ambulance", "images/ambulance.png", false );
icons.add( ambulance );
MapIcon blockTruck =
new MapIcon( "Block Truck", "images/concrete_block_truck.png", false );
icons.add( blockTruck );
MapIcon cwid = new MapIcon( "CWID", "images/cwid.png", false );
icons.add( cwid );
MapIcon dispatcher =
new MapIcon( "Dispatcher", "images/dispatcher.png", false );
icons.add( dispatcher );
MapIcon dumpTruck =
new MapIcon( "Dump Truck", "images/dump_truck_red.png", false );
icons.add( dumpTruck );
MapIcon fireTruck =
new MapIcon( "Fire Truck", "images/fire_truck.png", false );
icons.add( fireTruck );
MapIcon garbageTruck =
new MapIcon( "Garbage Truck", "images/garbage_truck.png", false );
icons.add( garbageTruck );
MapIcon loader = new MapIcon( "Loader", "images/loader.png", false );
icons.add( loader );
MapIcon police =
new MapIcon( "Police", "images/police.png", false );
icons.add( police );
MapIcon propaneTruck =
new MapIcon( "Propane Truck", "images/propane_truck.png", false );
icons.add( propaneTruck );
MapIcon rescueTruck =
new MapIcon( "Rescue Truck", "images/rescue_truck.png", false );
icons.add( rescueTruck );
MapIcon schoolBus =
new MapIcon( "School Bus", "images/school_bus.png", false );
icons.add( schoolBus );
MapIcon taxi =
new MapIcon( "Taxi", "images/taxi.png", false );
icons.add( taxi );
MapIcon train =
new MapIcon( "Train", "images/train.png", false );
icons.add( train );
MapIcon transportBus =
new MapIcon( "Transport Bus", "images/opt_bus.png", false );
icons.add( transportBus );
MapIcon van =
new MapIcon( "Van", "images/van.png", false );
icons.add( van );
return icons;
}
/**
* Deletes the map icon
*/
public void deleteMapIcon( MapIcon icon )
{
MapIcon existing = mIcons.get( icon.getName() );
if( existing != null )
{
mIcons.remove( icon.getName() );
mSettings.removeSetting( existing );
broadcastSettingDeleted( existing );
save();
}
}
/**
* Adds the icon, overwriting any existing icon with the same name
* @param icon
*/
public void addMapIcon( MapIcon icon )
{
MapIcon existing = mIcons.get( icon.getName() );
if( existing == null )
{
MapIcon newIcon = new MapIcon( icon.getName(), icon.getPath() );
mIcons.put( newIcon.getName(), newIcon );
addSetting( newIcon );
}
else
{
existing.setName( icon.getName() );
existing.setPath( icon.getPath() );
broadcastSettingChange( existing );
save();
}
}
public void updatMapIcon( MapIcon icon, String newName, String newPath )
{
MapIcon existing = mSettings.getMapIcon( icon.getName() );
if( existing == null )
{
addMapIcon( new MapIcon( newName, newPath ) );
}
else
{
existing.setName( newName );
existing.setPath( newPath );
broadcastSettingChange( existing );
save();
}
}
/**
* Returns named map icon scaled to height, if necessary.
* @param name - name of icon
* @param heigh - height of icon in pixels
*
* @return - ImageIcon or null
*/
public ImageIcon getImageIcon( String name, int height )
{
String mergedName = name + height;
if( mResizedIcons.containsKey( mergedName ) )
{
return mResizedIcons.get( mergedName );
}
MapIcon mapIcon = mIcons.get( name );
if( mapIcon != null )
{
if( mapIcon.getImageIcon().getIconHeight() > height )
{
ImageIcon scaled = getScaledIcon( mapIcon.getImageIcon(), height );
mResizedIcons.put( mergedName, scaled );
return scaled;
}
else
{
mResizedIcons.put( mergedName, mapIcon.getImageIcon() );
}
}
/* Use the default Icon */
String mergedDefault = mCurrentDefaultIconName + height;
if( mResizedIcons.containsKey( mergedDefault ) )
{
return mResizedIcons.get( mergedDefault );
}
else
{
MapIcon defaultIcon = mIcons.get( mCurrentDefaultIconName );
if( defaultIcon != null )
{
if( defaultIcon.getImageIcon().getIconHeight() > height )
{
ImageIcon scaledDefault = getScaledIcon( defaultIcon.getImageIcon(), height );
mResizedIcons.put( mergedDefault, scaledDefault );
return scaledDefault;
}
else
{
mResizedIcons.put( mergedDefault, defaultIcon.getImageIcon() );
return defaultIcon.getImageIcon();
}
}
}
/* Something happened ... the above should always return an icon */
mLog.error( "SettingsManager - couldn't return an icon named [" +
name + "] of heigh [" + height + "]" );
return null;
}
private ImageIcon getScaledIcon( ImageIcon original, int height )
{
double scale = (double)original.getIconHeight() / (double)height;
int scaledWidth = (int)( (double)original.getIconWidth() / scale );
Image scaledImage = original.getImage().getScaledInstance( scaledWidth,
height, java.awt.Image.SCALE_SMOOTH );
return new ImageIcon( scaledImage );
}
public MapIcon getMapIcon( String name )
{
if( mIcons.containsKey( name ) )
{
return mIcons.get( name );
}
/* Return the default */
if( mIcons.containsKey( mCurrentDefaultIconName ) )
{
return mIcons.get( mCurrentDefaultIconName );
}
/* Return the real default */
return mIcons.get( DEFAULT_ICON );
}
/**
* Returns the named map icon, or creates it with the default path
* @param name - name of the icon
* @param defaultPath - path to icon image file
* @return - map icon
*/
public MapIcon getMapIcon( String name, String defaultPath )
{
MapIcon icon = mSettings.getMapIcon( name );
if( icon == null )
{
icon = new MapIcon( name, defaultPath );
addSetting( icon );
}
return icon;
}
public DefaultIcon getDefaultIcon()
{
DefaultIcon icon = mSettings.getDefaultIcon();
if( icon == null )
{
icon = new DefaultIcon( DEFAULT_ICON );
addSetting( icon );
}
return icon;
}
public void setDefaultIcon( MapIcon icon )
{
if( mIcons.containsValue( icon ) )
{
MapIcon currentDefault = mIcons.get( mCurrentDefaultIconName );
currentDefault.setDefaultIcon( false );
icon.setDefaultIcon( true );
mCurrentDefaultIconName = icon.getName();
DefaultIcon defaultIconSetting = getDefaultIcon();
defaultIconSetting.setName( icon.getName() );
save();
broadcastSettingChange( defaultIconSetting );
}
}
/**
* Adds the setting and stores the set of settings
* @param setting
*/
private void addSetting( Setting setting )
{
mSettings.addSetting( setting );
save();
broadcastSettingChange( setting );
}
public ArrayList<RecordingConfiguration> getRecordingConfigurations()
{
return mSettings.getRecordingConfigurations();
}
public void addRecordingConfiguration( RecordingConfiguration config )
{
mSettings.addRecordingConfiguration( config );
save();
}
public void removeRecordingConfiguration( RecordingConfiguration config )
{
mSettings.removeRecordingConfiguration( config );
save();
}
public ArrayList<TunerConfiguration> getTunerConfigurations( TunerType type )
{
ArrayList<TunerConfiguration> configs = getSettings()
.getTunerConfigurations( type );
if( configs.isEmpty() )
{
configs.add( addNewTunerConfiguration( type, "Default" ) );
}
return configs;
}
public void deleteTunerConfiguration( TunerConfiguration config )
{
getSettings().removeTunerConfiguration( config );
save();
}
public TunerConfiguration addNewTunerConfiguration( TunerType type,
String name )
{
switch( type )
{
case ELONICS_E4000:
E4KTunerConfiguration e4KConfig =
new E4KTunerConfiguration( name );
getSettings().addTunerConfiguration( e4KConfig );
save();
return e4KConfig;
case FUNCUBE_DONGLE_PRO:
FCD1TunerConfiguration config =
new FCD1TunerConfiguration( name );
getSettings().addTunerConfiguration( config );
save();
return config;
case FUNCUBE_DONGLE_PRO_PLUS:
FCD2TunerConfiguration configPlus =
new FCD2TunerConfiguration( name );
getSettings().addTunerConfiguration( configPlus );
save();
return configPlus;
case HACKRF:
HackRFTunerConfiguration hackConfig =
new HackRFTunerConfiguration( name );
getSettings().addTunerConfiguration( hackConfig );
save();
return hackConfig;
case RAFAELMICRO_R820T:
R820TTunerConfiguration r820TConfig =
new R820TTunerConfiguration( name );
getSettings().addTunerConfiguration( r820TConfig );
save();
return r820TConfig;
default:
throw new IllegalArgumentException( "TunerConfiguration"
+ "Directory - tuner type is unrecognized [" +
type.toString() + "]" );
}
}
public TunerConfigurationAssignment getSelectedTunerConfiguration(
TunerType type, String address )
{
return mSettings.getConfigurationAssignment( type, address );
}
public void setSelectedTunerConfiguration( TunerType type,
String address, TunerConfiguration config )
{
mSettings.setConfigurationAssignment( type, address, config.getName() );
save();
}
public MapViewSetting getMapViewSetting( String name, GeoPosition position, int zoom )
{
MapViewSetting loc = mSettings.getMapViewSetting( name );
if( loc != null )
{
return loc;
}
else
{
MapViewSetting newLoc = new MapViewSetting( name, position, zoom );
addSetting( newLoc );
return newLoc;
}
}
public void setMapViewSetting( String name, GeoPosition position, int zoom )
{
MapViewSetting loc = getMapViewSetting( name, position, zoom );
loc.setGeoPosition( position );
loc.setZoom( zoom );
save();
}
public void save()
{
JAXBContext context = null;
SystemProperties props = SystemProperties.getInstance();
Path settingsPath = props.getApplicationFolder( "settings" );
String settingsDefault = props.get( "settings.defaultFilename",
"settings.xml" );
String settingsCurrent = props.get( "settings.currentFilename",
settingsDefault );
Path filePath = settingsPath.resolve( settingsCurrent );
File outputFile = new File( filePath.toString() );
try
{
if( !outputFile.exists() )
{
outputFile.createNewFile();
}
}
catch( Exception e )
{
mLog.error( "SettingsManager - couldn't create file to save "
+ "settings [" + filePath.toString() + "]", e );
}
OutputStream out = null;
try
{
out = new FileOutputStream( outputFile );
try
{
context = JAXBContext.newInstance( Settings.class );
Marshaller m = context.createMarshaller();
m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, true );
m.marshal( mSettings, out );
}
catch ( JAXBException e )
{
mLog.error( "SettingsManager - jaxb exception while saving " +
"settings", e );
}
}
catch ( Exception e )
{
mLog.error( "SettingsManager - coulcn't open outputstream to " +
"save settings [" + filePath.toString() + "]" );
}
finally
{
if( out != null )
{
try
{
out.close();
}
catch ( IOException e )
{
e.printStackTrace();
}
}
}
}
/**
* Erases current settings and loads settings from the settingsPath filename,
* if it exists.
*/
public void load( Path settingsPath )
{
if( Files.exists( settingsPath ) )
{
mLog.info( "SettingsManager - loading settings file [" +
settingsPath.toString() + "]" );
JAXBContext context = null;
InputStream in = null;
try
{
in = new FileInputStream( settingsPath.toString() );
try
{
context = JAXBContext.newInstance( Settings.class );
Unmarshaller m = context.createUnmarshaller();
mSettings = (Settings)m.unmarshal( in );
}
catch ( JAXBException e )
{
mLog.error( "SettingsManager - jaxb exception while loading " +
"settings", e );
}
}
catch ( Exception e )
{
mLog.error( "SettingsManager - coulcn't open inputstream to " +
"load settings [" + settingsPath.toString() + "]", e );
}
finally
{
if( in != null )
{
try
{
in.close();
}
catch ( IOException e )
{
mLog.error( "SettingsManager - exception while closing " +
"the settings file inputstream reader", e );
}
}
}
}
else
{
mLog.info( "SettingsManager - settings does not exist [" +
settingsPath.toString() + "]" );
}
if( mSettings == null )
{
mSettings = new Settings();
}
}
public void broadcastSettingChange( Setting setting )
{
Iterator<SettingChangeListener> it = mListeners.iterator();
while( it.hasNext() )
{
SettingChangeListener listener = it.next();
if( listener == null )
{
it.remove();
}
else
{
listener.settingChanged( setting );
}
}
}
public void broadcastSettingDeleted( Setting setting )
{
Iterator<SettingChangeListener> it = mListeners.iterator();
while( it.hasNext() )
{
SettingChangeListener listener = it.next();
if( listener == null )
{
it.remove();
}
else
{
listener.settingDeleted( setting );
}
}
}
public void addListener( SettingChangeListener listener )
{
mListeners.add( listener );
}
public void removeListener( SettingChangeListener listener )
{
mListeners.remove( listener );
}
}
<file_sep>package filter;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import javax.swing.JCheckBox;
import javax.swing.JLabel;
import javax.swing.JMenuItem;
import javax.swing.JPanel;
import javax.swing.JPopupMenu;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.event.CellEditorListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeCellRenderer;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreeCellEditor;
import javax.swing.tree.TreeSelectionModel;
import net.miginfocom.swing.MigLayout;
public class FilterEditorPanel<T> extends JPanel
{
private static final long serialVersionUID = 1L;
private JTree mTree;
private DefaultTreeModel mModel;
private FilterSet<T> mFilterSet;
public FilterEditorPanel( FilterSet<T> filterSet )
{
setLayout( new MigLayout("insets 0 0 0 0", "[grow,fill]", "[grow,fill]") );
mFilterSet = filterSet;
init();
}
private void init()
{
DefaultMutableTreeNode root = new DefaultMutableTreeNode( mFilterSet );
mModel = new DefaultTreeModel( root );
addFilterSet( mFilterSet, root );
mTree = new JTree( mModel );
mTree.setShowsRootHandles( true );
mTree.addMouseListener( new MouseHandler() );
mTree.getSelectionModel().setSelectionMode(
TreeSelectionModel.SINGLE_TREE_SELECTION );
mTree.setCellRenderer( new EditorTreeCellRenderer() );
mTree.setCellEditor( new FilterTreeNodeEditor() );
mTree.setEditable( true );
add( mTree );
}
private void addFilterSet( FilterSet<T> filterSet, DefaultMutableTreeNode parent )
{
List<IFilter<T>> filters = filterSet.getFilters();
/* sort the filters in alphabetical order by name */
Collections.sort( filters, new Comparator<IFilter<?>>()
{
@Override
public int compare( IFilter<?> first, IFilter<?> second )
{
return first.getName().compareTo( second.getName() );
}
});
for( IFilter<T> filter: filters )
{
DefaultMutableTreeNode child = new DefaultMutableTreeNode( filter );
mModel.insertNodeInto( child, parent, parent.getChildCount() );
if( filter instanceof FilterSet )
{
addFilterSet( (FilterSet<T>)filter, child );
}
else if( filter instanceof Filter )
{
addFilter( (Filter<T>)filter, child );
}
}
}
private void addFilter( Filter<T> filter, DefaultMutableTreeNode parent )
{
List<FilterElement<?>> elements = filter.getFilterElements();
Collections.sort( elements, new Comparator<FilterElement<?>>()
{
@Override
public int compare( FilterElement<?> o1, FilterElement<?> o2 )
{
return o1.toString().compareTo( o2.toString() );
}
} );
for( FilterElement<?> element: elements )
{
DefaultMutableTreeNode child = new DefaultMutableTreeNode( element );
mModel.insertNodeInto( child, parent, parent.getChildCount() );
}
}
public class MouseHandler implements MouseListener
{
public MouseHandler()
{
}
@Override
public void mouseClicked( MouseEvent event )
{
if( SwingUtilities.isRightMouseButton( event ) )
{
int row = mTree.getRowForLocation( event.getX(),
event.getY() );
if( row != -1 )
{
mTree.setSelectionRow( row );
Object selectedNode =
mTree.getLastSelectedPathComponent();
if( selectedNode instanceof DefaultMutableTreeNode )
{
final DefaultMutableTreeNode node =
(DefaultMutableTreeNode)selectedNode;
if( node.getChildCount() > 0 )
{
JPopupMenu selectionMenu = new JPopupMenu();
JMenuItem selectAll = new JMenuItem( "Select All" );
selectAll.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
setFilterEnabled( mModel, node, true );
}
});
selectionMenu.add( selectAll );
JMenuItem deselectAll = new JMenuItem( "Deselect All" );
deselectAll.addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
setFilterEnabled( mModel, node, false );
}
});
selectionMenu.add( deselectAll );
selectionMenu.show( mTree,
event.getX(),
event.getY() );
}
}
}
}
}
@Override
public void mousePressed( MouseEvent e ){}
@Override
public void mouseReleased( MouseEvent e ){}
@Override
public void mouseEntered( MouseEvent e ){}
@Override
public void mouseExited( MouseEvent e ){}
}
/**
* Recursively sets the enabled state on all filter node children below the
* specified parent node.
*
* @param model - model containing the tree nodes
* @param node - parent node
* @param enabled - true or false to enable or disable the filters
*/
private void setFilterEnabled( DefaultTreeModel model,
DefaultMutableTreeNode node,
boolean enabled )
{
Object obj = node.getUserObject();
if( obj instanceof FilterSet<?> )
{
((FilterSet<?>)obj).setEnabled( enabled );
}
else if( obj instanceof Filter )
{
((Filter<?>)obj).setEnabled( enabled );
}
else if( obj instanceof FilterElement )
{
((FilterElement<?>)obj).setEnabled( enabled );
}
model.nodeChanged( node );
/* Recursively set the children of this node */
Enumeration<?> children = node.children();
while( children.hasMoreElements() )
{
Object child = children.nextElement();
if( child instanceof DefaultMutableTreeNode )
{
setFilterEnabled( model, (DefaultMutableTreeNode)child, enabled );
}
}
}
public class EditorTreeCellRenderer extends DefaultTreeCellRenderer
{
private static final long serialVersionUID = 1L;
public Component getTreeCellRendererComponent( JTree tree,
Object treeNode,
boolean selected,
boolean expanded,
boolean leaf,
int row,
boolean hasFocus )
{
if( treeNode instanceof DefaultMutableTreeNode )
{
Object userObject = ((DefaultMutableTreeNode)treeNode).getUserObject();
JCheckBox checkBox = null;
if( userObject instanceof IFilter )
{
IFilter<?> filter = (IFilter<?>)userObject;
checkBox = new JCheckBox( filter.getName() );
checkBox.setSelected( filter.isEnabled() );
}
else if( userObject instanceof FilterElement )
{
FilterElement<?> element = (FilterElement<?>)userObject;
checkBox = new JCheckBox( element.getName() );
checkBox.setSelected( element.isEnabled() );
}
if( checkBox != null )
{
if( selected )
{
checkBox.setForeground( getTextSelectionColor() );
checkBox.setBackground( getBackgroundSelectionColor() );
}
else
{
checkBox.setForeground( getTextNonSelectionColor() );
checkBox.setBackground( getBackgroundNonSelectionColor() );
}
return checkBox;
}
}
return super.getTreeCellRendererComponent( tree, treeNode, selected,
expanded, leaf, row, hasFocus );
}
}
public class FilterCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private IFilter<T> mFilter;
public FilterCheckBox( IFilter<T> filter )
{
super( filter.getName() );
mFilter = filter;
setSelected( mFilter.isEnabled() );
addItemListener( new ItemListener()
{
@Override
public void itemStateChanged( ItemEvent e )
{
mFilter.setEnabled( FilterCheckBox.this.isSelected() );
}
} );
}
}
public class FilterElementCheckBox extends JCheckBox
{
private static final long serialVersionUID = 1L;
private FilterElement<?> mFilter;
public FilterElementCheckBox( FilterElement<?> filter )
{
super( filter.getName() );
mFilter = filter;
setSelected( mFilter.isEnabled() );
addItemListener( new ItemListener()
{
@Override
public void itemStateChanged( ItemEvent arg0 )
{
mFilter.setEnabled( FilterElementCheckBox.this.isSelected() );
}
} );
}
}
public class FilterTreeNodeEditor implements TreeCellEditor
{
@Override
@SuppressWarnings( { "rawtypes", "unchecked" } )
public Component getTreeCellEditorComponent( JTree tree, Object node,
boolean isSelected, boolean expanded, boolean leaf, int row )
{
if( node instanceof DefaultMutableTreeNode )
{
Object userObject = ((DefaultMutableTreeNode)node).getUserObject();
if( userObject instanceof IFilter )
{
return new FilterCheckBox( (IFilter)userObject );
}
else if( userObject instanceof FilterElement )
{
return new FilterElementCheckBox( (FilterElement<?>)userObject );
}
}
return new JLabel( node.toString() );
}
@Override
public void addCellEditorListener( CellEditorListener l ) {}
@Override
public void cancelCellEditing()
{
}
@Override
public Object getCellEditorValue()
{
return null;
}
@Override
public boolean isCellEditable( EventObject anEvent )
{
return true;
}
@Override
public void removeCellEditorListener( CellEditorListener l ) {}
@Override
public boolean shouldSelectCell( EventObject anEvent )
{
return false;
}
@Override
public boolean stopCellEditing()
{
return false;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 alias.mobileID;
import javax.xml.bind.annotation.XmlAttribute;
import alias.AliasID;
import alias.AliasIDType;
/**
* Mobile ID Number
*/
public class Min extends AliasID
{
private String mMin;
public Min()
{
}
@XmlAttribute
public String getMin()
{
return mMin;
}
public void setMin( String min )
{
mMin = min;
}
public String toString()
{
return "MIN: " + mMin;
}
@Override
public boolean matches( AliasID id )
{
boolean retVal = false;
if( mMin != null && id instanceof Min )
{
Min min = (Min)id;
//Create a pattern - replace * wildcards with regex single-char wildcard
String pattern = mMin.replace( "*", ".?" );
retVal = min.getMin().matches( pattern );
}
return retVal;
}
@Override
public AliasIDType getType()
{
return AliasIDType.MIN;
}
}
<file_sep>package source.tuner.frequency;
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2015 <NAME>
*
* 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/>
******************************************************************************/
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import source.tuner.frequency.FrequencyChangeEvent.Attribute;
/**
* Frequency control for providing frequency error correction to a tuner channel
*/
public class FrequencyCorrectionControl implements FrequencyChangeListener
{
private final static Logger mLog =
LoggerFactory.getLogger( FrequencyCorrectionControl.class );
protected FrequencyChangeListener mListener;
protected FrequencyCorrectionResetListener mResetListener;
protected int mErrorCorrection = 0;
private int mMaximumCorrection = 3000;
/**
* Frequency correction controller.
*
* @param maximum - defines the maximum +/- allowable frequency correction
* value
*/
public FrequencyCorrectionControl( int maximum )
{
mMaximumCorrection = maximum;
}
/**
* Cleanup
*/
public void dispose()
{
mListener = null;
mResetListener = null;
}
/**
* Registers a listener to receive frequency correction events
*/
public void setListener( FrequencyChangeListener listener )
{
mListener = listener;
}
/**
* Registers a listener to receive frequency correction resets
*/
public void setListener( FrequencyCorrectionResetListener listener )
{
mResetListener = listener;
}
/**
* Listener for source frequency or frequency offset value changes to
* reset this frequency controller value to zero.
*/
@Override
public void frequencyChanged( FrequencyChangeEvent event )
{
Attribute attribute = event.getAttribute();
if( attribute == Attribute.FREQUENCY ||
attribute == Attribute.SAMPLE_RATE_ERROR )
{
reset();
}
}
/**
* Resets frequency correction value to zero and notifies any reset
* listeners
*/
protected void reset()
{
setErrorCorrection( 0, false );
if( mResetListener != null )
{
mResetListener.resetFrequencyCorrection();
}
}
/**
* Sets frequency correction to the specified value and broadcasts a change
*/
public void setErrorCorrection( int correction )
{
setErrorCorrection( correction, true );
}
/**
* Sets frequency correction to the specified value
*/
public void setErrorCorrection( int correction, boolean broadcast )
{
mErrorCorrection = correction;
/* Limit frequency correction to +/- max correction value */
if( mErrorCorrection > mMaximumCorrection )
{
mErrorCorrection = mMaximumCorrection;
}
else if( mErrorCorrection < -mMaximumCorrection )
{
mErrorCorrection = -mMaximumCorrection;
}
/* Broadcast a change event */
if( broadcast && mListener != null )
{
mListener.frequencyChanged(
new FrequencyChangeEvent( Attribute.FREQUENCY_ERROR,
mErrorCorrection ) );
}
}
/**
* Increments the frequency error correction value by the specified adjustment
*/
public void adjust( int adjustment )
{
setErrorCorrection( getErrorCorrection() + adjustment );
}
/**
* Current frequency error correction value
* @return
*/
public int getErrorCorrection()
{
return mErrorCorrection;
}
/**
* Listener interface to be notified when this control is reset to a zero
* frequency correction value
*/
public interface FrequencyCorrectionResetListener
{
public void resetFrequencyCorrection();
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 util.waveaudio;
import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import javax.sound.sampled.AudioFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class WaveWriter
{
private final static Logger mLog = LoggerFactory.getLogger( WaveWriter.class );
private static final int sTOTAL_BYTE_LIMIT = Integer.MAX_VALUE;
private BufferedOutputStream mOutputStream;
private boolean mRunning = false;
private AudioFormat mAudioFormat;
private String mFileName;
private int mTotalByteCount = 0;
private int mFileRolloverCounter = 0;
public WaveWriter( String fileName, AudioFormat format )
{
mAudioFormat = format;
mFileName = fileName;
}
public void start() throws IOException
{
if( !mRunning )
{
openFile();
mRunning = true;
}
}
public void stop() throws IOException
{
if( mRunning )
{
closeFile();
//Increment file rollover count, in case we re-start the recorder
mFileRolloverCounter++;
mRunning = false;
}
}
public void write( ByteBuffer buffer ) throws IOException
{
checkFileRollover( buffer.capacity() );
if( mRunning && mOutputStream != null )
{
//Write the data
mOutputStream.write( buffer.array() );
mTotalByteCount += buffer.capacity();
}
}
protected void checkFileRollover( int byteCount ) throws IOException
{
if( mTotalByteCount + byteCount >= sTOTAL_BYTE_LIMIT )
{
closeFile();
mFileRolloverCounter++;
openFile();
}
}
private void closeFile() throws IOException
{
mOutputStream.flush();
mOutputStream.close();
String filename = mFileName;
//If this is a rollover file, append the rollover count to the filename
if( mFileRolloverCounter > 0 )
{
filename += mFileRolloverCounter;
}
//Correct the total count. Subtract 8 bytes from the total, to account
//for the ChunkID and ChunkSize bytes, at the beginning of the file
correctWAVEFileByteCount( filename, ( mTotalByteCount ) );
}
private void correctWAVEFileByteCount( String fileName, int newByteCount ) throws IOException
{
RandomAccessFile raf = new RandomAccessFile( fileName, "rw" );
//Get byte array for newByteCount minus header (8 bytes)
byte[] newTotalSize = new byte[ 4 ];
WaveUtils.loadDouble( newTotalSize, ( newByteCount - 8 ), 0, 4 );
//Seek to byte position 4 and write the 4 byte length value
raf.seek( 4 );
raf.write( newTotalSize );
//Get byte array for newByteCount minus all headers (44 bytes)
byte[] newDataSize = new byte[ 4 ];
WaveUtils.loadDouble( newDataSize, ( newByteCount - 44 ), 0, 4 );
//Seek to byte position 4 and write the 4 byte length value
raf.seek( 40 );
raf.write( newDataSize );
mLog.info( "Closing recording [" + mFileName + "] amending file byte size to:" + newByteCount );
raf.close();
}
private void openFile() throws IOException
{
mTotalByteCount = 0;
String filename = mFileName;
if( mFileRolloverCounter > 0 )
{
filename += mFileRolloverCounter;
}
mOutputStream = new BufferedOutputStream( new FileOutputStream( filename ) );
//Write the RIFF descriptor
byte[] riff = WaveUtils.getRIFFChunkDescriptor(
mAudioFormat.getSampleRate(), 10 );
mOutputStream.write( riff );
mTotalByteCount += riff.length;
//Write the WAVE descriptor
byte[] wave = WaveUtils.getWAVEFormatDescriptor(
mAudioFormat.getSampleRate(),
mAudioFormat.getChannels(),
mAudioFormat.getSampleSizeInBits() );
mOutputStream.write( wave );
mTotalByteCount += wave.length;
//Write the data chunk header - for 10 seconds of audio
byte[] header = WaveUtils.getDataChunkHeader(
(int)(10 * mAudioFormat.getSampleRate() ), mAudioFormat.getChannels() );
mOutputStream.write( header );
mTotalByteCount += header.length;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.mpt1327;
import instrument.Instrumentable;
import instrument.tap.Tap;
import instrument.tap.stream.BinaryTap;
import instrument.tap.stream.FloatTap;
import java.util.ArrayList;
import java.util.List;
import sample.Broadcaster;
import sample.real.RealSampleListener;
import source.Source.SampleType;
import alias.AliasList;
import audio.AudioOutputImpl;
import audio.IAudioOutput;
import bits.MessageFramer;
import bits.SyncPattern;
import decode.Decoder;
import decode.DecoderType;
import decode.config.DecodeConfiguration;
import dsp.filter.DCRemovalFilter;
import dsp.filter.FilterFactory;
import dsp.filter.Filters;
import dsp.filter.FloatFIRFilter;
import dsp.filter.FloatHalfBandFilter;
import dsp.filter.Window.WindowType;
import dsp.fsk.FSK2Decoder;
import dsp.fsk.FSK2Decoder.Output;
import dsp.nbfm.NBFMDemodulator;
/**
* MPT1327 Decoder - 1200 baud 2FSK decoder that can process 48k sample rate
* complex or floating point samples and output fully framed MPT1327 control and
* traffic messages.
*/
public class MPT1327Decoder extends Decoder implements Instrumentable
{
/* Determines how quickly the DC remove filter responds */
private static final double sDC_REMOVAL_RATIO = 0.95;
/* Decimated sample rate ( 48,000 / 2 = 24,000 ) feeding the decoder */
private static final int sDECIMATED_SAMPLE_RATE = 24000;
/* Baud or Symbol Rate */
private static final int sSYMBOL_RATE = 1200;
/* Message length -- longest possible message is:
* 4xREVS + 16xSYNC + 64xADD1 + 64xDCW1 + 64xDCW2 + 64xDCW3 + 64xDCW4 */
private static final int sMESSAGE_LENGTH = 350;
/* Instrumentation Taps */
private static final String INSTRUMENT_INPUT = "Tap Point: Input";
private static final String INSTRUMENT_HB1_FILTER_TO_LOW_PASS =
"Tap Point: Half-band Decimation Filter > < Low Pass Filter";
private static final String INSTRUMENT_LOW_PASS_TO_DECODER =
"Tap Point: Low Pass Filter > < Decoder";
private static final String INSTRUMENT_DECODER_TO_FRAMER =
"Tap Point: Decoder > < Sync Detect/Message Framer";
private List<Tap> mAvailableTaps;
private NBFMDemodulator mNBFMDemodulator;
private FloatHalfBandFilter mDecimationFilter;
private FloatFIRFilter mLowPassFilter;
private DCRemovalFilter mDCRemovalFilter;
private FSK2Decoder mFSKDecoder;
private Broadcaster<Boolean> mSymbolBroadcaster;
private MessageFramer mControlMessageFramer;
private MessageFramer mTrafficMessageFramer;
private MPT1327MessageProcessor mMessageProcessor;
private AudioOutputImpl mAudioOutput = new AudioOutputImpl( "MPT1327 Decoder Audio Output" );
public MPT1327Decoder( DecodeConfiguration config,
SampleType sampleType,
AliasList aliasList,
Sync sync )
{
super( config, sampleType );
/* If we're receiving complex samples, do FM demodulation and DC removal
* and feed the output back to this decoder */
if( mSourceSampleType == SampleType.COMPLEX )
{
/* I/Q low pass filtering narrow band FM demodulator */
mNBFMDemodulator = new NBFMDemodulator(
FilterFactory.getLowPass( 48000, 4000, 73, WindowType.HAMMING ),
1.0002, true );
this.addComplexListener( mNBFMDemodulator );
/* DC removal filter */
mDCRemovalFilter = new DCRemovalFilter( sDC_REMOVAL_RATIO );
if( mNBFMDemodulator != null )
{
mNBFMDemodulator.addListener( mDCRemovalFilter );
mDCRemovalFilter.setListener( this.getRealReceiver() );
}
}
/* Demodulated float sample processing */
/* Decimation filter - 48000 / 2 = 24000 output */
mDecimationFilter = new FloatHalfBandFilter(
Filters.FIR_HALF_BAND_31T_ONE_EIGHTH_FCO, 1.0002 );
addRealSampleListener( mDecimationFilter );
/* Low pass filter: 2kHz to pass the 1200 & 1800 Hz FSK */
mLowPassFilter = new FloatFIRFilter(
FilterFactory.getLowPass( 24000, //sampleRate,
2000, //passFrequency,
4000, //stopFrequency,
60, //attenuation,
WindowType.HANNING, //windowType,
true ) //forceOddLength
, 2.0 ); //Gain
mDecimationFilter.setListener( mLowPassFilter );
/**
* Normal: 2FSK Decoder with inverted output
* French: 2FSK Decoder with normal output
*/
if( sync == Sync.NORMAL )
{
mFSKDecoder = new FSK2Decoder( 24000, 1200, Output.INVERTED );
}
else if( sync == Sync.FRENCH )
{
mFSKDecoder = new FSK2Decoder( 24000, 1200, Output.NORMAL );
}
else
{
throw new IllegalArgumentException( "MPT1327 Decoder - unrecognized Sync type" );
}
mLowPassFilter.setListener( mFSKDecoder );
mSymbolBroadcaster = new Broadcaster<Boolean>();
mFSKDecoder.setListener( mSymbolBroadcaster );
/* Message framer for control channel messages */
mControlMessageFramer =
new MessageFramer( sync.getControlSyncPattern().getPattern(),
sMESSAGE_LENGTH );
mSymbolBroadcaster.addListener( mControlMessageFramer );
/* Message framer for traffic channel massages */
mTrafficMessageFramer =
new MessageFramer( sync.getTrafficSyncPattern().getPattern(),
sMESSAGE_LENGTH );
mSymbolBroadcaster.addListener( mTrafficMessageFramer );
/* Fully decoded and framed messages processor */
mMessageProcessor = new MPT1327MessageProcessor( aliasList );
mMessageProcessor.addMessageListener( this );
mControlMessageFramer.addMessageListener( mMessageProcessor );
mTrafficMessageFramer.addMessageListener( mMessageProcessor );
}
@Override
public void addUnfilteredRealSampleListener( RealSampleListener listener )
{
if( mNBFMDemodulator != null )
{
mNBFMDemodulator.addListener( listener );
}
}
@Override
public DecoderType getType()
{
return DecoderType.MPT1327;
}
/**
* Cleanup method
*/
public void dispose()
{
super.dispose();
mSymbolBroadcaster.dispose();
mAudioOutput.dispose();
mControlMessageFramer.dispose();
if( mDCRemovalFilter != null )
{
mDCRemovalFilter.dispose();
}
if( mNBFMDemodulator != null )
{
mNBFMDemodulator.dispose();
}
mFSKDecoder.dispose();
mDecimationFilter.dispose();
mLowPassFilter.dispose();
mMessageProcessor.dispose();
mTrafficMessageFramer.dispose();
}
/* Instrumentation Taps */
@Override
public List<Tap> getTaps()
{
if( mAvailableTaps == null )
{
mAvailableTaps = new ArrayList<Tap>();
mAvailableTaps.add(
new FloatTap( INSTRUMENT_INPUT, 0, 1.0f ) );
mAvailableTaps.add(
new FloatTap( INSTRUMENT_HB1_FILTER_TO_LOW_PASS, 0, 0.5f ) );
mAvailableTaps.add(
new FloatTap( INSTRUMENT_LOW_PASS_TO_DECODER, 0, 0.5f ) );
mAvailableTaps.add(
new BinaryTap( INSTRUMENT_DECODER_TO_FRAMER, 0, 0.025f ) );
/* Add the taps from the FSK decoder */
mAvailableTaps.addAll( mFSKDecoder.getTaps() );
}
return mAvailableTaps;
}
@Override
public void addTap( Tap tap )
{
/* Send request to decoder */
mFSKDecoder.addTap( tap );
switch( tap.getName() )
{
case INSTRUMENT_INPUT:
FloatTap inputTap = (FloatTap)tap;
if( mNBFMDemodulator != null )
{
mNBFMDemodulator.addListener( inputTap );
}
else
{
addRealSampleListener( inputTap );
}
break;
case INSTRUMENT_HB1_FILTER_TO_LOW_PASS:
FloatTap hb1Tap = (FloatTap)tap;
mDecimationFilter.setListener( hb1Tap );
hb1Tap.setListener( mLowPassFilter );
break;
case INSTRUMENT_LOW_PASS_TO_DECODER:
FloatTap lowTap = (FloatTap)tap;
mLowPassFilter.setListener( lowTap );
lowTap.setListener( mFSKDecoder );
break;
case INSTRUMENT_DECODER_TO_FRAMER:
BinaryTap decoderTap = (BinaryTap)tap;
mFSKDecoder.setListener( decoderTap );
decoderTap.setListener( mSymbolBroadcaster );
break;
}
}
@Override
public void removeTap( Tap tap )
{
mFSKDecoder.removeTap( tap );
switch( tap.getName() )
{
case INSTRUMENT_INPUT:
FloatTap inputTap = (FloatTap)tap;
if( mNBFMDemodulator != null )
{
mNBFMDemodulator.removeListener( inputTap );
}
else
{
removeRealListener( inputTap );
}
break;
case INSTRUMENT_HB1_FILTER_TO_LOW_PASS:
mDecimationFilter.setListener( mLowPassFilter );
break;
case INSTRUMENT_LOW_PASS_TO_DECODER:
mLowPassFilter.setListener( mFSKDecoder );
break;
case INSTRUMENT_DECODER_TO_FRAMER:
mFSKDecoder.setListener( mSymbolBroadcaster );
break;
}
}
public enum Sync
{
NORMAL( "Normal",
SyncPattern.MPT1327_CONTROL,
SyncPattern.MPT1327_TRAFFIC ),
FRENCH( "French",
SyncPattern.MPT1327_CONTROL_FRENCH,
SyncPattern.MPT1327_TRAFFIC_FRENCH );
private String mLabel;
private SyncPattern mControlSyncPattern;
private SyncPattern mTrafficSyncPattern;
private Sync( String label,
SyncPattern controlPattern,
SyncPattern trafficPattern )
{
mLabel = label;
mControlSyncPattern = controlPattern;
mTrafficSyncPattern = trafficPattern;
}
public String getLabel()
{
return mLabel;
}
public SyncPattern getControlSyncPattern()
{
return mControlSyncPattern;
}
public SyncPattern getTrafficSyncPattern()
{
return mTrafficSyncPattern;
}
public String toString()
{
return getLabel();
}
}
@Override
public IAudioOutput getAudioOutput()
{
return mAudioOutput;
}
}
<file_sep>/*
* WaypointMapOverlay.java
*
* Created on April 1, 2006, 4:59 PM
*
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
*/
package map;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.jdesktop.swingx.JXMapViewer;
import org.jdesktop.swingx.painter.AbstractPainter;
import settings.SettingsManager;
public class PlottableEntityPainter extends AbstractPainter<JXMapViewer>
{
private PlottableEntityRenderer mRenderer;
private Set<PlottableEntity> mEntities = new HashSet<PlottableEntity>();
public PlottableEntityPainter( SettingsManager settingsManager )
{
mRenderer = new PlottableEntityRenderer( settingsManager );
setAntialiasing( true );
setCacheable( false );
}
public void addEntity( PlottableEntity entity )
{
mEntities.add( entity );
}
public void removeEntity( PlottableEntity entity )
{
mEntities.remove( entity );
}
public void clearEntities()
{
mEntities.clear();
}
private Set<PlottableEntity> getEntities()
{
return Collections.unmodifiableSet( mEntities );
}
@Override
protected void doPaint(Graphics2D g, JXMapViewer map, int width, int height)
{
Rectangle viewportBounds = map.getViewportBounds();
g.translate( -viewportBounds.getX(), -viewportBounds.getY() );
Set<PlottableEntity> entities = getEntities();
for (PlottableEntity entity: entities )
{
mRenderer.paintPlottableEntity( g, map, entity, true );
}
g.translate( viewportBounds.getX(), viewportBounds.getY() );
}
}
<file_sep>package decode.p25.message.tsbk.motorola;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
public class MotorolaTSBKMessage extends TSBKMessage
{
public MotorolaTSBKMessage( BinaryMessage message, DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
protected String getMessageStub()
{
StringBuilder sb = new StringBuilder();
sb.append( "NAC:" );
sb.append( getNAC() ); /* NAC is the system id for TSBK messages */
sb.append( " " );
sb.append( getDUID().getLabel() );
sb.append( " MOTOROLA" );
if( isEncrypted() )
{
sb.append( " ENCRYPTED" );
}
sb.append( getMotorolaOpcode().getLabel() );
return sb.toString();
}
public MotorolaOpcode getMotorolaOpcode()
{
return MotorolaOpcode.fromValue( mMessage.getInt( OPCODE ) );
}
}
<file_sep>package decode.p25.message.pdu.osp.control;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.pdu.PDUMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import decode.p25.reference.Response;
import edac.CRCP25;
public class GroupAffiliationResponseExtended extends PDUMessage
{
public static final int[] TARGET_ADDRESS = { 88,89,90,91,92,93,94,95,96,97,
98,99,100,101,102,103,104,105,106,107,108,109,110,111 };
public static final int[] SOURCE_WACN = { 128,129,130,131,132,133,134,135,
136,137,138,139,140,141,142,143,160,161,162,163 };
public static final int[] SOURCE_SYSTEM_ID = { 164,165,166,167,168,169,170,
171,172,173,174,175 };
public static final int[] SOURCE_ID = { 176,177,178,179,180,181,182,183,184,
185,186,187,188,189,190,191,192,193,194,195,196,197,198,199 };
public static final int[] GROUP_WACN = { 200,201,202,203,204,205,206,207,
208,209,210,211,212,213,214,215,216,217,218,219 };
public static final int[] GROUP_SYSTEM_ID = { 220,221,222,223,224,225,226,
227,228,229,230,231 };
public static final int[] GROUP_ID = { 232,233,234,235,236,237,238,239,240,
241,242,243,244,245,246,247 };
public static final int[] ANNOUNCEMENT_GROUP_ID = { 248,249,250,251,252,253,
254,255,256,257,258,259,260,261,262,263 };
public static final int[] GROUP_AFFILIATION_RESPONSE_VALUE = { 270,271 };
public static final int[] MULTIPLE_BLOCK_CRC = { 320,321,322,323,324,325,
326,327,328,329,330,331,332,333,334,335,336,337,338,339,340,341,342,
343,344,345,346,347,348,349,350,351 };
public GroupAffiliationResponseExtended( BinaryMessage message,
DataUnitID duid, AliasList aliasList )
{
super( message, duid, aliasList );
/* Header block is already error detected/corrected - perform error
* detection correction on the intermediate and final data blocks */
mMessage = CRCP25.correctPDU1( mMessage );
mCRC[ 1 ] = mMessage.getCRC();
}
@Override
public String getEventType()
{
return Opcode.GROUP_AFFILIATION_RESPONSE.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( "AFFILIATION:" );
sb.append( getResponse().name() );
sb.append( " TO:" );
sb.append( getTargetAddress() );
sb.append( " FROM:" );
sb.append( getSourceID() );
sb.append( " WACN:" );
sb.append( getSourceWACN() );
sb.append( " SYS:" );
sb.append( getSourceSystemID() );
sb.append( " GROUP:" );
sb.append( getGroupID() );
sb.append( " WACN:" );
sb.append( getGroupWACN() );
sb.append( " SYS:" );
sb.append( getGroupSystemID() );
sb.append( " ANNOUNCEMENT GROUP:" );
sb.append( getAnnouncementGroupID() );
return sb.toString();
}
public String getTargetAddress()
{
return mMessage.getHex( TARGET_ADDRESS, 6 );
}
public String getSourceWACN()
{
return mMessage.getHex( SOURCE_WACN, 5 );
}
public String getSourceSystemID()
{
return mMessage.getHex( SOURCE_SYSTEM_ID, 3 );
}
public String getSourceID()
{
return mMessage.getHex( SOURCE_ID, 6 );
}
public String getGroupWACN()
{
return mMessage.getHex( GROUP_WACN, 5 );
}
public String getGroupSystemID()
{
return mMessage.getHex( GROUP_SYSTEM_ID, 3 );
}
public String getGroupID()
{
return mMessage.getHex( GROUP_ID, 4 );
}
public String getAnnouncementGroupID()
{
return mMessage.getHex( GROUP_ID, 4 );
}
public Response getResponse()
{
return Response.fromValue(
mMessage.getInt( GROUP_AFFILIATION_RESPONSE_VALUE ) );
}
}
<file_sep>package decode.p25.message.ldu.lc;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.message.IBandIdentifier;
import decode.p25.message.IdentifierReceiver;
import decode.p25.message.ldu.LDU1Message;
import decode.p25.reference.LinkControlOpcode;
import decode.p25.reference.Service;
public class NetworkStatusBroadcast extends LDU1Message
implements IdentifierReceiver
{
private final static Logger mLog =
LoggerFactory.getLogger( NetworkStatusBroadcast.class );
public static final int[] NETWORK_ID = { 376,377,382,383,384,385,386,387,
536,537,538,539,540,541,546,547,548,549,550,551 };
public static final int[] SYSTEM_ID = { 556,557,558,559,560,561,566,567,568,
569,570,571 };
public static final int[] IDENTIFIER = { 720,721,722,723 };
public static final int[] CHANNEL = { 724,725,730,731,732,733,734,735,740,
741,742,743 };
public static final int[] SYSTEM_SERVICE_CLASS = { 744,745,750,751,752,753,
754,755 };
private IBandIdentifier mIdentifierUpdate;
public NetworkStatusBroadcast( LDU1Message source )
{
super( source );
}
@Override
public String getEventType()
{
return LinkControlOpcode.NETWORK_STATUS_BROADCAST.getDescription();
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " NETWORK:" + getNetworkID() );
sb.append( " SYS:" + getSystem() );
sb.append( " CHAN:" + getChannel() );
sb.append( " " + Service.getServices( getSystemServiceClass() ).toString() );
return sb.toString();
}
public String getNetworkID()
{
return mMessage.getHex( NETWORK_ID, 5 );
}
public String getSystem()
{
return mMessage.getHex( SYSTEM_ID, 3 );
}
public int getIdentifier()
{
return mMessage.getInt( IDENTIFIER );
}
public int getChannelNumber()
{
return mMessage.getInt( CHANNEL );
}
public String getChannel()
{
return getIdentifier() + "-" + getChannelNumber();
}
public int getSystemServiceClass()
{
return mMessage.getInt( SYSTEM_SERVICE_CLASS );
}
@Override
public void setIdentifierMessage( int identifier, IBandIdentifier message )
{
mIdentifierUpdate = message;
}
@Override
public int[] getIdentifiers()
{
int[] identifiers = new int[ 1 ];
identifiers[ 0 ] = getIdentifier();
return identifiers;
}
public long getDownlinkFrequency()
{
return calculateDownlink( mIdentifierUpdate, getChannelNumber() );
}
public long getUplinkFrequency()
{
return calculateUplink( mIdentifierUpdate, getChannelNumber() );
}
}
<file_sep>package sample.complex;
public interface ComplexSampleListener
{
public void receive( float i, float q );
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 edac;
public enum ChecksumType
{
FLEETSYNC_ANI( new short[]
{
0x0000, //Unknown Always One
0x0000, //Status Msg Flag
0x14C3, //Status Message 6 001010011000011
0x6908, //Status Message 5 110100100001000
0x3484, //Status Message 4 011010010000100
0x1A42, //Status Message 3 001101001000010
0x0D21, //Status Message 2 000110100100001
0x729A, //Status Message 1 111001010011010
0x394D, //Status Message 0 011100101001101
0x0000, //Type 7
0x0000, //Type 6
0x0000, //Type 5
0x0000, //Type 4
0x0000, //Type 3
0x0000, //Type 2
0x0000, //Type 1
0x0000, //Type 0
0x0000, //Fleet From 7
0x0000, //Fleet From 6
0x0000, //Fleet From 5
0x0000, //Fleet From 4
0x402E, //Fleet From 3 100000000101110
0x2017, //Fleet From 2 010000000010111
0x6401, //Fleet From 1 110010000000001
0x460A, //Fleet From 0 100011000001010
0x0000, //Ident From 11
0x0000, //Ident From 10
0x0000, //Ident From 9
0x0000, //Ident From 8
0x0CB1, //Ident From 7 000110010110001
0x7252, //Ident From 6 111001001010010
0x3929, //Ident From 5 011100100101001
0x689E, //Ident From 4 110100010011110
0x344F, //Ident From 3 011010001001111
0x6E2D, //Ident From 2 110111000101101
0x431C, //Ident From 1 100001100011100
0x218E, //Ident From 0 010000110001110
0x0000, //Ident To 11
0x0000, //Ident To 10
0x0000, //Ident To 9
0x0000, //Ident To 8
0x6685, //Ident To 7 110011010000101
0x4748, //Ident To 6 100011101001000
0x23A4, //Ident To 5 010001110100100
0x11D2, //Ident To 4 001000111010010
0x08E9, //Ident To 3 000100011101001
0x707E, //Ident To 2 111000001111110
0x383F, //Ident To 1 011100000111111
0x6815, //Ident To 0 110100000010101
}),
LTR( new short[]
{ 0x0038, //Area
0x001C, //Channel 4
0x000E, //Channel 3
0x0046, //Channel 2
0x0023, //Channel 1
0x0051, //Channel 0
0x0068, //Home 4
0x0075, //Home 3
0x007A, //Home 2
0x003D, //Home 1
0x001F, //Home 0
0x004F, //Group 7
0x0026, //Group 6
0x0052, //Group 5
0x0029, //Group 4
0x0015, //Group 3
0x000B, //Group 2
0x0045, //Group 1
0x0062, //Group 0
0x0031, //Free 4
0x0019, //Free 3
0x000D, //Free 2
0x0007, //Free 1
0x0043 //Free 0
} ),
PASSPORT( new short[]
{
// 0x6e,
// 0xbf,
// 0xd6,
// 0xe3,
// 0xf8,
// 0x7c,
// 0x3e,
// 0x97,
// 0xc2,
// 0xe9,
// 0x75,
// 0x3b,
// 0x94,
// 0x4a,
// 0xad,
// 0x57,
// 0xa2,
// 0xd9,
// 0x6d,
// 0x37,
// 0x92,
// 0xc1,
// 0x61,
// 0x31,
// 0x19,
// 0x0d,
// 0x07,
// 0x8a,
// 0xcd,
// 0x67,
// 0xba,
// 0xd5,
// 0x6b, // 0111110
// 0xbc, // 1111100
// 0x5e, // 1101001
// 0xa7, // 1000011
// 0xda, // 0010111
// 0xe5, // 0101110
// 0x73, // 1011100
// 0xb0, // 0101001
// 0x58, // 1010010
// 0x2c, // 0110101 Bit 43
// 0x16, // 1101010
// 0x83, // 1000101 Bit 45
// 0xc8, // 0011011 Bit 46
// 0x64, // 0110110
// 0x32, // 1101100
// 0x91, // 1001001
// 0x49,
// 0x25,
// 0x13,
} ),
MULTINET( new short[]
{
// 0x96, // 0010110
// 0xAC, // 0101100
// 0xd8, // 1011000
// 0x21, // 0100001
// 0x42, // 1000010
// 0x95, // 0010101
// 0xaa, // 0101010
// 0xd4, // 1010100
// 0x39, // 0111001
// 0x72, // 1110010
// 0xf5, // 1110101 Bit 10
// 0x7b, // 1111011
// 0xe7, // 1100111
// 0x5f, // 1011111
// 0xaf, // 0101111
// 0xde, // 1011110
// 0x2d, // 0101101
// 0x5a, // 1011010
// 0xa5, // 0100101
// 0xca, // 1001010
// 0x05, // 0000101
// 0x0a, // 0001010
// 0x14, // 0010100
// 0x28, // 0101000
// 0x50, // 1010000
// 0xb1, // 0110001
// 0xe2, // 1100010
// 0x55, // 1010101
// 0xbb, // 0111011
// 0xf6, // 1110110
// 0x7d, // 1111101
// 0xeb, // 1101011
// 0x47, // 1000111
// 0x9f, // 0011111 Bit 33
// 0xbe, // 0111110
// 0xfc, // 1111100
// 0x69, // 1101001
// 0xc3, // 1000011
// 0x17, // 0010111
// 0x2e, // 0101110
// 0x5c, // 1011100
// 0xA9, // 0101001
// 0xD2, // 1010010
// 0x35, // 0110101 Bit 43
// 0x6A, // 1101010
// 0xC5, // 1000101 Bit 45
// 0x1B, // 0011011 Bit 46
// 0x36, // 0110110
// 0x6C, // 1101100
// 0xC9 // 1001001
});
private short[] mValues;
ChecksumType( short[] values )
{
mValues = values;
}
public short[] getValues()
{
return mValues;
}
}
<file_sep>package decode.p25.message.tsbk.osp.control;
import java.util.List;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.TSBKMessage;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import decode.p25.reference.Service;
public class SystemServiceBroadcast extends TSBKMessage
{
public static final int[] AVAILABLE_SERVICES = { 88,89,90,91,92,93,94,95,
96,97,98,99,100,101,102,103,104,105,106,107,108,109,110,111 };
public static final int[] SUPPORTED_SERVICES = { 112,113,114,115,116,117,
118,119,120,121,122,123,124,125,126,127,128,129,130,131,132,133,134,135 };
public static final int[] REQUEST_PRIORITY_LEVEL = { 136,137,138,139,140,
141,142,143 };
public SystemServiceBroadcast( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
super( message, duid, aliasList );
}
@Override
public String getEventType()
{
return Opcode.SYSTEM_SERVICE_BROADCAST.getDescription();
}
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( getMessageStub() );
sb.append( " SERVICES AVAILABLE " );
sb.append( getAvailableServices() );
sb.append( " SUPPORTED " );
sb.append( getSupportedServices() );
return sb.toString();
}
public List<Service> getAvailableServices()
{
long bitmap = mMessage.getLong( AVAILABLE_SERVICES );
return Service.getServices( bitmap );
}
public List<Service> getSupportedServices()
{
long bitmap = mMessage.getLong( SUPPORTED_SERVICES );
return Service.getServices( bitmap );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.tait;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;
import map.Plottable;
import message.Message;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import alias.Alias;
import alias.AliasList;
import bits.BinaryMessage;
import edac.CRC;
public class Tait1200ANIMessage extends Message
{
private final static Logger mLog = LoggerFactory.getLogger( Tait1200ANIMessage.class );
public static int[] REVS_1 = { 0,1,2,3 };
public static int[] SYNC = { 4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19 };
public static int[] SIZE = { 20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35 };
public static int[] FROM_DIGIT_1 = { 36,37,38,39,40,41,42,43 };
public static int[] FROM_DIGIT_2 = { 44,45,46,47,48,49,50,51 };
public static int[] FROM_DIGIT_3 = { 52,53,54,55,56,57,58,59 };
public static int[] FROM_DIGIT_4 = { 60,61,62,63,64,65,66,67 };
public static int[] FROM_DIGIT_5 = { 68,69,70,71,72,73,74,75 };
public static int[] FROM_DIGIT_6 = { 76,77,78,79,80,81,82,83 };
public static int[] FROM_DIGIT_7 = { 84,85,86,87,88,89,90,91 };
public static int[] FROM_DIGIT_8 = { 92,93,94,95,96,97,98,99 };
public static int[] CHECKSUM_1 = { 100,101,102,103,104,105,106,107,108,109,
110,111,112,113,114,115 };
public static int[] REVS_2 = { 116,117,118,119,120,121,122,123,124,125,126,127,
128,129,130,131 };
public static int[] SIZE_2 = { 188,189,190,191,192,193,194,195,196,197,198,
199,200,201,202,203 };
public static int[] TO_DIGIT_1 = { 204,205,206,207,208,209,210,211 };
public static int[] TO_DIGIT_2 = { 212,213,214,215,216,217,218,219 };
public static int[] TO_DIGIT_3 = { 220,221,222,223,224,225,226,227 };
public static int[] TO_DIGIT_4 = { 228,229,230,231,232,233,234,235 };
public static int[] TO_DIGIT_5 = { 236,237,238,239,240,241,242,243 };
public static int[] TO_DIGIT_6 = { 244,245,246,247,248,249,250,251 };
public static int[] TO_DIGIT_7 = { 252,253,254,255,256,257,258,259 };
public static int[] TO_DIGIT_8 = { 260,261,262,263,264,265,266,267 };
public static int[] UNKNOWN_1 = { 268,269,270,271,272,273,274,275 };
public static int[] CHECKSUM_2 = { 276,277,278,279,280,281,282,283,284,285,
286,287,288,289,290,291 };
private static SimpleDateFormat mSDF = new SimpleDateFormat( "yyyyMMdd HHmmss" );
private BinaryMessage mMessage;
private AliasList mAliasList;
private CRC mCRC;
public Tait1200ANIMessage( BinaryMessage message, AliasList list )
{
mMessage = message;
mAliasList = list;
// checkCRC();
//
// switch( mCRC )
// {
// case CORRECTED:
// mLog.debug( "CORR:" + message.toString() );
// break;
// case FAILED_CRC:
// mLog.debug( "FAIL:" + message.toString() );
// break;
// case PASSED:
// mLog.debug( "PASS:" + message.toString() );
// break;
// }
}
@Override
public String getFromID()
{
StringBuilder sb = new StringBuilder();
sb.append( getCharacter( FROM_DIGIT_1 ) );
sb.append( getCharacter( FROM_DIGIT_2 ) );
sb.append( getCharacter( FROM_DIGIT_3 ) );
sb.append( getCharacter( FROM_DIGIT_4 ) );
sb.append( getCharacter( FROM_DIGIT_5 ) );
sb.append( getCharacter( FROM_DIGIT_6 ) );
sb.append( getCharacter( FROM_DIGIT_7 ) );
sb.append( getCharacter( FROM_DIGIT_8 ) );
return sb.toString();
}
@Override
public Alias getFromIDAlias()
{
if( mAliasList != null )
{
return mAliasList.getTalkgroupAlias( getFromID() );
}
return null;
}
@Override
public String getToID()
{
StringBuilder sb = new StringBuilder();
sb.append( getCharacter( TO_DIGIT_1 ) );
sb.append( getCharacter( TO_DIGIT_2 ) );
sb.append( getCharacter( TO_DIGIT_3 ) );
sb.append( getCharacter( TO_DIGIT_4 ) );
sb.append( getCharacter( TO_DIGIT_5 ) );
sb.append( getCharacter( TO_DIGIT_6 ) );
sb.append( getCharacter( TO_DIGIT_7 ) );
sb.append( getCharacter( TO_DIGIT_8 ) );
return sb.toString();
}
@Override
public Alias getToIDAlias()
{
if( mAliasList != null )
{
return mAliasList.getTalkgroupAlias( getToID() );
}
return null;
}
public char getCharacter( int[] bits )
{
int value = mMessage.getInt( bits );
return (char)value;
}
private void checkCRC()
{
// mCRC = CRCLJ.checkAndCorrect( mMessage );
}
public boolean isValid()
{
// return mCRC == CRC.PASSED || mCRC == CRC.CORRECTED;
return true;
}
@Override
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( "ANI FROM:" );
sb.append( getFromID() );
sb.append( " TO:" );
sb.append( getToID() );
return sb.toString();
}
/**
* Pads spaces onto the end of the value to make it 'places' long
*/
public String pad( String value, int places, String padCharacter )
{
StringBuilder sb = new StringBuilder();
sb.append( value );
while( sb.length() < places )
{
sb.append( padCharacter );
}
return sb.toString();
}
/**
* Pads an integer value with additional zeroes to make it decimalPlaces long
*/
public String format( int number, int decimalPlaces )
{
StringBuilder sb = new StringBuilder();
int paddingRequired = decimalPlaces - ( String.valueOf( number ).length() );
for( int x = 0; x < paddingRequired; x++)
{
sb.append( "0" );
}
sb.append( number );
return sb.toString();
}
@Override
public String getBinaryMessage()
{
return mMessage.toString();
}
@Override
public String getProtocol()
{
return "Tait-1200";
}
@Override
public String getEventType()
{
return "ANI";
}
@Override
public String getMessage()
{
return toString();
}
@Override
public String getErrorStatus()
{
return "UNKNOWN";
// return mCRC.getDisplayText();
}
@Override
public Plottable getPlottable()
{
return null;
}
/**
* Provides a listing of aliases contained in the message.
*/
public List<Alias> getAliases()
{
List<Alias> aliases = new ArrayList<Alias>();
Alias from = getFromIDAlias();
if( from != null )
{
aliases.add( from );
}
Alias to = getToIDAlias();
if( to != null )
{
aliases.add( to );
}
return aliases;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 decode.ltrstandard;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import message.Message;
import message.MessageDirection;
import message.MessageType;
import alias.Alias;
import alias.AliasList;
import bits.BinaryMessage;
import decode.DecoderType;
import edac.CRC;
import edac.CRCLTR;
public abstract class LTRStandardMessage extends Message
{
protected static final String sUNKNOWN = "**UNKNOWN**";
protected static final int sINT_NULL_VALUE = -1;
protected static final double sDOUBLE_NULL_VALUE = -1.0D;
protected SimpleDateFormat mDatestampFormatter =
new SimpleDateFormat( "yyyyMMdd HHmmss" );
protected DecimalFormat mDecimalFormatter = new DecimalFormat("0.00000");
protected static final int[] sSYNC = { 8,7,6,5,4,3,2,1,0 };
protected static final int[] sAREA = { 9 };
protected static final int[] sCHANNEL = { 14,13,12,11,10 };
protected static final int[] sHOME_REPEATER = { 19,18,17,16,15 };
protected static final int[] sGROUP = { 27,26,25,24,23,22,21,20 };
protected static final int[] sFREE = { 32,31,30,29,28 };
protected static final int[] sCRC = { 39,38,37,36,35,34,33 };
protected BinaryMessage mMessage;
protected MessageType mMessageType;
protected CRC mCRC;
protected AliasList mAliasList;
public LTRStandardMessage( BinaryMessage message,
MessageDirection direction,
AliasList list )
{
mMessage = message;
mCRC = CRCLTR.check( message, direction );
mAliasList = list;
}
public MessageType getMessageType()
{
return mMessageType;
}
public boolean isValid()
{
return mCRC != CRC.FAILED_CRC && mCRC != CRC.FAILED_PARITY;
}
/**
* Appends spaces to the end of the stringbuilder to make it length long
*/
protected void pad( StringBuilder sb, int length )
{
while( sb.length() < length )
{
sb.append( " " );
}
}
@Override
public String getBinaryMessage()
{
return mMessage.toString();
}
/**
* Returns a value formatted in hex notation.
*
* @param value - integer value
* @return - hex digits returned
*/
protected static String getHex( int value, int digits )
{
return String.format( "%0" + digits + "X", value );
}
protected int getInt( int[] bits )
{
int retVal = 0;
for( int x = 0; x < bits.length; x++ )
{
if( mMessage.get( bits[ x ] ) )
{
retVal += 1<<x;
}
}
return retVal;
}
/**
* Pads an integer value with additional zeroes to make it decimalPlaces long
*/
public String format( int number, int decimalPlaces )
{
StringBuilder sb = new StringBuilder();
int paddingRequired = decimalPlaces - ( String.valueOf( number ).length() );
for( int x = 0; x < paddingRequired; x++)
{
sb.append( "0" );
}
sb.append( number );
return sb.toString();
}
public String format( String val, int places )
{
StringBuilder sb = new StringBuilder();
sb.append( val );
while( sb.length() < places )
{
sb.append( " " );
}
return sb.toString();
}
public CRC getCRC()
{
return mCRC;
}
public int getArea()
{
return getInt( sAREA );
}
public int getChannel()
{
return getInt( sCHANNEL );
}
public int getHomeRepeater()
{
return getInt( sHOME_REPEATER );
}
public int getGroup()
{
return getInt( sGROUP );
}
public String getTalkgroupID()
{
return getTalkgroupID( true );
}
public String getTalkgroupID( boolean format )
{
StringBuilder sb = new StringBuilder();
sb.append( getArea() );
if( format )
{
sb.append( "-" );
}
sb.append( format( getHomeRepeater(), 2 ) );
if( format )
{
sb.append( "-" );
}
sb.append( format( getGroup(), 3 ) );
return sb.toString();
}
public Alias getTalkgroupIDAlias()
{
return mAliasList.getTalkgroupAlias( getTalkgroupID() );
}
public int getFree()
{
return getInt( sFREE );
}
public int getCRCChecksum()
{
return getInt( sCRC );
}
@Override
public String getProtocol()
{
return DecoderType.LTR_STANDARD.getDisplayString();
}
@Override
public String getEventType()
{
if( mMessageType != null )
{
return mMessageType.getDisplayText();
}
else
{
return MessageType.UN_KNWN.getDisplayText();
}
}
@Override
public String getToID()
{
return null;
}
@Override
public Alias getToIDAlias()
{
return null;
}
@Override
public String getErrorStatus()
{
return mCRC.getDisplayText();
}
}
<file_sep>package dsp.filter;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Polyphase interpolating FIR filter with an internal circular buffer as
* described by the dspGuru at:
*
* http://www.dspguru.com/dsp/faqs/multirate/interpolation
* See sections 3.4.2 and 3.4.3 )
*/
public class PolyphaseFIRInterpolatingFilter
{
private final static Logger mLog =
LoggerFactory.getLogger( PolyphaseFIRInterpolatingFilter.class );
private double[] mBuffer;
private int mBufferPointer = 0;
private double[] mTaps;
private Phase[] mPhases;
/**
* Constructs the interpolating filter. Coefficients length must be an
* integer multiple of the interpolation value. Each sample processed by
* the filter will generate a quantity of samples equal to the interpolation
* value.
*
* @param coefficients - low pass filter coefficients sized for the desired
* interpolated sample rate with a cutoff frequency of no more than half of
* the original sample rate.
*
* @param interpolation - integral interpolation quantity
*/
public PolyphaseFIRInterpolatingFilter( double[] coefficients, int interpolation )
{
/* Ensure coefficients are an integral multiple of the interpolation factor */
assert( coefficients.length % interpolation == 0 );
mTaps = coefficients;
mPhases = new Phase[ interpolation ];
int phaseSize = coefficients.length / interpolation;
mBuffer = new double[ phaseSize ];
for( int x = 0; x < interpolation; x++ )
{
int coefficientIndex = 0;
int[] indexes = new int[ phaseSize ];
for( int y = x; y < coefficients.length; y += interpolation )
{
indexes[ coefficientIndex++ ] = y;
}
/* Create a phase using the tap indexes and the interpolation value
* for the gain value, to offset the loss induced in upsampling from
* one sample to (interpolation) samples. */
mPhases[ interpolation - x - 1 ] = new Phase( indexes, interpolation );
}
}
/**
* Inserts the sample into the filter and returns (interpolation) number
* of interpolated samples in the return array.
*
* @param sample - float sample
* @return - array of interpolated samples, size = interpolation quantity
*/
public float[] interpolate( float sample )
{
mBuffer[ mBufferPointer ] = (double)sample;
mBufferPointer++;
mBufferPointer %= mBuffer.length;
float[] samples = new float[ mPhases.length ];
for( int x = 0; x < mPhases.length; x++ )
{
samples[ x ] = mPhases[ x ].filter();
}
return samples;
}
/**
* Upsamples and interpolates the array of samples, returning an array that
* is upsampled and low-pass filtered by the interpolation quantity.
*
* @param samples - array of float samples
* @return - array of interpolated samples, size = interpolation * samples size
*/
public float[] interpolate( float[] samples )
{
int pointer = 0;
float[] interpolated = new float[ samples.length * mPhases.length ];
for( float sample: samples )
{
mBuffer[ mBufferPointer ] = (double)sample;
mBufferPointer++;
mBufferPointer %= mBuffer.length;
for( int x = 0; x < mPhases.length; x++ )
{
interpolated[ pointer ] = mPhases[ x ].filter();
pointer++;
}
}
return interpolated;
}
/**
* Single phase element of a polyphase interpolating FIR filter. Each phase
* element shares a common buffer. The tap indexes argument defines the
* filter taps used by this phase element to generate an interpolated value
* from the shared circular buffer of samples.
*/
public class Phase
{
private int[] mIndexes;
private double mGain;
public Phase( int[] tapIndexes, int gain )
{
mIndexes = tapIndexes;
mGain = gain;
}
public float filter()
{
double accumulator = 0;
for( int x = 0; x < mIndexes.length; x++ )
{
accumulator += mTaps[ mIndexes[ x ] ] *
mBuffer[ ( x + mBufferPointer ) % mIndexes.length ];
}
return (float)( accumulator * mGain );
}
}
// public static void main( String[] args )
// {
// int interpolation = 6;
//
// PolyphaseFIRInterpolatingFilter p =
// new PolyphaseFIRInterpolatingFilter( IMBESynthesizer.INTERPOLATION_TAPS, interpolation );
//
// Oscillator o = new Oscillator( 500, 8000 );
//
// int iterations = 40;
//
// float[] in = new float[ iterations ];
// float[] out = new float[ iterations * interpolation ];
//
// int inIndex = 0;
// int outIndex = 0;
//
// for( int x = 0; x < iterations; x++ )
// {
// float next = o.nextFloat();
//
// in[ inIndex++ ] = next;
//
// float[] samples = p.interpolate( next );
//
// System.arraycopy( samples, 0, out, outIndex, samples.length );
//
// outIndex += interpolation;
// }
//
// mLog.debug( "In: " + Arrays.toString( in ) );
// mLog.debug( "Out: " + Arrays.toString( out ) );
// }
}
<file_sep>package source.tuner.hackrf;
/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* Ported from libhackrf at:
* https://github.com/mossmann/hackrf/tree/master/host/libhackrf
*
* Copyright (c) 2012, <NAME> <<EMAIL>>
* Copyright (c) 2013, <NAME> <<EMAIL>>
* copyright (c) 2013, <NAME> <<EMAIL>>
*
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* Neither the name of Great Scott Gadgets nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
* PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
* TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
* ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
* 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/>
******************************************************************************/
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import javax.usb.UsbException;
import org.apache.commons.io.EndianUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
import org.usb4java.Transfer;
import org.usb4java.TransferCallback;
import sample.Listener;
import sample.adapter.ByteSampleAdapter;
import sample.complex.ComplexBuffer;
import source.SourceException;
import source.tuner.TunerConfiguration;
import source.tuner.TunerController;
public class HackRFTunerController extends TunerController
{
private final static Logger mLog =
LoggerFactory.getLogger( HackRFTunerController.class );
public final static long TIMEOUT_US = 1000000l; //uSeconds
public static final byte USB_ENDPOINT = (byte)0x81;
public static final byte USB_INTERFACE = (byte)0x0;
public static final byte REQUEST_TYPE_IN =
(byte)( LibUsb.ENDPOINT_IN |
LibUsb.REQUEST_TYPE_VENDOR |
LibUsb.RECIPIENT_DEVICE );
public static final byte REQUEST_TYPE_OUT =
(byte)( LibUsb.ENDPOINT_OUT |
LibUsb.REQUEST_TYPE_VENDOR |
LibUsb.RECIPIENT_DEVICE );
public static final long MIN_FREQUENCY = 10000000l;
public static final long MAX_FREQUENCY = 6000000000l;
public static final long DEFAULT_FREQUENCY = 101100000;
public final static int TRANSFER_BUFFER_POOL_SIZE = 16;
private LinkedTransferQueue<byte[]> mFilledBuffers =
new LinkedTransferQueue<byte[]>();
private CopyOnWriteArrayList<Listener<ComplexBuffer>> mSampleListeners =
new CopyOnWriteArrayList<Listener<ComplexBuffer>>();
private ByteSampleAdapter mSampleAdapter = new ByteSampleAdapter();
private BufferProcessor mBufferProcessor = new BufferProcessor();
private HackRFSampleRate mSampleRate = HackRFSampleRate.RATE2_016MHZ;
public int mBufferSize = 262144;
private boolean mAmplifierEnabled = false;
private Device mDevice;
private DeviceDescriptor mDeviceDescriptor;
private DeviceHandle mDeviceHandle;
public HackRFTunerController( Device device, DeviceDescriptor descriptor )
throws SourceException
{
super( MIN_FREQUENCY, MAX_FREQUENCY );
mDevice = device;
mDeviceDescriptor = descriptor;
}
public void init() throws SourceException
{
mDeviceHandle = new DeviceHandle();
LibUsb.open( mDevice, mDeviceHandle );
try
{
claimInterface();
setMode( Mode.RECEIVE );
setFrequency( DEFAULT_FREQUENCY );
}
catch( Exception e )
{
throw new SourceException( "HackRF Tuner Controller - couldn't "
+ "claim USB interface or get endpoint or pipe", e );
}
}
/**
* Claims the USB interface. If another application currently has
* the interface claimed, the USB_FORCE_CLAIM_INTERFACE setting
* will dictate if the interface is forcibly claimed from the other
* application
*/
private void claimInterface() throws SourceException
{
if( mDeviceHandle != null )
{
int result = LibUsb.kernelDriverActive( mDeviceHandle, USB_INTERFACE );
if( result == 1 )
{
result = LibUsb.detachKernelDriver( mDeviceHandle, USB_INTERFACE );
if( result != LibUsb.SUCCESS )
{
mLog.error( "failed attempt to detach kernel driver [" +
LibUsb.errorName( result ) + "]" );
throw new SourceException( "couldn't detach kernel driver "
+ "from device" );
}
}
result = LibUsb.claimInterface( mDeviceHandle, USB_INTERFACE );
if( result != LibUsb.SUCCESS )
{
throw new SourceException( "couldn't claim usb interface [" +
LibUsb.errorName( result ) + "]" );
}
}
else
{
throw new SourceException( "couldn't claim usb interface - no "
+ "device handle" );
}
}
/**
* HackRF board identifier/type
*/
public BoardID getBoardID() throws UsbException
{
int id = readByte( Request.BOARD_ID_READ, (byte)0, (byte)0, false );
return BoardID.lookup( id );
}
/**
* HackRF firmware version string
*/
public String getFirmwareVersion() throws UsbException
{
ByteBuffer buffer = readArray( Request.VERSION_STRING_READ, 0, 0, 255 );
byte[] data = new byte[ 255 ];
buffer.get( data );
return new String( data );
}
/**
* HackRF part id number and serial number
*/
public Serial getSerial() throws UsbException
{
ByteBuffer buffer = readArray( Request.BOARD_PARTID_SERIALNO_READ, 0, 0, 24 );
return new Serial( buffer );
}
/**
* Sets the HackRF transceiver mode
*/
public void setMode( Mode mode ) throws UsbException
{
write( Request.SET_TRANSCEIVER_MODE, mode.getNumber(), 0 );
}
/**
* Sets the HackRF baseband filter
*/
public void setBasebandFilter( BasebandFilter filter ) throws UsbException
{
write( Request.BASEBAND_FILTER_BANDWIDTH_SET,
filter.getLowValue(),
filter.getHighValue() );
}
/**
* Enables (true) or disables (false) the amplifier
*/
public void setAmplifierEnabled( boolean enabled ) throws UsbException
{
write( Request.AMP_ENABLE, ( enabled ? 1 : 0 ), 0 );
mAmplifierEnabled = enabled;
}
public boolean getAmplifier()
{
return mAmplifierEnabled;
}
/**
* Sets the IF LNA Gain
*/
public void setLNAGain( HackRFLNAGain gain ) throws UsbException
{
int result = readByte( Request.SET_LNA_GAIN, 0, gain.getValue(), true );
if( result != 1 )
{
throw new UsbException( "couldn't set lna gain to " + gain );
}
}
/**
* Sets the Baseband VGA Gain
*/
public void setVGAGain( HackRFVGAGain gain ) throws UsbException
{
int result = readByte( Request.SET_VGA_GAIN, 0, gain.getValue(), true );
if( result != 1 )
{
throw new UsbException( "couldn't set vga gain to " + gain );
}
}
/**
* Not implemented
*/
public long getTunedFrequency() throws SourceException
{
return 0;
}
@Override
public void setTunedFrequency( long frequency ) throws SourceException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 8 );
buffer.order( ByteOrder.LITTLE_ENDIAN );
int mhz = (int)( frequency / 1E6 );
int hz = (int)( frequency - ( mhz * 1E6 ) );
buffer.putInt( mhz );
buffer.putInt( hz );
buffer.rewind();
try
{
write( Request.SET_FREQUENCY, 0, 0, buffer );
}
catch( UsbException e )
{
mLog.error( "error setting frequency [" + frequency + "]", e );
throw new SourceException( "error setting frequency [" +
frequency + "]", e );
}
}
@Override
public int getCurrentSampleRate() throws SourceException
{
return mSampleRate.getRate();
}
@Override
public void apply( TunerConfiguration config ) throws SourceException
{
if( config instanceof HackRFTunerConfiguration )
{
HackRFTunerConfiguration hackRFConfig =
(HackRFTunerConfiguration)config;
try
{
setSampleRate( hackRFConfig.getSampleRate() );
setFrequencyCorrection( hackRFConfig.getFrequencyCorrection() );
setAmplifierEnabled( hackRFConfig.getAmplifierEnabled() );
setLNAGain( hackRFConfig.getLNAGain() );
setVGAGain( hackRFConfig.getVGAGain() );
setFrequency( getFrequency() );
}
catch ( UsbException e )
{
throw new SourceException( "Error while applying tuner "
+ "configuration", e );
}
}
else
{
throw new IllegalArgumentException( "Invalid tuner configuration "
+ "type [" + config.getClass() + "]" );
}
}
public ByteBuffer readArray( Request request,
int value,
int index,
int length ) throws UsbException
{
if( mDeviceHandle != null )
{
ByteBuffer buffer = ByteBuffer.allocateDirect( length );
int transferred = LibUsb.controlTransfer( mDeviceHandle,
REQUEST_TYPE_IN,
request.getRequestNumber(),
(short)value,
(short)index,
buffer,
TIMEOUT_US );
if( transferred < 0 )
{
throw new LibUsbException( "read error", transferred );
}
return buffer;
}
else
{
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
}
public int read( Request request, int value, int index, int length )
throws UsbException
{
if( !( length == 1 || length == 2 || length == 4 ) )
{
throw new IllegalArgumentException( "invalid length [" + length +
"] must be: byte=1, short=2, int=4 to read a primitive" );
}
ByteBuffer buffer = readArray( request, value, index, length );
byte[] data = new byte[ buffer.capacity() ];
buffer.get( data );
switch( data.length )
{
case 1:
return data[ 0 ];
case 2:
return EndianUtils.readSwappedShort( data, 0 );
case 4:
return EndianUtils.readSwappedInteger( data, 0 );
default:
throw new UsbException( "read() primitive returned an "
+ "unrecognized byte array " + Arrays.toString( data ) );
}
}
public int readByte( Request request, int value, int index, boolean signed )
throws UsbException
{
ByteBuffer buffer = readArray( request, value, index, 1 );
if( signed )
{
return (int)( buffer.get() );
}
else
{
return (int)( buffer.get() & 0xFF );
}
}
public void write( Request request,
int value,
int index,
ByteBuffer buffer ) throws UsbException
{
if( mDeviceHandle != null )
{
int transferred = LibUsb.controlTransfer( mDeviceHandle,
REQUEST_TYPE_OUT,
request.getRequestNumber(),
(short)value,
(short)index,
buffer,
TIMEOUT_US );
if( transferred < 0 )
{
throw new LibUsbException( "error writing byte buffer",
transferred );
}
else if( transferred != buffer.capacity() )
{
throw new LibUsbException( "transferred bytes [" +
transferred + "] is not what was expected [" +
buffer.capacity() + "]", transferred );
}
}
else
{
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
}
/**
* Sends a request that doesn't have a data payload
*/
public void write( Request request,
int value,
int index ) throws UsbException
{
write( request, value, index, ByteBuffer.allocateDirect( 0 ) );
}
/**
* Sample Rate
*
* Note: the libhackrf set sample rate method is designed to allow fractional
* sample rates. However, since we're only using integral sample rates, we
* simply invoke the setSampleRateManual method directly.
*/
public void setSampleRate( HackRFSampleRate rate ) throws UsbException
{
setSampleRateManual( rate.getRate(), 1 );
mFrequencyController.setSampleRate( rate.getRate() );
setBasebandFilter( rate.getFilter() );
mSampleRate = rate;
}
public void setSampleRateManual( int frequency, int divider )
throws UsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 8 );
buffer.order( ByteOrder.LITTLE_ENDIAN );
buffer.putInt( frequency );
buffer.putInt( divider );
write( Request.SET_SAMPLE_RATE, 0, 0, buffer );
}
public int getSampleRate()
{
return mSampleRate.getRate();
}
public enum Request
{
SET_TRANSCEIVER_MODE( 1 ),
MAX2837_TRANSCEIVER_WRITE( 2 ),
MAX2837_TRANSCEIVER_READ( 3 ),
SI5351C_CLOCK_GENERATOR_WRITE( 4 ),
SI5351C_CLOCK_GENERATOR_READ( 5 ),
SET_SAMPLE_RATE( 6 ),
BASEBAND_FILTER_BANDWIDTH_SET( 7 ),
RFFC5071_MIXER_WRITE( 8 ),
RFFC5071_MIXER_READ( 9 ),
SPIFLASH_ERASE( 10 ),
SPIFLASH_WRITE( 11 ),
SPIFLASH_READ( 12 ),
BOARD_ID_READ( 14 ),
VERSION_STRING_READ( 15 ),
SET_FREQUENCY( 16 ),
AMP_ENABLE( 17 ),
BOARD_PARTID_SERIALNO_READ( 18 ),
SET_LNA_GAIN( 19 ),
SET_VGA_GAIN( 20 ),
SET_TXVGA_GAIN( 21 ),
ANTENNA_ENABLE( 23 ),
SET_FREQUENCY_EXPLICIT( 24 );
private byte mRequestNumber;
private Request( int number )
{
mRequestNumber = (byte)number;
}
public byte getRequestNumber()
{
return mRequestNumber;
}
}
public enum HackRFSampleRate
{
RATE2_016MHZ( 2016000, "2.016 MHz", BasebandFilter.F3_50 ),
RATE3_024MHZ( 3024000, "3.024 MHz", BasebandFilter.F5_00 ),
RATE4_464MHZ( 4464000, "4.464 MHz", BasebandFilter.F6_00 ),
RATE5_376MHZ( 5376000, "5.376 MHz", BasebandFilter.F7_00 ),
RATE7_488MHZ( 7488000, "7.488 MHz", BasebandFilter.F9_00 ),
RATE10_080MHZ( 10080000, "10.080 MHz", BasebandFilter.F12_00 ),
RATE12_000MHZ( 12000000, "12.000 MHz", BasebandFilter.F14_00 ),
RATE13_440MHZ( 13440000, "13.440 MHz", BasebandFilter.F15_00 ),
RATE14_976MHZ( 14976000, "14.976 MHz", BasebandFilter.F20_00 ),
RATE19_968MHZ( 19968000, "19.968 MHz", BasebandFilter.F24_00 );
private int mRate;
private String mLabel;
private BasebandFilter mFilter;
private HackRFSampleRate( int rate,
String label,
BasebandFilter filter )
{
mRate = rate;
mLabel = label;
mFilter = filter;
}
public int getRate()
{
return mRate;
}
public String getLabel()
{
return mLabel;
}
public String toString()
{
return mLabel;
}
public BasebandFilter getFilter()
{
return mFilter;
}
}
public enum BasebandFilter
{
FAUTO( 0, "AUTO" ),
F1_75( 1750000, "1.75 MHz" ),
F2_50( 2500000, "2.50 MHz" ),
F3_50( 3500000, "3.50 MHz" ),
F5_00( 5000000, "5.00 MHz" ),
F5_50( 5500000, "5.50 MHz" ),
F6_00( 6000000, "6.00 MHz" ),
F7_00( 7000000, "7.00 MHz" ),
F8_00( 8000000, "8.00 MHz" ),
F9_00( 9000000, "9.00 MHz" ),
F10_00( 10000000, "10.00 MHz" ),
F12_00( 12000000, "12.00 MHz" ),
F14_00( 14000000, "14.00 MHz" ),
F15_00( 15000000, "15.00 MHz" ),
F20_00( 20000000, "20.00 MHz" ),
F24_00( 24000000, "24.00 MHz" ),
F28_00( 28000000, "28.00 MHz" );
private int mBandwidth;
private String mLabel;
private BasebandFilter( int bandwidth, String label )
{
mBandwidth = bandwidth;
mLabel = label;
}
public int getBandwidth()
{
return mBandwidth;
}
public int getHighValue()
{
return mBandwidth >> 16;
}
public int getLowValue()
{
return mBandwidth & 0xFFFF;
}
public String getLabel()
{
return mLabel;
}
}
public enum BoardID
{
JELLYBEAN( 0x00, "HackRF Jelly Bean" ),
JAWBREAKER( 0x01, "HackRF Jaw Breaker" ),
HACKRF_ONE( 0x02, "HackRF One" ),
INVALID( 0xFF, "HackRF Unknown Board" );
private byte mIDNumber;
private String mLabel;
private BoardID( int number, String label )
{
mIDNumber = (byte)number;
mLabel = label;
}
public String toString()
{
return mLabel;
}
public String getLabel()
{
return mLabel;
}
public byte getNumber()
{
return mIDNumber;
}
public static BoardID lookup( int value )
{
switch( value )
{
case 0:
return JELLYBEAN;
case 1:
return JAWBREAKER;
case 2:
return HACKRF_ONE;
default:
return INVALID;
}
}
}
public enum Mode
{
OFF( 0, "Off" ),
RECEIVE( 1, "Receive" ),
TRANSMIT( 2, "Transmit" ),
SS( 3, "SS" );
private byte mNumber;
private String mLabel;
private Mode( int number, String label )
{
mNumber = (byte)number;
mLabel = label;
}
public byte getNumber()
{
return mNumber;
}
public String getLabel()
{
return mLabel;
}
public String toString()
{
return mLabel;
}
}
public enum HackRFLNAGain
{
GAIN_0( 0 ),
GAIN_8( 8 ),
GAIN_16( 16 ),
GAIN_24( 24 ),
GAIN_32( 32 ),
GAIN_40( 40 );
private int mValue;
private HackRFLNAGain( int value )
{
mValue = value;
}
public int getValue()
{
return mValue;
}
public String toString()
{
return String.valueOf( mValue ) + " dB";
}
}
/**
* Receive (baseband) VGA Gain values
*/
public enum HackRFVGAGain
{
GAIN_0( 0 ),
GAIN_2( 2 ),
GAIN_4( 4 ),
GAIN_6( 6 ),
GAIN_8( 8 ),
GAIN_10( 10 ),
GAIN_12( 12 ),
GAIN_14( 14 ),
GAIN_16( 16 ),
GAIN_18( 18 ),
GAIN_20( 20 ),
GAIN_22( 22 ),
GAIN_23( 24 ),
GAIN_26( 26 ),
GAIN_28( 28 ),
GAIN_30( 30 ),
GAIN_32( 32 ),
GAIN_34( 34 ),
GAIN_36( 36 ),
GAIN_38( 38 ),
GAIN_40( 40 ),
GAIN_42( 42 ),
GAIN_44( 44 ),
GAIN_46( 46 ),
GAIN_48( 48 ),
GAIN_50( 50 ),
GAIN_52( 52 ),
GAIN_54( 54 ),
GAIN_56( 56 ),
GAIN_58( 58 ),
GAIN_60( 60 ),
GAIN_62( 62 );
private int mValue;
private HackRFVGAGain( int value )
{
mValue = value;
}
public int getValue()
{
return mValue;
}
public String toString()
{
return String.valueOf( mValue ) + " dB";
}
}
/**
* HackRF part id and serial number parsing class
*/
public class Serial
{
private byte[] mData;
public Serial( ByteBuffer buffer )
{
mData = new byte[ buffer.capacity() ];
buffer.get( mData );
}
public String getPartID()
{
int part0 = EndianUtils.readSwappedInteger( mData, 0 );
int part1 = EndianUtils.readSwappedInteger( mData, 4 );
StringBuilder sb = new StringBuilder();
sb.append( String.format( "%08X", part0 ) );
sb.append( "-" );
sb.append( String.format( "%08X", part1 ) );
return sb.toString();
}
public String getSerialNumber()
{
int serial0 = EndianUtils.readSwappedInteger( mData, 8 );
int serial1 = EndianUtils.readSwappedInteger( mData, 12 );
int serial2 = EndianUtils.readSwappedInteger( mData, 16 );
int serial3 = EndianUtils.readSwappedInteger( mData, 20 );
StringBuilder sb = new StringBuilder();
sb.append( String.format( "%08X", serial0 ) );
sb.append( "-" );
sb.append( String.format( "%08X", serial1 ) );
sb.append( "-" );
sb.append( String.format( "%08X", serial2 ) );
sb.append( "-" );
sb.append( String.format( "%08X", serial3 ) );
return sb.toString();
}
}
/**
* Adds a sample listener. If the buffer processing thread is
* not currently running, starts it running in a new thread.
*/
public void addListener( Listener<ComplexBuffer> listener )
{
mSampleListeners.add( listener );
if( mBufferProcessor == null || !mBufferProcessor.isRunning() )
{
mBufferProcessor = new BufferProcessor();
Thread thread = new Thread( mBufferProcessor );
thread.setDaemon( true );
thread.setName( "HackRF Sample Processor" );
thread.start();
}
}
/**
* Removes the sample listener. If this is the last registered listener,
* shuts down the buffer processing thread.
*/
public void removeListener( Listener<ComplexBuffer> listener )
{
mSampleListeners.remove( listener );
if( mSampleListeners.isEmpty() )
{
mBufferProcessor.stop();
}
}
/**
* Dispatches the sample array to each registered listener. If there is more
* than one listener, they receive a copy of the samples. If there is only
* one listener, or the last listener, they receive the original sample array.
*
* This is to facilitate garbage collection of the array when the listener
* is done processing the samples.
*/
public void broadcast( ComplexBuffer samples )
{
Iterator<Listener<ComplexBuffer>> it = mSampleListeners.iterator();
while( it.hasNext() )
{
Listener<ComplexBuffer> next = it.next();
/* if this is the last (or only) listener, send the original
* buffer, otherwise send a copy of the buffer */
if( it.hasNext() )
{
next.receive( samples.copyOf() );
}
else
{
next.receive( samples );
}
}
}
/**
* Buffer processing thread. Fetches samples from the HackRF Tuner and
* dispatches them to all registered listeners
*/
public class BufferProcessor implements Runnable, TransferCallback
{
private ScheduledExecutorService mExecutor =
Executors.newScheduledThreadPool( 1 );
private ScheduledFuture<?> mSampleDispatcherTask;
private CopyOnWriteArrayList<Transfer> mTransfers;
private AtomicBoolean mRunning = new AtomicBoolean();
@Override
public void run()
{
if( mRunning.compareAndSet( false, true ) )
{
mLog.debug( "starting sample fetch thread" );
prepareTransfers();
for( Transfer transfer: mTransfers )
{
int result = LibUsb.submitTransfer( transfer );
if( result != LibUsb.SUCCESS )
{
mLog.error( "error submitting transfer [" +
LibUsb.errorName( result ) + "]" );
break;
}
}
mSampleDispatcherTask = mExecutor
.scheduleAtFixedRate( new BufferDispatcher(),
0, 20, TimeUnit.MILLISECONDS );
while( mRunning.get() )
{
ByteBuffer completed = ByteBuffer.allocateDirect( 4 );
int result = LibUsb.handleEventsTimeoutCompleted(
null, TIMEOUT_US, completed.asIntBuffer() );
if( result != LibUsb.SUCCESS )
{
mLog.error( "error handling events for libusb" );
}
}
}
}
/**
* Stops the sample fetching thread
*/
public void stop()
{
if( mRunning.compareAndSet( true, false ) )
{
mLog.debug( "stopping sample fetch thread" );
cancel();
if( mSampleDispatcherTask != null )
{
mSampleDispatcherTask.cancel( true );
mFilledBuffers.clear();
}
}
}
/**
* Indicates if this thread is running
*/
public boolean isRunning()
{
return mRunning.get();
}
@Override
public void processTransfer( Transfer transfer )
{
if( transfer.status() == LibUsb.TRANSFER_COMPLETED )
{
ByteBuffer buffer = transfer.buffer();
byte[] data = new byte[ transfer.actualLength() ];
buffer.get( data );
buffer.rewind();
mFilledBuffers.add( data );
if( !isRunning() )
{
LibUsb.cancelTransfer( transfer );
}
}
switch( transfer.status() )
{
case LibUsb.TRANSFER_COMPLETED:
/* resubmit the transfer */
int result = LibUsb.submitTransfer( transfer );
if( result != LibUsb.SUCCESS )
{
mLog.error( "couldn't resubmit buffer transfer to tuner" );
LibUsb.freeTransfer( transfer );
mTransfers.remove( transfer );
}
break;
case LibUsb.TRANSFER_CANCELLED:
/* free the transfer and remove it */
LibUsb.freeTransfer( transfer );
mTransfers.remove( transfer );
break;
default:
/* unexpected error */
mLog.error( "transfer error [" +
getTransferStatus( transfer.status() ) +
"] transferred actual: " + transfer.actualLength() );
}
}
private void cancel()
{
for( Transfer transfer: mTransfers )
{
LibUsb.cancelTransfer( transfer );
}
ByteBuffer completed = ByteBuffer.allocateDirect( 4 );
int result = LibUsb.handleEventsTimeoutCompleted(
null, TIMEOUT_US, completed.asIntBuffer() );
if( result != LibUsb.SUCCESS )
{
mLog.error( "error handling usb events during cancel [" +
LibUsb.errorName( result ) + "]" );
}
}
/**
* Prepares (allocates) a set of transfer buffers for use in
* transferring data from the tuner via the bulk interface
*/
private void prepareTransfers() throws LibUsbException
{
mTransfers = new CopyOnWriteArrayList<Transfer>();
for( int x = 0; x < TRANSFER_BUFFER_POOL_SIZE; x++ )
{
Transfer transfer = LibUsb.allocTransfer();
if( transfer == null )
{
throw new LibUsbException( "couldn't allocate transfer",
LibUsb.ERROR_NO_MEM );
}
final ByteBuffer buffer =
ByteBuffer.allocateDirect( mBufferSize );
LibUsb.fillBulkTransfer( transfer,
mDeviceHandle,
USB_ENDPOINT,
buffer,
BufferProcessor.this,
"Buffer #" + x,
TIMEOUT_US );
mTransfers.add( transfer );
}
}
}
/**
* Fetches byte[] chunks from the raw sample buffer. Converts each byte
* array and broadcasts the array to all registered listeners
*/
public class BufferDispatcher implements Runnable
{
@Override
public void run()
{
try
{
ArrayList<byte[]> buffers = new ArrayList<byte[]>();
mFilledBuffers.drainTo( buffers );
for( byte[] buffer: buffers )
{
float[] samples = mSampleAdapter.convert( buffer );
broadcast( new ComplexBuffer( samples ) );
}
}
catch( Exception e )
{
mLog.error( "error duruing HackRF buffer dispatching", e );
}
}
}
public static String getTransferStatus( int status )
{
switch( status )
{
case 0:
return "TRANSFER COMPLETED (0)";
case 1:
return "TRANSFER ERROR (1)";
case 2:
return "TRANSFER TIMED OUT (2)";
case 3:
return "TRANSFER CANCELLED (3)";
case 4:
return "TRANSFER STALL (4)";
case 5:
return "TRANSFER NO DEVICE (5)";
case 6:
return "TRANSFER OVERFLOW (6)";
default:
return "UNKNOWN TRANSFER STATUS (" + status + ")";
}
}
}
<file_sep>package decode.p25.message.pdu.confirmed;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import decode.p25.reference.IPHeaderCompression;
import decode.p25.reference.IPProtocol;
public class SNDCPUserData extends PDUConfirmedMessage
{
public final static Logger mLog =
LoggerFactory.getLogger( SNDCPUserData.class );
public static final int DATA_BLOCK_START = 176;
public static final int[] NSAPI = { 180,181,182,183 };
public static final int[] PCOMP = { 184,185,186,187 };
public static final int[] DCOMP = { 188,189,190,191 };
/* IP Packet Header */
public static final int[] IP_VERSION = { 192,193,194,195 };
public static final int[] IHL = { 196,197,198,199 };
public static final int[] DSCP = { 200,201,202,203,204,205 };
public static final int[] ECN = { 206,207 };
public static final int[] TOTAL_LENGTH = { 208,209,210,211,212,213,214,215,
216,217,218,219,220,221,222,223 };
public static final int[] IDENTIFICATION = { 224,225,226,227,228,229,230,231,
232,233,234,235,236,237,238,239 };
public static final int[] FLAGS = { 240,241,242 };
public static final int[] FRAGMENT_OFFSET = { 243,244,245,246,247,248,249,
250,251,252,253,254,255 };
public static final int[] TTL = { 256,257,258,259,260,261,262,263 };
public static final int[] PROTOCOL = { 264,265,266,267,268,269,270,271 };
public static final int[] HEADER_CHECKSUM = { 272,273,274,275,276,277,278,
279,280,281,282,283,284,285,286,287 };
public static final int[] SOURCE_IP_1 = { 288,289,290,291,292,293,294,295 };
public static final int[] SOURCE_IP_2 = { 296,297,298,299,300,301,302,303 };
public static final int[] BLOCK_SERIAL_2 = { 304,305,306,307,308,309,310 };
public static final int[] BLOCK_CRC9_2 = { 311,312,313,314,315,316,317,318,
319 };
public static final int[] SOURCE_IP_3 = { 320,321,322,323,324,325,326,327 };
public static final int[] SOURCE_IP_4 = { 328,329,330,331,332,333,334,335 };
public static final int[] DESTINATION_IP_1 = { 336,337,338,339,340,341,342,343 };
public static final int[] DESTINATION_IP_2 = { 344,345,346,347,348,349,350,351 };
public static final int[] DESTINATION_IP_3 = { 352,353,354,355,356,357,358,359 };
public static final int[] DESTINATION_IP_4 = { 360,361,362,363,364,365,366,367 };
public static final int IP_DATA_START = 368;
/* User Datagram Protocol */
public static final int[] UDP_SOURCE_PORT = { 368,369,370,371,372,373,374,
375 };
public static final int[] UDP_DESTINATION_PORT = { 376,377,378,379,380,381,
382,383 };
public static final int[] UDP_LENGTH = { 384,385,386,387,388,389,390,391,
392,393,394,395,396,397,398,399 };
public static final int[] UDP_CHECKSUM = { 400,401,402,403,404,405,406,407,
408,409,410,411,412,413,414,415 };
public static final int UDP_DATA_START = 416;
public SNDCPUserData( PDUConfirmedMessage message )
{
super( message );
}
@Override
public String getMessage()
{
StringBuilder sb = new StringBuilder();
sb.append( "NAC:" );
sb.append( getNAC() );
sb.append( " PDUC LLID:" );
sb.append( getLogicalLinkID() );
sb.append( " SNDCP NSAPI:" );
sb.append( getNSAPI() );
sb.append( " " );
IPProtocol protocol = getIPProtocol();
sb.append( protocol.getLabel() );
sb.append( "/IP" );
sb.append( " FM:" );
sb.append( getSourceIPAddress() );
if( protocol == IPProtocol.UDP )
{
sb.append( ":" );
sb.append( getUDPSourcePort() );
}
sb.append( " TO:" );
sb.append( getDestinationIPAddress() );
if( protocol == IPProtocol.UDP )
{
sb.append( ":" );
sb.append( getUDPDestinationPort() );
}
sb.append( " DATA:" );
sb.append( getPayload() );
sb.append( " CRC[" );
sb.append( getErrorStatus() );
sb.append( "]" );
sb.append( " PACKET #" );
sb.append( getPacketSequenceNumber() );
if( isFinalFragment() && getFragmentSequenceNumber() == 0 )
{
sb.append( ".C" );
}
else
{
sb.append( "." );
sb.append( getFragmentSequenceNumber() );
if( isFinalFragment() )
{
sb.append( "C" );
}
}
sb.append( " " );
sb.append( mMessage.toString() );
return sb.toString();
}
/**
* Network Service Access Point Identifier - up to 14 NSAPI's can be
* allocated to the mobile with each NSAPI to be used for a specific
* protocol layer.
*/
public int getNSAPI()
{
return mMessage.getInt( NSAPI );
}
public IPHeaderCompression getIPHeaderCompressionState()
{
return IPHeaderCompression.fromValue( mMessage.getInt( PCOMP ) );
}
/**
* No enum values were defined for this
*/
public boolean hasUserDataCompression()
{
return mMessage.getInt( DCOMP ) > 0;
}
/**
* IP Version - should always be 4 (IPV4)
*/
public int getIPVersion()
{
return mMessage.getInt( IP_VERSION );
}
/**
* IP packet header length in 32-bit words
*/
public int getInternetHeaderLength()
{
return mMessage.getInt( IHL );
}
/**
* IP packet DSCP
*/
public int getDifferentiatedServicesCodePoint()
{
return mMessage.getInt( DSCP );
}
/**
* IP packet ECN
*/
public int getExplicitCongestionNotification()
{
return mMessage.getInt( ECN );
}
/**
* IP packet size in bytes, including header and data
*/
public int getTotalLength()
{
return mMessage.getInt( TOTAL_LENGTH );
}
/**
* IP packet identification
*/
public int getIdentification()
{
return mMessage.getInt( IDENTIFICATION );
}
/**
* IP packet flags. 0-Reserved, 1-Don't Fragment, 2-More Fragments
*/
public int getFlags()
{
return mMessage.getInt( FLAGS );
}
public boolean isFragment()
{
return getFlags() > 0;
}
/**
* IP packet - identifies the offset value in 8-byte blocks (64-bit blocks)
* for this packet fragment from the beginning.
*/
public int getFragmentOffset()
{
return mMessage.getInt( FRAGMENT_OFFSET );
}
/**
* IP packet time (hops) to live
*/
public int getTimeToLive()
{
return mMessage.getInt( TTL );
}
/**
* Identifies the IP protocol carried by the IP packet
*/
public IPProtocol getIPProtocol()
{
return IPProtocol.fromValue( mMessage.getInt( PROTOCOL ) );
}
/**
* Source IPV4 address
*/
public String getSourceIPAddress()
{
StringBuilder sb = new StringBuilder();
sb.append( mMessage.getInt( SOURCE_IP_1 ) );
sb.append( "." );
sb.append( mMessage.getInt( SOURCE_IP_2 ) );
sb.append( "." );
sb.append( mMessage.getInt( SOURCE_IP_3 ) );
sb.append( "." );
sb.append( mMessage.getInt( SOURCE_IP_4 ) );
return sb.toString();
}
/**
* Destination IPV4 address
*/
public String getDestinationIPAddress()
{
StringBuilder sb = new StringBuilder();
sb.append( mMessage.getInt( DESTINATION_IP_1 ) );
sb.append( "." );
sb.append( mMessage.getInt( DESTINATION_IP_2 ) );
sb.append( "." );
sb.append( mMessage.getInt( DESTINATION_IP_3 ) );
sb.append( "." );
sb.append( mMessage.getInt( DESTINATION_IP_4 ) );
return sb.toString();
}
/**
* UDP source port
*/
public int getUDPSourcePort()
{
return mMessage.getInt( UDP_SOURCE_PORT );
}
/**
* UDP destination port
*/
public int getUDPDestinationPort()
{
return mMessage.getInt( UDP_DESTINATION_PORT );
}
/**
* UDP data payload size in bytes
*/
public int getUDPDataLength()
{
return mMessage.getInt( UDP_LENGTH );
}
/**
* Hex string representation of the packet data, including packet header
* data if present.
*/
public String getPayload()
{
StringBuilder sb = new StringBuilder();
/* Adjust for PDU header (2 bytes) plus IP Packet header (20 bytes) */
int start = 22;
if( getIPProtocol() == IPProtocol.UDP )
{
/* Adjust for UDP header (8 bytes) */
start = 30;
}
int spacingCounter = 0;
/* Append octets inserting a space between each 32-bit value */
int octets = getOctetCount() + getDataHeaderOffset();
for( int x = start; x < octets; x++ )
{
sb.append( getPacketOctet( x ) );
spacingCounter++;
if( spacingCounter >= 4 )
{
sb.append( " " );
spacingCounter = 0;
}
}
return sb.toString();
}
/**
* Returns the octet identified by the 0-indexed 'octet' argument location.
* If there is a Data Header Offset, the 0 index points to the first octet
* of the data header. Otherwise, the 0 index points to the first octet
* of the packet. You must account for the data header offset when
* specifying the octet.
*/
public String getPacketOctet( int octet )
{
int block = (int)( octet / 16 );
int offset = octet % 16;
int start = DATA_BLOCK_START + ( block * 144 ) + ( offset * 8 );
return mMessage.getHex( start, start + 7, 2 );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 source.tuner;
import java.util.ArrayList;
import javax.sound.sampled.TargetDataLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sample.Listener;
import sample.adapter.SampleAdapter;
import sample.complex.ComplexBuffer;
import sample.complex.ComplexSampleListListener;
import source.mixer.ComplexMixer;
public abstract class MixerTuner extends Tuner implements Listener<ComplexBuffer>
{
private final static Logger mLog =
LoggerFactory.getLogger( MixerTuner.class );
protected MixerTunerType mMixerTunerType;
protected ComplexMixer mComplexMixer;
protected ArrayList<ComplexSampleListListener> mListeners =
new ArrayList<ComplexSampleListListener>();
/**
* Wrapper class to add basic Tuner functionality to the ComplexMixer.
* Subclasses should couple this functionality with a tuner controller class
* to support tuning.
*/
public MixerTuner( String name,
MixerTunerType mixerTunerType,
TargetDataLine targetDataLine,
SampleAdapter sampleAdapter )
{
super( name );
mMixerTunerType = mixerTunerType;
mComplexMixer = new ComplexMixer( targetDataLine,
mMixerTunerType.getAudioFormat(),
name,
sampleAdapter,
(Listener<ComplexBuffer>)this );
}
public MixerTuner( String name,
MixerTunerDataLine mixerTuner,
SampleAdapter sampleAdapter )
{
this( name,
mixerTuner.getMixerTunerType(),
mixerTuner.getTargetDataLine(),
sampleAdapter );
}
public void dispose()
{
mComplexMixer.stop();
super.dispose();
}
public MixerTunerType getMixerTunerType()
{
return mMixerTunerType;
}
public TargetDataLine getTargetDataLine()
{
return mComplexMixer.getTargetDataLine();
}
/**
* Dispatches the received complex buffers from the mComplexMixer to all
* listeners registered on the parent Tuner class
*/
@Override
public void receive( ComplexBuffer buffer )
{
super.broadcast( buffer );
}
/**
* Overrides the parent Tuner class listener management method to allow
* starting the buffer processing thread
*/
@Override
public void addListener( Listener<ComplexBuffer> listener )
{
super.addListener( listener );
/* We can call start multiple times -- it ignores additional requests */
mComplexMixer.start();
}
/**
* Overrides the parent Tuner class listener management method to allow
* stopping the buffer processing thread when there are no more listeners
*/
@Override
public void removeListener( Listener<ComplexBuffer> listener )
{
super.removeListener( listener );
if( mSampleListeners.isEmpty() )
{
mComplexMixer.stop();
}
}
}
<file_sep>package dsp.am;
import sample.Listener;
import sample.complex.ComplexSample;
import sample.real.RealSampleListener;
import sample.real.RealSampleProvider;
public class AMDemodulator implements Listener<ComplexSample>, RealSampleProvider
{
private RealSampleListener mListener;
public AMDemodulator()
{
}
@Override
public void receive( ComplexSample sample )
{
float demodulated = (float)Math.sqrt( ( sample.real() *
sample.real() ) +
( sample.imaginary() *
sample.imaginary() ) );
if( mListener != null )
{
mListener.receive( demodulated * 500.0f );
}
}
/**
* Adds a listener to receive demodulated samples
*/
public void setListener( RealSampleListener listener )
{
mListener = listener;
}
/**
* Removes a listener from receiving demodulated samples
*/
public void removeListener( RealSampleListener listener )
{
mListener = null;
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* Java version based on librtlsdr
* Copyright (C) 2012-2013 by <NAME> <<EMAIL>>
* Copyright (C) 2012 by <NAME> <<EMAIL>>
*
* 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 source.tuner.rtl;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedTransferQueue;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import javax.swing.JPanel;
import javax.usb.UsbDisconnectedException;
import javax.usb.UsbException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.usb4java.Device;
import org.usb4java.DeviceDescriptor;
import org.usb4java.DeviceHandle;
import org.usb4java.LibUsb;
import org.usb4java.LibUsbException;
import org.usb4java.Transfer;
import org.usb4java.TransferCallback;
import sample.Listener;
import sample.adapter.ByteSampleAdapter;
import sample.complex.ComplexBuffer;
import source.SourceException;
import source.tuner.frequency.FrequencyChangeEvent;
import source.tuner.frequency.FrequencyChangeEvent.Attribute;
import source.tuner.TunerController;
import source.tuner.TunerType;
import buffer.FloatAveragingBuffer;
import controller.ResourceManager;
public abstract class RTL2832TunerController extends TunerController
{
private final static Logger mLog =
LoggerFactory.getLogger( RTL2832TunerController.class );
public final static int INT_NULL_VALUE = -1;
public final static long LONG_NULL_VALUE = -1l;
public final static double DOUBLE_NULL_VALUE = -1.0D;
public final static int TWO_TO_22_POWER = 4194304;
public final static byte USB_INTERFACE = (byte)0x0;
public final static byte BULK_ENDPOINT_IN = (byte)0x81;
public final static byte CONTROL_ENDPOINT_IN =
(byte)( LibUsb.ENDPOINT_IN | LibUsb.REQUEST_TYPE_VENDOR );
public final static byte CONTROL_ENDPOINT_OUT =
(byte)( LibUsb.ENDPOINT_OUT | LibUsb.REQUEST_TYPE_VENDOR );
public final static long TIMEOUT_US = 1000000l; //uSeconds
public final static byte REQUEST_ZERO = (byte)0;
public final static int TRANSFER_BUFFER_POOL_SIZE = 16;
public final static byte EEPROM_ADDRESS = (byte)0xA0;
public final static byte[] sFIR_COEFFICIENTS =
{
(byte)0xCA, (byte)0xDC, (byte)0xD7, (byte)0xD8, (byte)0xE0,
(byte)0xF2, (byte)0x0E, (byte)0x35, (byte)0x06, (byte)0x50,
(byte)0x9C, (byte)0x0D, (byte)0x71, (byte)0x11, (byte)0x14,
(byte)0x71, (byte)0x74, (byte)0x19, (byte)0x41, (byte)0xA5
};
public static final SampleRate DEFAULT_SAMPLE_RATE =
SampleRate.RATE_0_960MHZ;
protected Device mDevice;
protected DeviceDescriptor mDeviceDescriptor;
protected DeviceHandle mDeviceHandle;
private SampleRate mSampleRate = DEFAULT_SAMPLE_RATE;
private BufferProcessor mBufferProcessor = new BufferProcessor();
private ByteSampleAdapter mSampleAdapter = new ByteSampleAdapter();
private CopyOnWriteArrayList<Listener<ComplexBuffer>> mSampleListeners =
new CopyOnWriteArrayList<Listener<ComplexBuffer>>();
private LinkedTransferQueue<byte[]> mFilledBuffers =
new LinkedTransferQueue<byte[]>();
private SampleRateMonitor mSampleRateMonitor;
private AtomicInteger mSampleCounter = new AtomicInteger();
private double mSampleRateAverageSum;
private int mSampleRateAverageCount;
private static final DecimalFormat mDecimalFormatter =
new DecimalFormat( "###,###,###.0" );
private static final DecimalFormat mPercentFormatter =
new DecimalFormat( "###.00" );
protected int mOscillatorFrequency = 28800000; //28.8 MHz
public int mBufferSize = 131072;
protected Descriptor mDescriptor;
/**
* Abstract tuner controller device. Use the static getTunerClass() method
* to determine the tuner type, and construct the corresponding child
* tuner controller class for that tuner type.
*/
public RTL2832TunerController( Device device,
DeviceDescriptor deviceDescriptor,
long minTunableFrequency,
long maxTunableFrequency ) throws SourceException
{
super( minTunableFrequency, maxTunableFrequency );
mDevice = device;
mDeviceDescriptor = deviceDescriptor;
}
public void init() throws SourceException
{
mDeviceHandle = new DeviceHandle();
int result = LibUsb.open( mDevice, mDeviceHandle );
if( result != LibUsb.SUCCESS )
{
mDeviceHandle = null;
throw new SourceException( "libusb couldn't open RTL2832 usb "
+ "device [" + LibUsb.errorName( result ) + "]" );
}
claimInterface( mDeviceHandle );
try
{
setSampleRate( DEFAULT_SAMPLE_RATE );
}
catch( Exception e )
{
throw new SourceException( "RTL2832 Tuner Controller - couldn't "
+ "set default sample rate", e );
}
byte[] eeprom = null;
try
{
/* Read the contents of the 256-byte EEPROM */
eeprom = readEEPROM( mDeviceHandle, (short)0, 256 );
}
catch( Exception e )
{
mLog.error( "error while reading the EEPROM device descriptor", e );
}
try
{
mDescriptor = new Descriptor( eeprom );
if( eeprom == null )
{
mLog.error( "eeprom byte array was null - constructed "
+ "empty descriptor object" );
}
}
catch( Exception e )
{
mLog.error( "error while constructing device descriptor using "
+ "descriptor byte array " +
( eeprom == null ? "[null]" : Arrays.toString( eeprom )), e );
}
}
/**
* Claims the USB interface. Attempts to detach the active kernel driver
* if one is currently attached.
*/
public static void claimInterface( DeviceHandle handle ) throws SourceException
{
if( handle != null )
{
int result = LibUsb.kernelDriverActive( handle, USB_INTERFACE );
if( result == 1 )
{
result = LibUsb.detachKernelDriver( handle, USB_INTERFACE );
if( result != LibUsb.SUCCESS )
{
mLog.error( "failed attempt to detach kernel driver [" +
LibUsb.errorName( result ) + "]" );
throw new SourceException( "couldn't detach kernel driver "
+ "from device" );
}
}
result = LibUsb.claimInterface( handle, USB_INTERFACE );
if( result != LibUsb.SUCCESS )
{
throw new SourceException( "couldn't claim usb interface [" +
LibUsb.errorName( result ) + "]" );
}
}
else
{
throw new SourceException( "couldn't claim usb interface - no "
+ "device handle" );
}
}
public static void releaseInterface( DeviceHandle handle )
throws SourceException
{
int result = LibUsb.releaseInterface( handle, USB_INTERFACE );
if( result != LibUsb.SUCCESS )
{
throw new SourceException( "couldn't release interface [" +
LibUsb.errorName( result ) + "]" );
}
}
/**
* Descriptor contains all identifiers and labels parsed from the EEPROM.
*
* May return null if unable to get 256 byte eeprom descriptor from tuner
* or if the descriptor doesn't begin with byte values of 0x28 and 0x32
* meaning it is a valid (and can be parsed) RTL2832 descriptor
*/
public Descriptor getDescriptor()
{
if( mDescriptor != null && mDescriptor.isValid() )
{
return mDescriptor;
}
return null;
}
public void setSamplingMode( SampleMode mode ) throws LibUsbException
{
switch( mode )
{
case QUADRATURE:
/* Set intermediate frequency to 0 Hz */
setIFFrequency( 0 );
/* Enable I/Q ADC Input */
writeDemodRegister( mDeviceHandle,
Page.ZERO,
(short)0x08,
(short)0xCD,
1 );
/* Enable zero-IF mode */
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0xB1,
(short)0x1B,
1 );
/* Set default i/q path */
writeDemodRegister( mDeviceHandle,
Page.ZERO,
(short)0x06,
(short)0x80,
1 );
break;
case DIRECT:
default:
throw new LibUsbException( "QUADRATURE mode is the only mode "
+ "currently supported", LibUsb.ERROR_NOT_SUPPORTED );
}
}
public void setIFFrequency( int frequency ) throws LibUsbException
{
long ifFrequency = ( (long)TWO_TO_22_POWER * (long)frequency ) /
(long)mOscillatorFrequency * -1;
/* Write byte 2 (high) */
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0x19,
(short)( Long.rotateRight( ifFrequency, 16 ) & 0x3F ),
1 );
/* Write byte 1 (middle) */
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0x1A,
(short)( Long.rotateRight( ifFrequency, 8 ) & 0xFF ),
1 );
/* Write byte 0 (low) */
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0x1B,
(short)( ifFrequency & 0xFF ),
1 );
}
public abstract void initTuner( boolean controlI2CRepeater )
throws UsbException;
/**
* Provides a unique identifier to use in distinctly identifying this
* tuner from among other tuners of the same type, so that we can fetch a
* tuner configuration from the settings manager for this specific tuner.
*
* @return serial number of the device
*/
public String getUniqueID()
{
if( mDescriptor != null && mDescriptor.hasSerial() )
{
return mDescriptor.getSerial();
}
else
{
int serial =
( 0xFF & mDeviceDescriptor.iSerialNumber() );
return "SER#" + serial;
}
}
public abstract JPanel getEditor( ResourceManager resourceManager );
public abstract void setSampleRateFilters( int sampleRate )
throws SourceException;
public abstract TunerType getTunerType();
public static TunerType identifyTunerType( Device device )
throws SourceException
{
DeviceHandle handle = new DeviceHandle();
int reason = LibUsb.open( device, handle );
if( reason != LibUsb.SUCCESS )
{
throw new SourceException( "couldn't open device - check permissions"
+ " (udev.rule) [" + LibUsb.errorName( reason ) + "]" );
}
TunerType tunerClass = TunerType.UNKNOWN;
try
{
claimInterface( handle );
/* Perform a dummy write to see if the device needs reset */
boolean resetRequired = false;
try
{
writeRegister( handle,
Block.USB,
Address.USB_SYSCTL.getAddress(),
0x09,
1 );
}
catch( LibUsbException e )
{
if( e.getErrorCode() < 0 )
{
mLog.error( "error performing dummy write - attempting "
+ "device reset", e );
resetRequired = true;
}
else
{
throw new SourceException( "error performing dummy write "
+ "to device [" + LibUsb.errorName(
e.getErrorCode() ) + "]", e );
}
}
if( resetRequired )
{
reason = LibUsb.resetDevice( handle );
try
{
writeRegister( handle,
Block.USB,
Address.USB_SYSCTL.getAddress(),
0x09,
1 );
}
catch( LibUsbException e2 )
{
mLog.error( "device reset attempted, but lost device handle. "
+ "Try restarting the application to use this device" );
throw new SourceException( "couldn't reset device" );
}
}
/* Initialize the baseband */
initBaseband( handle );
enableI2CRepeater( handle, true );
boolean controlI2CRepeater = false;
/* Test for each tuner type until we find the correct one */
if( isTuner( TunerTypeCheck.E4K, handle, controlI2CRepeater ) )
{
tunerClass = TunerType.ELONICS_E4000;
}
else if( isTuner( TunerTypeCheck.FC0013, handle, controlI2CRepeater ) )
{
tunerClass = TunerType.FITIPOWER_FC0013;
}
else if( isTuner( TunerTypeCheck.R820T, handle, controlI2CRepeater ) )
{
tunerClass = TunerType.RAFAELMICRO_R820T;
}
else if( isTuner( TunerTypeCheck.R828D, handle, controlI2CRepeater ) )
{
tunerClass = TunerType.RAFAELMICRO_R828D;
}
else if( isTuner( TunerTypeCheck.FC2580, handle, controlI2CRepeater ) )
{
tunerClass = TunerType.FCI_FC2580;
}
else if( isTuner( TunerTypeCheck.FC0012, handle, controlI2CRepeater ) )
{
tunerClass = TunerType.FITIPOWER_FC0012;
}
enableI2CRepeater( handle, false );
releaseInterface( handle );
LibUsb.close( handle );
}
catch( Exception e )
{
mLog.error( "error while determining tuner type", e );
}
return tunerClass;
}
/**
* Releases the USB interface
*/
public void release()
{
try
{
if( mBufferProcessor.isRunning() )
{
mBufferProcessor.stop();
}
LibUsb.releaseInterface( mDeviceHandle, USB_INTERFACE );
LibUsb.exit( null );
}
catch ( Exception e )
{
mLog.error( "attempt to release USB interface failed", e );
}
}
public void resetUSBBuffer() throws LibUsbException
{
writeRegister( mDeviceHandle, Block.USB, Address.USB_EPA_CTL.getAddress(), 0x1002, 2 );
writeRegister( mDeviceHandle, Block.USB, Address.USB_EPA_CTL.getAddress(), 0x0000, 2 );
}
public static void initBaseband( DeviceHandle handle ) throws LibUsbException
{
/* Initialize USB */
writeRegister( handle, Block.USB, Address.USB_SYSCTL.getAddress(), 0x09, 1 );
writeRegister( handle, Block.USB, Address.USB_EPA_MAXPKT.getAddress(), 0x0002, 2 );
writeRegister( handle, Block.USB, Address.USB_EPA_CTL.getAddress(), 0x1002, 2 );
/* Power on demod */
writeRegister( handle, Block.SYS, Address.DEMOD_CTL_1.getAddress(), 0x22, 1 );
writeRegister( handle, Block.SYS, Address.DEMOD_CTL.getAddress(), 0xE8, 1 );
/* Reset demod */
writeDemodRegister( handle, Page.ONE, (short)0x01, 0x14, 1 ); //Bit 3 = soft reset
writeDemodRegister( handle, Page.ONE, (short)0x01, 0x10, 1 );
/* Disable spectrum inversion and adjacent channel rejection */
writeDemodRegister( handle, Page.ONE, (short)0x15, 0x00, 1 );
writeDemodRegister( handle, Page.ONE, (short)0x16, 0x0000, 2 );
/* Clear DDC shift and IF frequency registers */
writeDemodRegister( handle, Page.ONE, (short)0x16, 0x00, 1 );
writeDemodRegister( handle, Page.ONE, (short)0x17, 0x00, 1 );
writeDemodRegister( handle, Page.ONE, (short)0x18, 0x00, 1 );
writeDemodRegister( handle, Page.ONE, (short)0x19, 0x00, 1 );
writeDemodRegister( handle, Page.ONE, (short)0x1A, 0x00, 1 );
writeDemodRegister( handle, Page.ONE, (short)0x1B, 0x00, 1 );
/* Set FIR coefficients */
for( int x = 0; x < sFIR_COEFFICIENTS.length; x++ )
{
writeDemodRegister( handle,
Page.ONE,
(short)( 0x1C + x ),
sFIR_COEFFICIENTS[ x ],
1 );
}
/* Enable SDR mode, disable DAGC (bit 5) */
writeDemodRegister( handle, Page.ZERO, (short)0x19, 0x05, 1 );
/* Init FSM state-holding register */
writeDemodRegister( handle, Page.ONE, (short)0x93, 0xF0, 1 );
writeDemodRegister( handle, Page.ONE, (short)0x94, 0x0F, 1 );
/* Disable AGC (en_dagc, bit 0) (seems to have no effect) */
writeDemodRegister( handle, Page.ONE, (short)0x11, 0x00, 1 );
/* Disable RF and IF AGC loop */
writeDemodRegister( handle, Page.ONE, (short)0x04, 0x00, 1 );
/* Disable PID filter */
writeDemodRegister( handle, Page.ZERO, (short)0x61, 0x60, 1 );
/* opt_adc_iq = 0, default ADC_I/ADC_Q datapath */
writeDemodRegister( handle, Page.ZERO, (short)0x06, 0x80, 1 );
/* Enable Zero-if mode (en_bbin bit),
* DC cancellation (en_dc_est),
* IQ estimation/compensation (en_iq_comp, en_iq_est) */
writeDemodRegister( handle, Page.ONE, (short)0xB1, 0x1B, 1 );
/* Disable 4.096 MHz clock output on pin TP_CK0 */
writeDemodRegister( handle, Page.ZERO, (short)0x0D, 0x83, 1 );
}
protected void deinitBaseband( DeviceHandle handle )
throws IllegalArgumentException, UsbDisconnectedException, UsbException
{
writeRegister( handle, Block.SYS, Address.DEMOD_CTL.getAddress(), 0x20, 1);
}
/**
* Sets the General Purpose Input/Output (GPIO) register bit
*
* @param handle - USB tuner device
* @param bitMask - bit mask with one for targeted register bits and zero
* for the non-targeted register bits
* @param enabled - true to set the bit and false to clear the bit
* @throws UsbDisconnectedException - if the tuner device is disconnected
* @throws UsbException - if there is a USB error while communicating with
* the device
*/
protected static void setGPIOBit( DeviceHandle handle,
byte bitMask,
boolean enabled ) throws LibUsbException
{
//Get current register value
int value = readRegister( handle, Block.SYS, Address.GPO.getAddress(), 1 );
//Update the masked bits
if( enabled )
{
value |= bitMask;
}
else
{
value &= ~bitMask;
}
//Write the change back to the device
writeRegister( handle, Block.SYS, Address.GPO.getAddress(), value, 1 );
}
/**
* Enables GPIO Output
* @param handle - usb tuner device
* @param bitMask - mask containing one bit value in targeted bit field(s)
* @throws UsbDisconnectedException
* @throws UsbException
*/
protected static void setGPIOOutput( DeviceHandle handle, byte bitMask )
throws LibUsbException
{
//Get current register value
int value = readRegister( handle, Block.SYS, Address.GPD.getAddress(), 1 );
//Mask the value and rewrite it
writeRegister( handle, Block.SYS, Address.GPO.getAddress(),
value & ~bitMask, 1 );
//Get current register value
value = readRegister( handle, Block.SYS, Address.GPOE.getAddress(), 1 );
//Mask the value and rewrite it
writeRegister( handle, Block.SYS, Address.GPOE.getAddress(),
value | bitMask, 1 );
}
protected static void enableI2CRepeater( DeviceHandle handle,
boolean enabled )
throws LibUsbException
{
Page page = Page.ONE;
short address = 1;
int value;
if( enabled )
{
value = 0x18; //ON
}
else
{
value = 0x10; //OFF
}
writeDemodRegister( handle, page, address, value, 1 );
}
protected boolean isI2CRepeaterEnabled() throws SourceException
{
int register = readDemodRegister( mDeviceHandle, Page.ONE, (short)0x1, 1 );
return register == 0x18;
}
protected static int readI2CRegister( DeviceHandle handle,
byte i2CAddress,
byte i2CRegister,
boolean controlI2CRepeater )
throws LibUsbException
{
short address = (short)( i2CAddress & 0xFF );
ByteBuffer buffer = ByteBuffer.allocateDirect( 1 );
buffer.put( i2CRegister );
buffer.rewind();
ByteBuffer data = ByteBuffer.allocateDirect( 1 );
if( controlI2CRepeater )
{
enableI2CRepeater( handle, true );
write( handle, address, Block.I2C, buffer );
read( handle, address, Block.I2C, data );
enableI2CRepeater( handle, false );
}
else
{
write( handle, address, Block.I2C, buffer );
read( handle, address, Block.I2C, data );
}
return (int)( data.get() & 0xFF );
}
protected void writeI2CRegister( DeviceHandle handle,
byte i2CAddress,
byte i2CRegister,
byte value,
boolean controlI2CRepeater ) throws LibUsbException
{
short address = (short)( i2CAddress & 0xFF );
ByteBuffer buffer = ByteBuffer.allocateDirect( 2 );
buffer.put( i2CRegister );
buffer.put( value );
buffer.rewind();
if( controlI2CRepeater )
{
enableI2CRepeater( handle, true );
write( handle, address, Block.I2C, buffer );
enableI2CRepeater( handle, false );
}
else
{
write( handle, address, Block.I2C, buffer );
}
}
protected static void writeDemodRegister( DeviceHandle handle,
Page page,
short address,
int value,
int length ) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( length );
buffer.order( ByteOrder.BIG_ENDIAN );
if( length == 1 )
{
buffer.put( (byte)( value & 0xFF ) );
}
else if( length == 2 )
{
buffer.putShort( (short)( value & 0xFFFF ) );
}
else
{
throw new IllegalArgumentException( "Cannot write value greater "
+ "than 16 bits to the register - length [" + length + "]" );
}
short index = (short)( 0x10 | page.getPage() );
short newAddress = (short)( address << 8 | 0x20 );
write( handle, newAddress, index, buffer );
readDemodRegister( handle, Page.TEN, (short)1, length );
}
protected static int readDemodRegister( DeviceHandle handle,
Page page,
short address,
int length ) throws LibUsbException
{
short index = page.getPage();
short newAddress = (short)( ( address << 8 ) | 0x20 );
ByteBuffer buffer = ByteBuffer.allocateDirect( length );
read( handle, newAddress, index, buffer );
buffer.order( ByteOrder.LITTLE_ENDIAN );
if( length == 2 )
{
return (int)( buffer.getShort() & 0xFFFF );
}
else
{
return (int)( buffer.get() & 0xFF );
}
}
protected static void writeRegister( DeviceHandle handle,
Block block,
short address,
int value,
int length ) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( length );
buffer.order( ByteOrder.BIG_ENDIAN );
if( length == 1 )
{
buffer.put( (byte)( value & 0xFF ) ) ;
}
else if( length == 2 )
{
buffer.putShort( (short)value );
}
else
{
throw new IllegalArgumentException( "Cannot write value greater "
+ "than 16 bits to the register - length [" + length + "]" );
}
buffer.rewind();
write( handle, address, block, buffer );
}
protected static int readRegister( DeviceHandle handle,
Block block,
short address,
int length ) throws LibUsbException
{
ByteBuffer buffer = ByteBuffer.allocateDirect( 2 );
read( handle, address, block, buffer );
buffer.order( ByteOrder.LITTLE_ENDIAN );
if( length == 2 )
{
return (int)( buffer.getShort() & 0xFFFF );
}
else
{
return (int)( buffer.get() & 0xFF );
}
}
/**
*/
protected static void write( DeviceHandle handle,
short address,
Block block,
ByteBuffer buffer ) throws LibUsbException
{
write( handle, address, block.getWriteIndex(), buffer );
}
protected static void write( DeviceHandle handle,
short value,
short index,
ByteBuffer buffer ) throws LibUsbException
{
if( handle != null )
{
int transferred = LibUsb.controlTransfer( handle,
CONTROL_ENDPOINT_OUT,
REQUEST_ZERO,
value,
index,
buffer,
TIMEOUT_US );
if( transferred < 0 )
{
throw new LibUsbException( "error writing byte buffer",
transferred );
}
else if( transferred != buffer.capacity() )
{
throw new LibUsbException( "transferred bytes [" +
transferred + "] is not what was expected [" +
buffer.capacity() + "]", transferred );
}
}
else
{
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
}
/**
* Performs a control type read
*/
protected static void read( DeviceHandle handle,
short address,
short index,
ByteBuffer buffer ) throws LibUsbException
{
if( handle != null )
{
int transferred = LibUsb.controlTransfer( handle,
CONTROL_ENDPOINT_IN,
REQUEST_ZERO,
address,
index,
buffer,
TIMEOUT_US );
if( transferred < 0 )
{
throw new LibUsbException( "read error", transferred );
}
else if( transferred != buffer.capacity() )
{
throw new LibUsbException( "transferred bytes [" +
transferred + "] is not what was expected [" +
buffer.capacity() + "]", transferred );
}
}
else
{
throw new LibUsbException( "device handle is null",
LibUsb.ERROR_NO_DEVICE );
}
}
/**
* Reads byte array from index at the address.
*
* @return big-endian byte array (needs to be swapped to be usable)
*
*/
protected static void read( DeviceHandle handle,
short address,
Block block,
ByteBuffer buffer ) throws LibUsbException
{
read( handle, address, block.getReadIndex(), buffer );
}
/**
* Tests if the specified tuner type is contained in the usb tuner device.
*
* @param type - tuner type to test for
* @param handle - handle to the usb tuner device
* @param controlI2CRepeater - indicates if the method should control the
* I2C repeater independently
*
* @return - true if the device is the specified tuner type
*/
protected static boolean isTuner( TunerTypeCheck type,
DeviceHandle handle,
boolean controlI2CRepeater )
{
try
{
if( type == TunerTypeCheck.FC0012 ||
type == TunerTypeCheck.FC2580 )
{
/* Initialize the GPIOs */
setGPIOOutput( handle, (byte)0x20 );
/* Reset tuner before probing */
setGPIOBit( handle, (byte)0x20, true );
setGPIOBit( handle, (byte)0x20, false );
}
int value = readI2CRegister( handle, type.getI2CAddress(),
type.getCheckAddress(), controlI2CRepeater );
if( type == TunerTypeCheck.FC2580 )
{
return ( ( value & 0x7F ) == type.getCheckValue() );
}
else
{
return ( value == type.getCheckValue() );
}
}
catch( LibUsbException e )
{
//Do nothing ... it's not the specified tuner
}
return false;
}
public int getCurrentSampleRate() throws SourceException
{
return mSampleRate.getRate();
}
public int getSampleRate() throws SourceException
{
try
{
int high= readDemodRegister( mDeviceHandle, Page.ONE, (short)0x9F, 2 );
int low = readDemodRegister( mDeviceHandle, Page.ONE, (short)0xA1, 2 );
int ratio = Integer.rotateLeft( high, 16 ) | low;
int rate = (int)( mOscillatorFrequency * TWO_TO_22_POWER / ratio );
SampleRate sampleRate = SampleRate.getClosest( rate );
/* If we're not currently set to this rate, set it as the current rate */
if( sampleRate.getRate() != rate )
{
setSampleRate( sampleRate );
return sampleRate.getRate();
}
}
catch ( Exception e )
{
throw new SourceException( "RTL2832 Tuner Controller - cannot get "
+ "current sample rate", e );
}
return DEFAULT_SAMPLE_RATE.getRate();
}
public void setSampleRate( SampleRate sampleRate ) throws SourceException
{
/* Write high-order 16-bits of sample rate ratio to demod register */
writeDemodRegister( mDeviceHandle, Page.ONE, (short)0x9F,
sampleRate.getRatioHighBits(), 2 );
/* Write low-order 16-bits of sample rate ratio to demod register */
writeDemodRegister( mDeviceHandle, Page.ONE, (short)0xA1,
sampleRate.getRatioLowBits(), 2 );
/* Set sample rate correction to 0 */
setSampleRateFrequencyCorrection( 0 );
/* Reset the demod for the changes to take effect */
writeDemodRegister( mDeviceHandle, Page.ONE, (short)0x01, 0x14, 1 );
writeDemodRegister( mDeviceHandle, Page.ONE, (short)0x01, 0x10, 1 );
/* Apply any tuner specific sample rate filter settings */
setSampleRateFilters( sampleRate.getRate() );
mSampleRate = sampleRate;
mFrequencyController.setSampleRate( sampleRate.getRate() );
if( mSampleRateMonitor != null )
{
mSampleRateMonitor.setSampleRate( mSampleRate.getRate() );
}
}
public void setSampleRateFrequencyCorrection( int ppm ) throws SourceException
{
int offset = -ppm * TWO_TO_22_POWER / 1000000;
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0x3F,
( offset & 0xFF ),
1 );
writeDemodRegister( mDeviceHandle,
Page.ONE,
(short)0x3E,
( Integer.rotateRight( offset, 8 ) & 0xFF ),
1 );
/* Test to retune controller to apply frequency correction */
try
{
mFrequencyController.setFrequency( mFrequencyController.getFrequency() );
}
catch( Exception e )
{
throw new SourceException( "couldn't set sample rate frequency correction", e );
}
}
public int getSampleRateFrequencyCorrection() throws UsbException
{
int high = readDemodRegister( mDeviceHandle, Page.ONE, (short)0x3E, 1 );
int low = readDemodRegister( mDeviceHandle, Page.ONE, (short)0x3F, 1 );
return ( Integer.rotateLeft( high, 8 ) | low );
}
/**
* Returns contents of the 256-byte EEPROM. The contents are as follows:
*
* 256-byte EEPROM (in hex):
* 00/01 - 2832 Signature
* 03/02 - 0BDA Vendor ID
* 05/04 - 2832 Product ID
* 06 - A5 (has serial id?)
* 07 - 16 (bit field - bit 0 = remote wakeup, bit 1 = IR enabled
* 08 - 02 or 12
* 10/09 0310 ETX(0x03) plus label length (includes length and ETX bytes)
* 12/11 First UTF-16 character
* 14/13 Second UTF-16 character ...
*
* Label 1: vendor
* Label 2: product
* Label 3: serial
* Label 4,5 ... (user defined)
*/
public byte[] readEEPROM( DeviceHandle handle, short offset, int length )
throws IllegalArgumentException
{
if( offset + length > 256 )
{
throw new IllegalArgumentException( "cannot read more than 256 "
+ "bytes from EEPROM - requested to read to byte [" +
( offset + length ) + "]" );
}
byte[] data = new byte[ length ];
ByteBuffer buffer = ByteBuffer.allocateDirect( 1 );
try
{
/* Tell the RTL-2832 to address the EEPROM */
writeRegister( handle, Block.I2C, EEPROM_ADDRESS, (byte)offset, 1 );
}
catch( LibUsbException e )
{
mLog.error( "usb error while attempting to set read address to "
+ "EEPROM register, prior to reading the EEPROM device "
+ "descriptor", e );
}
for( int x = 0; x < length; x++ )
{
try
{
read( handle, EEPROM_ADDRESS, Block.I2C, buffer );
data[ x ] = buffer.get();
buffer.rewind();
}
catch( Exception e )
{
mLog.error( "error while reading eeprom byte [" + x + "/" +
length + "] aborting eeprom read and returning partially "
+ "filled descriptor byte array", e );
x = length;
}
}
return data;
}
/**
* Writes a single byte to the 256-byte EEPROM using the specified offset.
*
* Note: introduce a 5 millisecond delay between each successive write to
* the EEPROM or subsequent writes may fail.
*/
public void writeEEPROMByte( DeviceHandle handle, byte offset, byte value )
throws IllegalArgumentException, UsbDisconnectedException, UsbException
{
if( offset < 0 || offset > 255 )
{
throw new IllegalArgumentException( "RTL2832 Tuner Controller - "
+ "EEPROM offset must be within range of 0 - 255" );
}
int offsetAndValue = Integer.rotateLeft( ( 0xFF & offset ), 8 ) |
( 0xFF & value );
writeRegister( handle, Block.I2C, EEPROM_ADDRESS, offsetAndValue, 2 );
}
public enum Address
{
USB_SYSCTL( 0x2000 ),
USB_CTRL( 0x2010 ),
USB_STAT( 0x2014 ),
USB_EPA_CFG( 0x2144 ),
USB_EPA_CTL( 0x2148 ),
USB_EPA_MAXPKT( 0x2158 ),
USB_EPA_MAXPKT_2( 0x215A ),
USB_EPA_FIFO_CFG( 0x2160 ),
DEMOD_CTL( 0x3000 ),
GPO( 0x3001 ),
GPI( 0x3002 ),
GPOE( 0x3003 ),
GPD( 0x3004 ),
SYSINTE( 0x3005 ),
SYSINTS( 0x3006 ),
GP_CFG0( 0x3007 ),
GP_CFG1( 0x3008 ),
SYSINTE_1( 0x3009 ),
SYSINTS_1( 0x300A ),
DEMOD_CTL_1( 0x300B ),
IR_SUSPEND( 0x300C );
private int mAddress;
private Address( int address )
{
mAddress = address;
}
public short getAddress()
{
return (short)mAddress;
}
}
public enum Page
{
ZERO( 0x0 ),
ONE( 0x1 ),
TEN( 0xA );
private int mPage;
private Page( int page )
{
mPage = page;
}
public byte getPage()
{
return (byte)( mPage & 0xFF );
}
}
public enum SampleMode
{
QUADRATURE, DIRECT;
}
public enum Block
{
DEMOD( 0 ),
USB( 1 ),
SYS( 2 ),
TUN( 3 ),
ROM( 4 ),
IR( 5 ),
I2C( 6 ); //I2C controller
private int mValue;
private Block( int value )
{
mValue = value;
}
public int getValue()
{
return mValue;
}
/**
* Returns the value left shifted 8 bits
*/
public short getReadIndex()
{
return (short)Integer.rotateLeft( mValue, 8 );
}
public short getWriteIndex()
{
return (short)( getReadIndex() | 0x10 );
}
}
/**
* Sample rates supported by the RTL-2832.
*
* Formula to calculate the ratio value:
*
* ratio = ( ( crystal_frequency * 2^22 ) / sample_rate ) & ~3
*
* Default crystal_frequency is 28,800,000
*
* This produces a 32-bit value that has to be set in 2 x 16-bit registers.
* Place the high 16-bit value in ratioMSB and the low 16-bit value in
* ratioLSB. Use integer for these values to avoid sign-extension issues.
*
* Mask the value with 0xFFFF when setting the register.
*/
public enum SampleRate
{
/* Note: sample rates below 1.0MHz are subject to aliasing */
RATE_0_240MHZ( 0x0DFC, 0x0000, 240000, "0.240 MHz" ),
RATE_0_288MHZ( 0x08FC, 0x0000, 288000, "0.288 MHz" ),
RATE_0_912MHZ( 0x07E4, 0x0000, 912000, "0.912 MHz" ),
RATE_0_960MHZ( 0x0778, 0x0000, 960000, "0.960 MHz" ),
RATE_1_200MHZ( 0x05F4, 0x0000, 1200000, "1.200 MHz" ),
RATE_1_440MHZ( 0x04FC, 0x0000, 1440000, "1.440 MHz" ),
RATE_1_680MHZ( 0x0448, 0x0000, 1680000, "1.680 MHz" ),
RATE_1_824MHZ( 0x03F0, 0x0000, 1824000, "1.824 MHz" ),
RATE_2_016MHZ( 0x038C, 0x0000, 2016000, "2.016 MHz" ),
RATE_2_208MHZ( 0x0340, 0x0000, 2208000, "2.208 MHz" ),
RATE_2_400MHZ( 0x02FC, 0x0000, 2400000, "2.400 MHz" ),
RATE_2_640MHZ( 0x02B4, 0x8000, 2640000, "2.640 MHz" ),
RATE_2_880MHZ( 0x027C, 0x0000, 2880000, "2.880 MHz" );
private int mRatioHigh;
private int mRatioLow;
private int mRate;
private String mLabel;
private SampleRate( int ratioHigh,
int ratioLow,
int rate,
String label )
{
mRatioHigh = ratioHigh;
mRatioLow = ratioLow;
mRate = rate;
mLabel = label;
}
public int getRatioHighBits()
{
return mRatioHigh;
}
public int getRatioLowBits()
{
return mRatioLow;
}
public int getRate()
{
return mRate;
}
public String getLabel()
{
return mLabel;
}
public String toString()
{
return mLabel;
}
/**
* Returns the sample rate that is equal to the argument or the next
* higher sample rate
* @param sampleRate
* @return
*/
public static SampleRate getClosest( int sampleRate )
{
for( SampleRate rate: values () )
{
if( rate.getRate() >= sampleRate )
{
return rate;
}
}
return DEFAULT_SAMPLE_RATE;
}
}
/**
* Adds a sample listener. If the buffer processing thread is
* not currently running, starts it running in a new thread.
*/
public void addListener( Listener<ComplexBuffer> listener )
{
mSampleListeners.add( listener );
if( mBufferProcessor == null || !mBufferProcessor.isRunning() )
{
mBufferProcessor = new BufferProcessor();
Thread thread = new Thread( mBufferProcessor );
thread.setDaemon( true );
thread.setName( "RTL2832 Sample Processor" );
thread.start();
}
}
/**
* Removes the sample listener. If this is the last registered listener,
* shuts down the buffer processing thread.
*/
public void removeListener( Listener<ComplexBuffer> listener )
{
mSampleListeners.remove( listener );
if( mSampleListeners.isEmpty() )
{
mBufferProcessor.stop();
}
}
/**
* Dispatches float sample buffers to all registered listeners
*/
public void broadcast( ComplexBuffer buffer )
{
Iterator<Listener<ComplexBuffer>> it = mSampleListeners.iterator();
while( it.hasNext() )
{
Listener<ComplexBuffer> next = it.next();
/* if this is the last (or only) listener, send him the original
* buffer, otherwise send him a copy of the buffer */
if( it.hasNext() )
{
next.receive( buffer.copyOf() );
}
else
{
next.receive( buffer );
}
}
}
/**
* Buffer processing thread. Fetches samples from the RTL2832 Tuner and
* dispatches them to all registered listeners
*/
public class BufferProcessor implements Runnable, TransferCallback
{
private ScheduledExecutorService mExecutor =
Executors.newScheduledThreadPool( 2 );
private ScheduledFuture<?> mSampleDispatcherTask;
private ScheduledFuture<?> mSampleRateCounterTask;
private CopyOnWriteArrayList<Transfer> mTransfers;
private AtomicBoolean mRunning = new AtomicBoolean();
@Override
public void run()
{
if( mRunning.compareAndSet( false, true ) )
{
mLog.debug( "rtl2832 [" + getUniqueID() +
"] - starting sample fetch thread" );
try
{
setSampleRate( mSampleRate );
resetUSBBuffer();
}
catch( SourceException e )
{
mLog.error( "couldn't start buffer processor", e );
mRunning.set( false );
}
prepareTransfers();
for( Transfer transfer: mTransfers )
{
int result = LibUsb.submitTransfer( transfer );
if( result != LibUsb.SUCCESS )
{
mLog.error( "error submitting transfer [" +
LibUsb.errorName( result ) + "]" );
break;
}
}
mSampleDispatcherTask = mExecutor
.scheduleAtFixedRate( new BufferDispatcher(),
0, 20, TimeUnit.MILLISECONDS );
mSampleRateMonitor =
new SampleRateMonitor( mSampleRate.getRate() );
mSampleRateCounterTask = mExecutor
.scheduleAtFixedRate( mSampleRateMonitor,
10, 10, TimeUnit.SECONDS );
while( mRunning.get() )
{
ByteBuffer completed = ByteBuffer.allocateDirect( 4 );
int result = LibUsb.handleEventsTimeoutCompleted(
null, TIMEOUT_US, completed.asIntBuffer() );
if( result != LibUsb.SUCCESS )
{
mLog.error( "error handling events for libusb" );
}
}
}
}
/**
* Stops the sample fetching thread
*/
public void stop()
{
if( mRunning.compareAndSet( true, false ) )
{
mLog.debug( "rtl2832 [" + getUniqueID() +
"] - stopping sample fetch thread" );
cancel();
if( mSampleDispatcherTask != null )
{
mSampleDispatcherTask.cancel( true );
mSampleRateCounterTask.cancel( true );
mFilledBuffers.clear();
}
}
}
/**
* Indicates if this thread is running
*/
public boolean isRunning()
{
return mRunning.get();
}
@Override
public void processTransfer( Transfer transfer )
{
if( transfer.status() == LibUsb.TRANSFER_COMPLETED )
{
ByteBuffer buffer = transfer.buffer();
byte[] data = new byte[ transfer.actualLength() ];
buffer.get( data );
buffer.rewind();
mFilledBuffers.add( data );
mSampleCounter.addAndGet( transfer.actualLength() );
if( !isRunning() )
{
LibUsb.cancelTransfer( transfer );
}
}
switch( transfer.status() )
{
case LibUsb.TRANSFER_COMPLETED:
/* resubmit the transfer */
int result = LibUsb.submitTransfer( transfer );
if( result != LibUsb.SUCCESS )
{
mLog.error( "couldn't resubmit buffer transfer to tuner" );
LibUsb.freeTransfer( transfer );
mTransfers.remove( transfer );
}
break;
case LibUsb.TRANSFER_CANCELLED:
/* free the transfer and remove it */
LibUsb.freeTransfer( transfer );
mTransfers.remove( transfer );
break;
default:
/* unexpected error */
mLog.error( "transfer error [" +
getTransferStatus( transfer.status() ) +
"] transferred actual: " + transfer.actualLength() );
}
}
private void cancel()
{
for( Transfer transfer: mTransfers )
{
LibUsb.cancelTransfer( transfer );
}
ByteBuffer completed = ByteBuffer.allocateDirect( 4 );
int result = LibUsb.handleEventsTimeoutCompleted(
null, TIMEOUT_US, completed.asIntBuffer() );
if( result != LibUsb.SUCCESS )
{
mLog.error( "error handling usb events during cancel [" +
LibUsb.errorName( result ) + "]" );
}
}
/**
* Prepares (allocates) a set of transfer buffers for use in
* transferring data from the tuner via the bulk interface
*/
private void prepareTransfers() throws LibUsbException
{
mTransfers = new CopyOnWriteArrayList<Transfer>();
for( int x = 0; x < TRANSFER_BUFFER_POOL_SIZE; x++ )
{
Transfer transfer = LibUsb.allocTransfer();
if( transfer == null )
{
throw new LibUsbException( "couldn't allocate transfer",
LibUsb.ERROR_NO_MEM );
}
final ByteBuffer buffer =
ByteBuffer.allocateDirect( mBufferSize );
LibUsb.fillBulkTransfer( transfer,
mDeviceHandle,
BULK_ENDPOINT_IN,
buffer,
BufferProcessor.this,
"Buffer #" + x,
TIMEOUT_US );
mTransfers.add( transfer );
}
}
}
/**
* Fetches byte[] chunks from the raw sample buffer. Converts each byte
* array and broadcasts the array to all registered listeners
*/
public class BufferDispatcher implements Runnable
{
@Override
public void run()
{
try
{
ArrayList<byte[]> buffers = new ArrayList<byte[]>();
mFilledBuffers.drainTo( buffers );
for( byte[] buffer: buffers )
{
float[] samples = mSampleAdapter.convert( buffer );
broadcast( new ComplexBuffer( samples ) );
}
}
catch( Exception e )
{
mLog.error( "error duing rtl2832 buffer dispatcher run", e );
}
}
}
public static String getTransferStatus( int status )
{
switch( status )
{
case 0:
return "TRANSFER COMPLETED (0)";
case 1:
return "TRANSFER ERROR (1)";
case 2:
return "TRANSFER TIMED OUT (2)";
case 3:
return "TRANSFER CANCELLED (3)";
case 4:
return "TRANSFER STALL (4)";
case 5:
return "TRANSFER NO DEVICE (5)";
case 6:
return "TRANSFER OVERFLOW (6)";
default:
return "UNKNOWN TRANSFER STATUS (" + status + ")";
}
}
/**
* Averages the sample rate over a 10-second period. The count is for the
* number of bytes received from the tuner. There are two bytes for each
* sample. So, we divide by 20 to get the average sample rate.
*/
public class SampleRateMonitor implements Runnable
{
private static final int BUFFER_SIZE = 5;
private int mTargetSampleRate;
private int mSampleRateMinimum;
private int mSampleRateMaximum;
private int mNewTargetSampleRate;
private FloatAveragingBuffer mRateErrorBuffer =
new FloatAveragingBuffer( BUFFER_SIZE );
private AtomicBoolean mRateChanged = new AtomicBoolean();
public SampleRateMonitor( int sampleRate )
{
setTargetRate( sampleRate );
}
public void setSampleRate( int sampleRate )
{
mNewTargetSampleRate = sampleRate;
mRateChanged.set( true );
}
private void setTargetRate( int rate )
{
mTargetSampleRate = rate;
mSampleRateMinimum = (int)( (float)mTargetSampleRate * 0.95f );
mSampleRateMaximum = (int)( (float)mTargetSampleRate * 1.05f );
for( int x = 0; x < BUFFER_SIZE; x++ )
{
mRateErrorBuffer.get( 0 );
}
}
@Override
public void run()
{
if( mRateChanged.compareAndSet( true, false ) )
{
setTargetRate( mNewTargetSampleRate );
/* Reset the sample counter */
mSampleCounter.set( 0 );
mLog.info( "monitor reset for new sample rate [" + mTargetSampleRate + "]" );
}
else
{
int count = mSampleCounter.getAndSet( 0 );
float current = (float)count / 20.0f;
/**
* Only accept values +/- 5% of target rate
*/
float average;
if( mSampleRateMinimum < current && current < mSampleRateMaximum )
{
average = mRateErrorBuffer.get( (float)mTargetSampleRate - current );
/* broadcast an actual sample rate update */
if( mFrequencyController != null )
{
mFrequencyController.broadcastFrequencyChangeEvent(
new FrequencyChangeEvent(
Attribute.SAMPLE_RATE_ERROR, (int)average ) );
}
}
else
{
average = mTargetSampleRate;
}
StringBuilder sb = new StringBuilder();
sb.append( "[" );
if( mDescriptor != null )
{
sb.append( mDescriptor.getSerial() );
}
else
{
sb.append( "DESCRIPTOR IS NULL" );
}
sb.append( "] sample rate current [" );
sb.append( mDecimalFormatter.format( current ) );
sb.append( " Hz " );
sb.append( mPercentFormatter.format( 100.0f * ( current / (float)mTargetSampleRate ) ) );
sb.append( "% ] error [" );
sb.append( average );
sb.append( " Hz ] target " );
sb.append( mDecimalFormatter.format( mTargetSampleRate ) );
mLog.info( sb.toString() );
}
}
}
/**
* RTL2832 EEPROM byte array descriptor parsing class
*/
public class Descriptor
{
private byte[] mData;
private ArrayList<String> mLabels = new ArrayList<String>();
public Descriptor( byte[] data )
{
if( data != null )
{
mData = data;
}
else
{
data = new byte[ 256 ];
}
getLabels();
}
public boolean isValid()
{
return mData[ 0 ] == (byte)0x28 &&
mData[ 1 ] == (byte)0x32;
}
public String getVendorID()
{
int id = Integer.rotateLeft( ( 0xFF & mData[ 3] ), 8 ) |
( 0xFF & mData[ 2 ] );
return String.format("%04X", id );
}
public String getVendorLabel()
{
return mLabels.get( 0 );
}
public String getProductID()
{
int id = Integer.rotateLeft( ( 0xFF & mData[ 5] ), 8 ) |
( 0xFF & mData[ 4 ] );
return String.format("%04X", id );
}
public String getProductLabel()
{
return mLabels.get( 1 );
}
public boolean hasSerial()
{
return mData[ 6 ] == (byte)0xA5;
}
public String getSerial()
{
return mLabels.get( 2 );
}
public boolean remoteWakeupEnabled()
{
byte mask = (byte)0x01;
return ( mData[ 7 ] & mask ) == mask;
}
public boolean irEnabled()
{
byte mask = (byte)0x02;
return ( mData[ 7 ] & mask ) == mask;
}
private void getLabels()
{
mLabels.clear();
int start = 0x09;
while( start < 256 )
{
start = getLabel( start );
}
}
private int getLabel( int start )
{
/* Validate length and check second byte for ETX (0x03) */
if( start > 254 || mData[ start + 1 ] != (byte)0x03 )
{
return 256;
}
/* Get label length, including the length and ETX bytes */
int length = 0xFF & mData[ start ];
if( start + length > 255 )
{
return 256;
}
/* Get the label bytes */
byte[] data = Arrays.copyOfRange( mData, start + 2, start + length );
/* Translate the bytes as UTF-16 Little Endian and store the label */
String label = new String( data, Charset.forName( "UTF-16LE" ) );
mLabels.add( label );
return start + length;
}
public String toString()
{
StringBuilder sb = new StringBuilder();
sb.append( "RTL-2832 EEPROM Descriptor\n" );
sb.append( "Vendor: " );
sb.append( getVendorID() );
sb.append( " [" );
sb.append( getVendorLabel() );
sb.append( "]\n" );
sb.append( "Product: " );
sb.append( getProductID() );
sb.append( " [" );
sb.append( getProductLabel() );
sb.append( "]\n" );
sb.append( "Serial: " );
if( hasSerial() )
{
sb.append( "yes [" );
sb.append( getSerial() );
sb.append( "]\n" );
}
else
{
sb.append( "no\n" );
}
sb.append( "Remote Wakeup Enabled: " );
sb.append( ( remoteWakeupEnabled() ? "yes" : "no" ) );
sb.append( "\n" );
sb.append( "IR Enabled: " );
sb.append( ( irEnabled() ? "yes" : "no" ) );
sb.append( "\n" );
if( mLabels.size() > 3 )
{
sb.append( "Additional Labels: " );
for( int x = 3; x < mLabels.size(); x++ )
{
sb.append( " [" );
sb.append( mLabels.get( x ) );
sb.append( "\n" );
}
}
return sb.toString();
}
}
public class USBEventHandlingThread implements Runnable
{
/** If thread should abort. */
private volatile boolean mAbort;
/**
* Aborts the event handling thread.
*/
public void abort()
{
mAbort = true;
}
@Override
public void run()
{
while ( !mAbort )
{
int result = LibUsb.handleEventsTimeout( null, 1000 );
if ( result != LibUsb.SUCCESS )
{
mAbort = true;
mLog.error( "error handling usb events [" +
LibUsb.errorName( result ) + "]" );
throw new LibUsbException("Unable to handle USB "
+ "events", result );
}
}
}
}
public enum TunerTypeCheck
{
E4K( 0xC8, 0x02, 0x40 ),
FC0012( 0xC6, 0x00, 0xA1 ),
FC0013( 0xC6, 0x00, 0xA3 ),
FC2580( 0xAC, 0x01, 0x56 ),
R820T( 0x34, 0x00, 0x69 ),
R828D( 0x74, 0x00, 0x69 );
private int mI2CAddress;
private int mCheckAddress;
private int mCheckValue;
private TunerTypeCheck( int i2c, int address, int value )
{
mI2CAddress = i2c;
mCheckAddress = address;
mCheckValue = value;
}
public byte getI2CAddress()
{
return (byte)mI2CAddress;
}
public byte getCheckAddress()
{
return (byte)mCheckAddress;
}
public byte getCheckValue()
{
return (byte)mCheckValue;
}
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 buffer;
public class ByteArrayDelayBuffer
{
private int mBufferSize;
private byte[][] mBuffer = null;
private int mBufferPointer = 0;
/**
* Implements a delay buffer for byte arrays. As a new byte[] is placed
* into the buffer, the oldest byte[] is returned
* @param bufferSize - number of byte arrays to buffer
*/
public ByteArrayDelayBuffer( int bufferSize )
{
mBufferSize = bufferSize;
}
/**
* Inserts new bytes into the buffer
*
* @return - oldest byte[] from the buffer, or null if the buffer is not
* yet full
*/
public byte[] get( byte[] bytes )
{
if( mBuffer == null )
{
mBuffer = new byte[ mBufferSize ][ bytes.length ];
}
byte[] returnBytes = mBuffer[ mBufferPointer ];
mBuffer[ mBufferPointer++ ] = bytes;
if( mBufferPointer >= mBufferSize )
{
mBufferPointer = 0;
}
return returnBytes;
}
}
<file_sep>package decode.p25.message.tsbk;
import alias.AliasList;
import bits.BinaryMessage;
import decode.p25.message.tsbk.motorola.ControlChannelBaseStationIdentification;
import decode.p25.message.tsbk.motorola.MotorolaOpcode;
import decode.p25.message.tsbk.motorola.MotorolaTSBKMessage;
import decode.p25.message.tsbk.motorola.PatchGroupAdd;
import decode.p25.message.tsbk.motorola.PatchGroupDelete;
import decode.p25.message.tsbk.motorola.PatchGroupVoiceChannelGrant;
import decode.p25.message.tsbk.motorola.PatchGroupVoiceChannelGrantUpdate;
import decode.p25.message.tsbk.motorola.PlannedControlChannnelShutdown;
import decode.p25.message.tsbk.motorola.SystemLoading;
import decode.p25.message.tsbk.motorola.TrafficChannelBaseStationIdentification;
import decode.p25.message.tsbk.osp.control.AcknowledgeResponse;
import decode.p25.message.tsbk.osp.control.AdjacentStatusBroadcast;
import decode.p25.message.tsbk.osp.control.AuthenticationCommand;
import decode.p25.message.tsbk.osp.control.CallAlert;
import decode.p25.message.tsbk.osp.control.DenyResponse;
import decode.p25.message.tsbk.osp.control.ExtendedFunctionCommand;
import decode.p25.message.tsbk.osp.control.GroupAffiliationQuery;
import decode.p25.message.tsbk.osp.control.GroupAffiliationResponse;
import decode.p25.message.tsbk.osp.control.IdentifierUpdateNonVUHF;
import decode.p25.message.tsbk.osp.control.IdentifierUpdateVUHF;
import decode.p25.message.tsbk.osp.control.LocationRegistrationResponse;
import decode.p25.message.tsbk.osp.control.MessageUpdate;
import decode.p25.message.tsbk.osp.control.NetworkStatusBroadcast;
import decode.p25.message.tsbk.osp.control.ProtectionParameterUpdate;
import decode.p25.message.tsbk.osp.control.QueuedResponse;
import decode.p25.message.tsbk.osp.control.RFSSStatusBroadcast;
import decode.p25.message.tsbk.osp.control.RadioUnitMonitorCommand;
import decode.p25.message.tsbk.osp.control.RoamingAddressCommand;
import decode.p25.message.tsbk.osp.control.SecondaryControlChannelBroadcast;
import decode.p25.message.tsbk.osp.control.SecondaryControlChannelBroadcastExplicit;
import decode.p25.message.tsbk.osp.control.StatusQuery;
import decode.p25.message.tsbk.osp.control.StatusUpdate;
import decode.p25.message.tsbk.osp.control.SystemServiceBroadcast;
import decode.p25.message.tsbk.osp.control.TimeAndDateAnnouncement;
import decode.p25.message.tsbk.osp.control.UnitDeregistrationAcknowledge;
import decode.p25.message.tsbk.osp.control.UnitRegistrationCommand;
import decode.p25.message.tsbk.osp.control.UnitRegistrationResponse;
import decode.p25.message.tsbk.osp.data.GroupDataChannelAnnouncement;
import decode.p25.message.tsbk.osp.data.GroupDataChannelAnnouncementExplicit;
import decode.p25.message.tsbk.osp.data.GroupDataChannelGrant;
import decode.p25.message.tsbk.osp.data.IndividualDataChannelGrant;
import decode.p25.message.tsbk.osp.data.SNDCPDataChannelAnnouncementExplicit;
import decode.p25.message.tsbk.osp.data.SNDCPDataChannelGrant;
import decode.p25.message.tsbk.osp.data.SNDCPDataPageRequest;
import decode.p25.message.tsbk.osp.voice.GroupVoiceChannelGrant;
import decode.p25.message.tsbk.osp.voice.GroupVoiceChannelGrantUpdate;
import decode.p25.message.tsbk.osp.voice.GroupVoiceChannelGrantUpdateExplicit;
import decode.p25.message.tsbk.osp.voice.TelephoneInterconnectAnswerRequest;
import decode.p25.message.tsbk.osp.voice.TelephoneInterconnectVoiceChannelGrant;
import decode.p25.message.tsbk.osp.voice.UnitToUnitAnswerRequest;
import decode.p25.message.tsbk.osp.voice.UnitToUnitVoiceChannelGrant;
import decode.p25.message.tsbk.osp.voice.UnitToUnitVoiceChannelGrantUpdate;
import decode.p25.reference.DataUnitID;
import decode.p25.reference.Opcode;
import decode.p25.reference.Vendor;
public class TSBKMessageFactory
{
public static TSBKMessage getMessage( BinaryMessage message,
DataUnitID duid,
AliasList aliasList )
{
Vendor vendor = Vendor.fromValue(
message.getInt( TSBKMessage.VENDOR_ID ) );
switch( vendor )
{
case STANDARD:
Opcode opcode =
Opcode.fromValue( message.getInt( TSBKMessage.OPCODE ) );
switch( opcode )
{
case ACKNOWLEDGE_RESPONSE:
return new AcknowledgeResponse( message, duid,
aliasList );
case ADJACENT_STATUS_BROADCAST:
return new AdjacentStatusBroadcast( message, duid,
aliasList );
case AUTHENTICATION_COMMAND:
return new AuthenticationCommand( message, duid,
aliasList );
case CALL_ALERT:
return new CallAlert( message, duid, aliasList );
case DENY_RESPONSE:
return new DenyResponse( message, duid, aliasList );
case EXTENDED_FUNCTION_COMMAND:
return new ExtendedFunctionCommand( message, duid,
aliasList );
case GROUP_AFFILIATION_QUERY:
return new GroupAffiliationQuery( message, duid,
aliasList );
case GROUP_AFFILIATION_RESPONSE:
return new GroupAffiliationResponse( message, duid,
aliasList );
case GROUP_DATA_CHANNEL_ANNOUNCEMENT:
return new GroupDataChannelAnnouncement( message, duid,
aliasList );
case GROUP_DATA_CHANNEL_ANNOUNCEMENT_EXPLICIT:
return new GroupDataChannelAnnouncementExplicit(
message, duid, aliasList );
case GROUP_DATA_CHANNEL_GRANT:
return new GroupDataChannelGrant( message, duid,
aliasList );
case GROUP_VOICE_CHANNEL_GRANT:
return new GroupVoiceChannelGrant( message, duid,
aliasList );
case GROUP_VOICE_CHANNEL_GRANT_UPDATE:
return new GroupVoiceChannelGrantUpdate( message, duid,
aliasList );
case GROUP_VOICE_CHANNEL_GRANT_UPDATE_EXPLICIT:
return new GroupVoiceChannelGrantUpdateExplicit( message,
duid, aliasList );
case IDENTIFIER_UPDATE_NON_VUHF:
return new IdentifierUpdateNonVUHF( message, duid,
aliasList );
case IDENTIFIER_UPDATE_VHF_UHF_BANDS:
return new IdentifierUpdateVUHF( message, duid,
aliasList );
case INDIVIDUAL_DATA_CHANNEL_GRANT:
return new IndividualDataChannelGrant( message, duid,
aliasList );
case LOCATION_REGISTRATION_RESPONSE:
return new LocationRegistrationResponse( message, duid,
aliasList );
case MESSAGE_UPDATE:
return new MessageUpdate( message, duid, aliasList );
case NETWORK_STATUS_BROADCAST:
return new NetworkStatusBroadcast( message, duid,
aliasList );
case QUEUED_RESPONSE:
return new QueuedResponse( message, duid, aliasList );
case PROTECTION_PARAMETER_UPDATE:
return new ProtectionParameterUpdate( message, duid,
aliasList );
case RADIO_UNIT_MONITOR_COMMAND:
return new RadioUnitMonitorCommand( message, duid,
aliasList );
case RFSS_STATUS_BROADCAST:
return new RFSSStatusBroadcast( message, duid,
aliasList );
case ROAMING_ADDRESS_COMMAND:
return new RoamingAddressCommand( message, duid,
aliasList );
case SECONDARY_CONTROL_CHANNEL_BROADCAST:
return new SecondaryControlChannelBroadcast( message,
duid, aliasList );
case SECONDARY_CONTROL_CHANNEL_BROADCAST_EXPLICIT:
return new SecondaryControlChannelBroadcastExplicit(
message, duid, aliasList );
case SNDCP_DATA_CHANNEL_GRANT:
return new SNDCPDataChannelGrant( message, duid,
aliasList );
case SNDCP_DATA_CHANNEL_ANNOUNCEMENT_EXPLICIT:
return new SNDCPDataChannelAnnouncementExplicit(
message, duid, aliasList );
case SNDCP_DATA_PAGE_REQUEST:
return new SNDCPDataPageRequest( message, duid,
aliasList );
case STATUS_QUERY:
return new StatusQuery( message, duid, aliasList );
case STATUS_UPDATE:
return new StatusUpdate( message, duid, aliasList );
case SYSTEM_SERVICE_BROADCAST:
return new SystemServiceBroadcast( message, duid,
aliasList );
case TELEPHONE_INTERCONNECT_ANSWER_REQUEST:
return new TelephoneInterconnectAnswerRequest(
message, duid, aliasList );
case TELEPHONE_INTERCONNECT_VOICE_CHANNEL_GRANT:
return new TelephoneInterconnectVoiceChannelGrant(
message, duid, aliasList );
case TIME_DATE_ANNOUNCEMENT:
return new TimeAndDateAnnouncement( message, duid,
aliasList );
case UNIT_DEREGISTRATION_ACKNOWLEDGE:
return new UnitDeregistrationAcknowledge( message,
duid, aliasList );
case UNIT_REGISTRATION_COMMAND:
return new UnitRegistrationCommand( message, duid,
aliasList );
case UNIT_REGISTRATION_RESPONSE:
return new UnitRegistrationResponse( message, duid,
aliasList );
case UNIT_TO_UNIT_ANSWER_REQUEST:
return new UnitToUnitAnswerRequest( message, duid,
aliasList );
case UNIT_TO_UNIT_VOICE_CHANNEL_GRANT:
return new UnitToUnitVoiceChannelGrant( message,
duid, aliasList );
case UNIT_TO_UNIT_VOICE_CHANNEL_GRANT_UPDATE:
return new UnitToUnitVoiceChannelGrantUpdate( message,
duid, aliasList );
default:
return new TSBKMessage( message, duid, aliasList );
}
case MOTOROLA:
MotorolaOpcode motorolaOpcode = MotorolaOpcode.
fromValue( message.getInt( TSBKMessage.OPCODE ) );
switch( motorolaOpcode )
{
case CCH_PLANNED_SHUTDOWN:
return new PlannedControlChannnelShutdown( message, duid, aliasList );
case CONTROL_CHANNEL_ID:
return new ControlChannelBaseStationIdentification( message, duid, aliasList );
case PATCH_GROUP_ADD:
return new PatchGroupAdd( message, duid, aliasList );
case PATCH_GROUP_DELETE:
return new PatchGroupDelete( message, duid, aliasList );
case PATCH_GROUP_CHANNEL_GRANT:
return new PatchGroupVoiceChannelGrant( message, duid, aliasList );
case PATCH_GROUP_CHANNEL_GRANT_UPDATE:
return new PatchGroupVoiceChannelGrantUpdate( message, duid, aliasList );
case SYSTEM_LOAD:
return new SystemLoading( message, duid, aliasList );
case TRAFFIC_CHANNEL_ID:
return new TrafficChannelBaseStationIdentification( message, duid, aliasList );
default:
}
return new MotorolaTSBKMessage( message, duid, aliasList );
default:
return new TSBKMessage( message, duid, aliasList );
}
}
}
<file_sep>package spectrum.menu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JCheckBoxMenuItem;
import spectrum.DFTProcessor;
public class FrameRateItem extends JCheckBoxMenuItem
{
private static final long serialVersionUID = 1L;
private DFTProcessor mDFTProcessor;
private int mFrameRate;
public FrameRateItem( DFTProcessor processor, int frameRate )
{
super( String.valueOf( frameRate ) );
mDFTProcessor = processor;
mFrameRate = frameRate;
if( processor.getFrameRate() == mFrameRate )
{
setSelected( true );
}
addActionListener( new ActionListener()
{
@Override
public void actionPerformed( ActionEvent arg0 )
{
mDFTProcessor.setFrameRate( mFrameRate );
}
} );
}
}
<file_sep>/*******************************************************************************
* SDR Trunk
* Copyright (C) 2014 <NAME>
*
* 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 audio;
/**
* Standard voice inversion foldover frequencies
*
* Reference: http://en.wikipedia.org/wiki/Voice_inversion
*/
public enum InversionFrequency
{
HZ_2500( 2500 ),
HZ_2550( 2550 ),
HZ_2600( 2600 ),
HZ_2632( 2632 ),
HZ_2675( 2675 ),
HZ_2718( 2718 ),
HZ_2800( 2800 ),
HZ_2868( 2868 ),
HZ_2950( 2950 ),
HZ_3023( 3023 ),
HZ_3075( 3075 ),
HZ_3107( 3107 ),
HZ_3150( 3150 ),
HZ_3196( 3196 ),
HZ_3333( 3333 ),
HZ_3339( 3339 ),
HZ_3400( 3400 ),
HZ_3496( 3496 ),
HZ_3729( 3729 ),
HZ_4096( 4096 );
private int mFrequency;
private InversionFrequency( int frequency )
{
mFrequency = frequency;
}
public int getFrequency()
{
return mFrequency;
}
}
|
5d0625353bf671fb88776129c1d80a4303920c68
|
[
"Java",
"Ant Build System",
"Shell"
] | 248 |
Java
|
brock/sdrtrunk
|
538a2992465d8233b67d1c2ee60339216e54062c
|
a58a83f591378a1e58a489727bae99d9521a33f3
|
refs/heads/master
|
<file_sep>package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"github.com/gorilla/mux"
)
var (
errTeamEmpty = errors.New("Team name is empty")
)
func (s *Service) teamsPOST(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log.Print("Service.teamsPOST")
_, err := checkAuthEmail(r)
if err != nil {
s.InternalServerError(w, errNoAuthEmail)
return
}
var v struct {
Name string `json:"name"`
}
err = json.NewDecoder(r.Body).Decode(&v)
if err != nil {
s.BadRequest(w, err)
return
}
if v.Name == "" {
s.BadRequest(w, errTeamEmpty)
return
}
err = s.db.CreateTeam(ctx, v.Name)
if err != nil {
s.BadRequest(w, err)
return
}
s.OK(w)
}
func (s *Service) teamsGET(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log.Print("Service.teamsGET")
_, err := checkAuthEmail(r)
if err != nil {
s.InternalServerError(w, errNoAuthEmail)
return
}
teams := s.db.ListTeams(ctx)
s.Json(w, teams)
}
func (s *Service) teamsPUT(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log.Print("Service.teamsPUT")
email, err := checkAuthEmail(r)
if err != nil {
s.InternalServerError(w, errNoAuthEmail)
return
}
vars := mux.Vars(r)
team := vars["team"]
if team == "" {
s.BadRequest(w, errTeamEmpty)
return
}
err = s.db.AddVolunteer(ctx, team, email)
if err != nil {
s.BadRequest(w, err)
return
}
s.OK(w)
}
<file_sep>package main
import (
"context"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"testing"
)
const (
POSTGRES_CONN = "user=postgres dbname=postgres sslmode=disable host=localhost"
)
var conns = []struct {
name string
conn string
}{
{"mockdb", ""},
{"postgres", POSTGRES_CONN},
}
//TestDB tests the db operation of mock db and postgres db
func TestDB(t *testing.T) {
ctx := context.Background()
assert := assert.New(t)
require := require.New(t)
for _, tt := range conns {
t.Run(tt.name, func(t *testing.T) {
var db DBer
db, err := NewDBer(tt.conn)
if err != nil {
t.Skip()
}
require.NoError(err)
err = db.StoreVolunteer(ctx, "<EMAIL>", "AlexanderTheGreat")
assert.NoError(err)
err = db.StoreVolunteer(ctx, "<EMAIL>", "AlexanderTheGreat")
assert.Error(err)
err = db.CheckVolunteer(ctx, "no@user", "")
assert.Error(err)
err = db.CheckVolunteer(ctx, "<EMAIL>", "AlexanderTheGreat!")
assert.Error(err)
err = db.CheckVolunteer(ctx, "<EMAIL>", "AlexanderTheGreat")
assert.NoError(err)
// add team
// TODO subtest?
teams := db.ListTeams(ctx)
assert.Equal(0, len(teams))
err = db.CreateTeam(ctx, "TEAM-A")
assert.NoError(err)
teams = db.ListTeams(ctx)
require.Equal(1, len(teams))
assert.Equal("TEAM-A", teams[0])
err = db.CreateTeam(ctx, "TEAM-A")
assert.Error(err)
assert.Equal(errTeamAlreadyStored, err)
err = db.CreateTeam(ctx, "TEAM-B")
assert.NoError(err)
// list teams
teams = db.ListTeams(ctx)
assert.Equal(2, len(teams))
assert.Equal("TEAM-A", teams[0])
assert.Equal("TEAM-B", teams[1])
err = db.AddVolunteer(ctx, "no-team", "")
assert.Error(err)
assert.Equal(errTeamNotFound, err)
err = db.AddVolunteer(ctx, "TEAM-A", "<EMAIL>")
assert.Error(err)
assert.Equal(errVolunteerNotFound, err)
err = db.AddVolunteer(ctx, "TEAM-A", "<EMAIL>")
assert.NoError(err)
err = db.AddVolunteer(ctx, "TEAM-A", "<EMAIL>")
assert.Error(err)
assert.Equal(errVolunteerAlreadyStored, err)
// list volunteers info
err = db.StoreVolunteer(ctx, "<EMAIL>", "GaiusJuliusCaesar")
assert.NoError(err)
err = db.AddVolunteer(ctx, "TEAM-A", "<EMAIL>")
assert.NoError(err)
vinfo, err := db.GetVolunteerInfo(ctx, "<EMAIL>")
assert.NoError(err)
require.Equal(1, len(vinfo.Teams))
assert.Equal("TEAM-A", vinfo.Teams[0])
err = db.AddVolunteer(ctx, "TEAM-B", "<EMAIL>")
assert.NoError(err)
vinfo, err = db.GetVolunteerInfo(ctx, "<EMAIL>")
assert.NoError(err)
require.Equal(2, len(vinfo.Teams))
assert.Equal("TEAM-A", vinfo.Teams[0])
assert.Equal("TEAM-B", vinfo.Teams[1])
})
}
}
<file_sep>CREATE SCHEMA gwi;
CREATE TABLE gwi.volunteer (
id BIGSERIAL PRIMARY KEY,
email TEXT UNIQUE,
hash BYTEA NOT NULL,
salt BYTEA NOT NULL,
CHECK(position('@' IN email) > 0)
);
CREATE INDEX idx_gwi_volunteer_email ON gwi.volunteer(email);
CREATE TABLE gwi.team (
id BIGSERIAL PRIMARY KEY,
name TEXT UNIQUE NOT NULL
);
CREATE INDEX idx_gwi_team_name ON gwi.team(name);
CREATE TABLE gwi.signup (
volunteer_id BIGSERIAL REFERENCES gwi.volunteer(id),
team_id BIGSERIAL REFERENCES gwi.team(id),
UNIQUE (volunteer_id, team_id)
);
-- explain anaylze verbose found seq scan in query returning named of tests for user
-- drops cost from 14-40 -> 0.15..9.21
CREATE INDEX idx_gwi_signup_team_id ON gwi.signup(team_id);
<file_sep># Volunteers
Create an http API application that provides the following functionality โฆ
## Volunteer API
Allows creating a volunteer with a unique login (can be email) without any
kind of authentication or authorization
## oauth2 like token generation
```
POST /api/v1/volunteers
{"user" : "<EMAIL>", grant_type="password", "password": <PASSWORD>"}
// generate confirm link with oauth token
{"token": "token",
"token_type": "bearer",
"expires_in": 3600
}
```
o Allows any volunteer to retrieve information about himself only
```
GET /api/v1/volunteers/profile
Authorization: Bearer + token
{"email:" "<EMAIL>", teams: [{}, {}, {}]}
```
## Teams API
Allows any authenticated volunteer to create a team (described only by some
unique identifier + potentially a name), read and also sign up for any team
without restrictions.
## create
POST /api/v1/teams
{"name" : "name"}
## list
GET /api/v1/teams
## signup
PUT /api/v1/team/<name>
## Developer notes
Build: go build (requires 1.12)
Unit Test: go test -v
Unit Test (incl SQL coe): ./testdata/01psql and go test -v
Integration test: ./test.sh (need bash, curl and jq installed)
## Run API server
With MockDB
```sh
./gwi
```
With Postgresql
```
./testdata/01psql
#other tab
./gwi -c "user=postgres dbname=postgres sslmode=disable host=localhost"
```
## Highlights
1. Use oauth2-like (did not check the 100% compatibility) schema for generating tokens
2. Tokens and cryptographically signed (hmac+sha256 + private key)
3. Tokens are time bounded (24 hours)
4. User password are hashed using `scrypt` state of the art password hashing function and with salt
5. Only hash and salt are stored in DB!
6. There is clean and tested DBer interface between HTTP API and database
7. `MockDB` is thread safe, so can be used with a net/http server. It uses `sync.RWMutex` for write and read operations
8. db tests are table driven, so the SAME test code run against Mock and real DB (test expects running posgresql)
9. There are smoke tests using HTTP, curl calls HTTP API and there's no check of the result
10. SQL queries are profiled (EXPLAIN ANALYZE VERBOSE), so some indices have been added.
11. Use gorilla/mux instead of default muxer
## Areas of improvement
I must say that I have reduced the scope a LOT in order to finish something :-)
1. While signing and authentication is secure, it can be further improved. There should be private key rotation - after X days or Y usages.
2. There is no support for token refresh - or you can't get it again (missing API for it)
3. I wanted to add more options, like Google Oauth2 tokens. Usually I try to preffer third party authentication in order to avoid storing hashes in the DB. But I did not want to setup the console for this project.
4. CORS for first endpoint is not solved
5. Some queries (AddVolunteer) can be written using `SELECT WITH` Postgres syntax
6. There is almost zero configurability
7. You can't easily change algorithm of user hash, this is NOT forward compatible implementation
8. On the other hand there is `algo` field for tokens
9. I wanted to write UI (therefor CORS have been almost solved)
10. Errors can be declared in one file
11. No metrics besides HTTP access log available
12. Short on log messages - sometimes an error is ignored, but should be exported
13. I took a SHORTCUT for user registration, usually there will be a confirmation link sent and probably Redis based store for not-yet confirmed users prior writing to Postgres. Redis can automatically expire the old entries (SETEX command).
14. I did not invest in non-Linux integration, thwere is no Docker compose or so and everything works the best on Linux with `tmux`, where one can run components from shell.
15. Integration tests are not properly automated, except test.sh calling curl.
16. No rate-limiting, no SSL, usually solved by ngninx proxy and not in Go code
<file_sep>package main
import (
"encoding/json"
"errors"
"log"
"net/http"
"strings"
)
var (
errBadGrantType = errors.New("grant_type must be 'password'")
errEmptyUser = errors.New("user must not be empty")
errNoAt = errors.New("user must be email address")
errEmptyPassword = errors.New("password must not be empty")
errNoAuthEmail = errors.New("There is no authenticated user email available")
)
type AuthRequest struct {
User string `json:"user"`
Password string `json:"<PASSWORD>"`
GrantType string `json:"grant_type"`
}
type AuthReply struct {
Token string `json:"access_token"`
Type string `json:"token_type"`
Expires int `json:"expires_in"`
}
func (s *Service) volunteersPOST(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log.Print("Service.volunteersPOST")
var v AuthRequest
err := json.NewDecoder(r.Body).Decode(&v)
if err != nil {
s.BadRequest(w, err)
return
}
if v.GrantType != "password" {
s.BadRequest(w, errBadGrantType)
return
}
if v.User == "" {
s.BadRequest(w, errEmptyUser)
return
}
if strings.Index(v.User, "@") == -1 {
s.BadRequest(w, errNoAt)
return
}
if v.Password == "" {
s.BadRequest(w, errEmptyPassword)
return
}
// store the volunteer
err = s.db.StoreVolunteer(ctx, v.User, v.Password)
if err != nil {
if err == errVolunteerAlreadyStored {
s.BadRequest(w, errVolunteerAlreadyStored)
return
}
s.InternalServerError(w, err)
return
}
// generate token
token, err := s.psvc.Encode(v.User)
if err != nil {
s.db.DeleteVolunteer(ctx, v.User)
s.InternalServerError(w, err)
return
}
reply := AuthReply{
Token: string(token),
Type: "Bearer",
Expires: 86400,
}
s.Json(w, reply)
}
func checkAuthEmail(r *http.Request) (string, error) {
ctx := r.Context()
email, ok := ctx.Value(authKey("email")).(string)
if !ok {
return email, errNoAuthEmail
}
return email, nil
}
func (s *Service) volunteersGET(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
log.Print("Service.volunteersGET")
email, err := checkAuthEmail(r)
if err != nil {
s.InternalServerError(w, errNoAuthEmail)
return
}
vinfo, err := s.db.GetVolunteerInfo(ctx, email)
if err != nil {
s.BadRequest(w, err)
return
}
s.Json(w, vinfo)
return
}
<file_sep>package main
import (
"context"
"encoding/json"
"errors"
"flag"
"log"
"net/http"
"os"
"os/signal"
"strings"
"time"
"github.com/gorilla/mux"
)
var (
errAuthorizationHeaderMissing = errors.New("Authorization header is missing")
errBadAuthorizationScheme = errors.New("Only authorization scheme Bearer is supported")
errCannotDecodeToken = errors.New("Provided token is invalid")
)
// Service wraps the volunteers/test service
type Service struct {
verbose bool
psvc TokenService
db DBer
}
// HTTP helper code
// Bad sends non-200 status code response and logs metadata
func (s *Service) bad(w http.ResponseWriter, err error, statusCode int) {
if statusCode == http.StatusOK {
panic("Service.bad: assertion non-200 status code")
}
var reply struct {
Err string `json:"error"`
}
reply.Err = err.Error()
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
json.NewEncoder(w).Encode(reply)
}
// BadRequest - return HTTP 400 Bad Request
func (s *Service) BadRequest(w http.ResponseWriter, err error) {
s.bad(w, err, http.StatusBadRequest)
}
// InternalServerError - return HTTP 500 Internal Server Error
func (s *Service) InternalServerError(w http.ResponseWriter, err error) {
s.bad(w, err, http.StatusInternalServerError)
}
// InternalServerError - return HTTP 500 Internal Server Error
func (s *Service) Forbidden(w http.ResponseWriter, err error) {
s.bad(w, err, http.StatusForbidden)
}
func (s *Service) Json(w http.ResponseWriter, reply interface{}) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
json.NewEncoder(w).Encode(reply)
}
func (s *Service) OK(w http.ResponseWriter) {
w.WriteHeader(http.StatusNoContent)
}
type authKey string
// authMiddleware does
// 1. setup CORS to accept everything
// 3. token in HTTP header Authorization: Bearer <token>
// 4. pass to next handler if valid
func (s *Service) authMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
//TODO: solve CORS here
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Headers", "Authorization, Content-Type")
w.Header().Set("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
var email string
auth := r.Header.Get("Authorization")
if len(auth) == 0 {
s.Forbidden(w, errAuthorizationHeaderMissing)
return
}
foo := strings.Split(auth, " ")
if len(foo) != 2 && foo[0] != "Bearer" {
s.Forbidden(w, errBadAuthorizationScheme)
return
}
email, valid := s.psvc.Decode([]byte(foo[1]))
if !valid {
s.Forbidden(w, errCannotDecodeToken)
return
}
ctx := r.Context()
r = r.WithContext(
context.WithValue(ctx, authKey("email"), email))
next.ServeHTTP(w, r)
})
}
func main() {
var conn string
flag.StringVar(&conn, "c", "", "postgres compatible connection string or empty (mock DB will be used)")
flag.Parse()
db, err := NewDBer(conn)
if err != nil {
log.Fatal(err)
}
s := &Service{
verbose: true,
//TODO configure the key, key rotation, ...
psvc: NewTokenService(PasswdPrivateKeyBytes),
db: db,
}
r := mux.NewRouter()
// register new volunteer
volunteerV1 := r.PathPrefix("/api/v1").Subrouter()
volunteerV1.HandleFunc("/volunteers", s.volunteersPOST).Methods("POST", "OPTIONS")
// info about volunteer
authAPIV1 := r.PathPrefix("/api/v1").Subrouter()
authAPIV1.HandleFunc("/volunteers", s.volunteersGET).Methods("GET", "OPTIONS")
// teams API
authAPIV1.HandleFunc("/teams", s.teamsPOST).Methods("POST", "OPTIONS")
authAPIV1.HandleFunc("/teams", s.teamsGET).Methods("GET", "OPTIONS")
authAPIV1.HandleFunc("/teams/{team}", s.teamsPUT).Methods("PUT", "OPTIONS")
authAPIV1.Use(s.authMiddleware)
srv := &http.Server{
Addr: ":8765",
// Good practice to set timeouts to avoid Slowloris attacks.
WriteTimeout: time.Second * 15,
ReadTimeout: time.Second * 15,
IdleTimeout: time.Second * 60,
Handler: r, // Pass our instance of gorilla/mux in.
}
// Run our server in a goroutine so that it doesn't block.
go func() {
log.Printf("Listening on :%s", ":8765")
if err := srv.ListenAndServe(); err != nil {
log.Print(err.Error())
}
}()
c := make(chan os.Signal, 1)
// We'll accept graceful shutdowns when quit via SIGINT (Ctrl+C)
// SIGKILL, SIGQUIT or SIGTERM (Ctrl+/) will not be caught.
signal.Notify(c, os.Interrupt)
// Block until we receive our signal.
<-c
wait := 15 * time.Second
// Create a deadline to wait for.
ctx, cancel := context.WithTimeout(context.Background(), wait)
defer cancel()
// Doesn't block if no connections, but will otherwise wait
// until the timeout deadline.
srv.Shutdown(ctx)
// Optionally, you could run srv.Shutdown in a goroutine and block on
// <-ctx.Done() if your application should wait for other services
// to finalize based on context cancellation.
log.Print("shutting down")
return
}
<file_sep>module gwi
go 1.12
require (
github.com/gorilla/mux v1.7.3
github.com/lib/pq v1.1.1
github.com/stretchr/testify v1.3.0
golang.org/x/crypto v0.0.0-20190621222207-cc06ce4a13d4
)
<file_sep>package main
// main - code dealing with scrypt
// and user code hashing
import (
"crypto/rand"
"crypto/subtle"
"errors"
"golang.org/x/crypto/scrypt"
)
var (
errVolunteerAlreadyStored = errors.New("Volunteer already stored")
errVolunteerCheckFailed = errors.New("Unknown comabination of user+password")
)
type Passwd struct {
Hash []byte `json:"hash"`
Salt []byte `json:"salt"`
}
func HashPassword(password string) (Passwd, error) {
//1. generate salt
salt := make([]byte, ScryptSaltSize)
_, err := rand.Read(salt)
if err != nil {
return Passwd{}, err
}
//2. scrypto password
dk, err := scrypt.Key([]byte(password), salt, ScryptN, ScryptR, ScryptP, ScryptKeySize)
if err != nil {
return Passwd{}, err
}
//3. store
return Passwd{Hash: dk, Salt: salt}, nil
}
func (p *Passwd) Check(password string) error {
//2. scrypto password
dk, err := scrypt.Key([]byte(password), p.Salt, ScryptN, ScryptR, ScryptP, ScryptKeySize)
if err != nil {
return errVolunteerCheckFailed
}
if subtle.ConstantTimeCompare(p.Hash, dk) != 1 {
return errVolunteerCheckFailed
}
return nil
}
<file_sep>#!/bin/bash
GIT_ROOT=$(git rev-parse --show-toplevel)
SQL_DIR=${GIT_ROOT}/testdata/sql
die() {
echo "ERROR: ${@}" >&2
exit 1
}
rm -rf $SQL_DIR
mkdir $SQL_DIR
cp ${GIT_ROOT}/*.sql $SQL_DIR/
docker run --rm --name postgres -p 5432:5432 -v ${SQL_DIR}/:/docker-entrypoint-initdb.d/ postgres:10.6
<file_sep>package main
import (
"github.com/stretchr/testify/assert"
"testing"
)
func TestScrypt(t *testing.T) {
assert := assert.New(t)
p, err := HashPassword("AlexanderTheGreat")
assert.NoError(err)
err = p.Check("")
assert.Error(err)
err = p.Check("AlexanderTheGreat!")
assert.Error(err)
err = p.Check("AlexanderTheGreat")
assert.NoError(err)
}
<file_sep>package main
import (
"context"
"database/sql"
"errors"
pq "github.com/lib/pq"
)
var (
errNotImplemented = errors.New("Feature not yet implemented")
)
const (
PqUniqueViolation = "23505"
)
type PostgresDB struct {
db *sql.DB
}
func NewPostgresDB(conn string) (*PostgresDB, error) {
db, err := sql.Open("postgres", conn)
pdb := &PostgresDB{}
if err != nil {
return pdb, err
}
err = db.Ping()
if err != nil {
if db != nil {
db.Close()
}
return pdb, err
}
pdb.db = db
return pdb, err
}
func (d *PostgresDB) StoreVolunteer(ctx context.Context, email string, password string) error {
p, err := HashPassword(password)
if err != nil {
return err
}
_, err = d.db.ExecContext(
ctx,
"INSERT INTO gwi.volunteer (email, hash, salt) VALUES($1, $2, $3)",
email,
p.Hash,
p.Salt,
)
if err != nil {
//TODO: unify errors between layers
return err
}
return nil
}
func (d *PostgresDB) CheckVolunteer(ctx context.Context, email string, password string) error {
var hash []byte
var salt []byte
err := d.db.QueryRowContext(ctx, "SELECT hash, salt FROM gwi.volunteer WHERE email=$1", email).Scan(&hash, &salt)
if err != nil {
return errVolunteerCheckFailed
}
p := Passwd{Hash: hash, Salt: salt}
err = p.Check(password)
if err != nil {
return errVolunteerCheckFailed
}
return nil
}
func (d *PostgresDB) DeleteVolunteer(ctx context.Context, email string) error {
d.db.QueryRowContext(ctx, "DELETE FROM gwi.volunteer WHERE email=$1 CASCADE ON ERROR IGNORE", email)
return nil
}
func (d *PostgresDB) CreateTeam(ctx context.Context, name string) error {
_, err := d.db.ExecContext(
ctx,
"INSERT INTO gwi.team (name) VALUES($1)",
name,
)
if err != nil {
pqerr, ok := err.(*pq.Error)
// handle duplicated key value constraint
if ok && pqerr.Code == PqUniqueViolation {
return errTeamAlreadyStored
}
return err
}
return nil
}
func (d *PostgresDB) ListTeams(ctx context.Context) []string {
rows, err := d.db.QueryContext(ctx, "SELECT name FROM gwi.team ORDER BY name ASC")
if err != nil {
//TODO: unify errors between layers
return []string{}
}
r := make([]string, 0)
for rows.Next() {
var name string
err := rows.Scan(&name)
if err != nil {
//TODO: unify errors between layers
return []string{}
}
r = append(r, name)
}
return r
}
func (d *PostgresDB) AddVolunteer(ctx context.Context, team string, email string) error {
tx, err := d.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelSerializable})
if err != nil {
return err
}
// TODO: use SELECT WITH syntax or stored procedure
var teamID, volunteerID int64
err = tx.QueryRowContext(ctx, "SELECT id FROM gwi.team WHERE name=$1", team).Scan(&teamID)
if err != nil {
tx.Rollback()
if err == sql.ErrNoRows {
return errTeamNotFound
}
return err
}
err = tx.QueryRowContext(ctx, "SELECT id FROM gwi.volunteer WHERE email=$1", email).Scan(&volunteerID)
if err != nil {
tx.Rollback()
if err == sql.ErrNoRows {
return errVolunteerNotFound
}
return err
}
_, err = tx.ExecContext(ctx, "INSERT INTO gwi.signup (volunteer_id, team_id) VALUES ($1, $2)", volunteerID, teamID)
if err != nil {
tx.Rollback()
pqerr, ok := err.(*pq.Error)
// handle duplicated key value constraint
if ok && pqerr.Code == PqUniqueViolation {
return errVolunteerAlreadyStored
}
return err
}
tx.Commit()
return nil
}
func (d *PostgresDB) GetVolunteerInfo(ctx context.Context, email string) (VolunteerInfo, error) {
tx, err := d.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelDefault, ReadOnly: true})
if err != nil {
return VolunteerInfo{}, err
}
var volunteerID int64
err = d.db.QueryRowContext(ctx, "SELECT id FROM gwi.volunteer WHERE email=$1", email).Scan(&volunteerID)
if err != nil {
tx.Rollback()
if err == sql.ErrNoRows {
return VolunteerInfo{}, errVolunteerNotFound
}
return VolunteerInfo{}, err
}
teams := make([]string, 0)
rows, err := d.db.QueryContext(ctx, "SELECT name FROM gwi.signup AS s LEFT JOIN gwi.team AS t ON t.id=s.team_id WHERE s.volunteer_id=$1", volunteerID)
if err != nil {
tx.Rollback()
return VolunteerInfo{}, err
}
for rows.Next() {
var name string
err = rows.Scan(&name)
if err != nil {
tx.Rollback()
return VolunteerInfo{}, err
}
teams = append(teams, name)
}
tx.Commit()
return VolunteerInfo{User: email, Teams: teams}, nil
}
func (d *PostgresDB) Close() {
d.db.Close()
}
<file_sep>package main
// TODO: move to configuration!!!
const (
// dd status=none if=/dev/urandom of=/dev/stdout count=8 | base64 --wrap 0 | xclip
passwdPrivateKey = "<KEY>9FBlMUMTo="
)
// scrypt constants
// https://godoc.org/golang.org/x/crypto/scrypt
const (
ScryptN = 32768
ScryptR = 8
ScryptP = 1
ScryptSaltSize = 32
ScryptKeySize = 32
)
var (
PasswdPrivateKeyBytes []byte
)
<file_sep>package main
// passwd.go
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/json"
"errors"
"time"
)
// code dealing with password based authentization
//
// app uses oauth2 (like) schema
//
// Token format base64(payload).base64(hmac+2ha256)
// dot(.) is a separator as it is unregistered URL parameter accroding RFC 3986 (2005)
//
// payload is
// algo - used algoritm for hmac
// email - user email
// valid-until - date until this is valid
// so link automatically expires after while
//
var (
errUnknownAlgo = errors.New("Unknown algo, supported is: sha256")
)
// TokenService stores the private key inside and offers methods to Encode/Decode
// the PasswordToken
type TokenService struct {
// TODO: in reality we will generate new random key at leat once a day, or during X thousands of requests
// to prevent leak of the private key
privateKey []byte
}
// NewTokenService returns service with a private key inside
func NewTokenService(privateKey []byte) TokenService {
return TokenService{
privateKey: privateKey,
}
}
type AuthPayload struct {
Algo string `json:"algo"`
Email string `json:"email"`
ValidUntil time.Time `json:"valid-until"`
}
func NewAuthPayload(email string) AuthPayload {
return AuthPayload{
Algo: "sha256",
Email: email,
ValidUntil: time.Now().Add(24 * time.Hour),
}
}
// Hmac returns
// marshaled AuthPayload
// hmac+sha256 of it
// error if happened
func (p *TokenService) hmac(payload AuthPayload) ([]byte, []byte, error) {
b, err := json.Marshal(payload)
if err != nil {
return []byte{}, []byte{}, err
}
h := hmac.New(sha256.New, p.privateKey)
h.Write(b)
mac := h.Sum(nil)
return b, mac, nil
}
// Encode PasswordToken to base64(PasswordToken).base64(HMAC)
func (p *TokenService) Encode(email string) ([]byte, error) {
payload := NewAuthPayload(email)
b, hmac, err := p.hmac(payload)
if err != nil {
return []byte{}, err
}
// base64 payload
var b1 []byte
{
bb := bytes.NewBuffer([]byte{})
encoder := base64.NewEncoder(base64.RawURLEncoding, bb)
encoder.Write(b)
encoder.Close()
b1 = bb.Bytes()
}
// base64 hmac
var b2 []byte
{
bb := bytes.NewBuffer([]byte{})
encoder := base64.NewEncoder(base64.RawURLEncoding, bb)
encoder.Write(hmac)
encoder.Close()
b2 = bb.Bytes()
}
ret := bytes.Join([][]byte{b1, b2}, []byte("."))
return ret, nil
}
// Decode user email from provided payload.hmac buffer
// return valid if
// 1. there is . inside buffer
// 2. one can base64 decode first part (payload)
// 2. one can base64 decode second part (signature)
// 2. one hmac+256 of payload matches given signature
func (p *TokenService) Decode(b []byte) (email string, valid bool) {
valid = false
foo := bytes.Split(b, []byte("."))
if len(foo) != 2 {
return
}
// payload
var b1 []byte
{
dbuf := make([]byte, base64.RawURLEncoding.DecodedLen(len(foo[0])))
_, err := base64.RawURLEncoding.Decode(dbuf, foo[0])
if err != nil {
return
}
b1 = dbuf
}
var payload AuthPayload
err := json.Unmarshal(b1, &payload)
if err != nil {
return
}
if payload.Algo != "sha256" {
err = errUnknownAlgo
return
}
// hmac
var b2 []byte
{
dbuf := make([]byte, base64.RawURLEncoding.DecodedLen(len(foo[1])))
_, err := base64.RawURLEncoding.Decode(dbuf, foo[1])
if err != nil {
return
}
b2 = dbuf
}
_, mac, err := p.hmac(payload)
if hmac.Equal(b2, mac) {
if time.Now().Before(payload.ValidUntil) {
email = payload.Email
valid = true
}
}
return
}
<file_sep>package main
import (
"context"
"errors"
"sort"
"sync"
)
var (
errVolunteerNotFound = errors.New("Volunteer not found")
errTeamAlreadyStored = errors.New("Team already stored")
errTeamNotFound = errors.New("Team not found")
)
type VolunteerInfo struct {
User string `json:"user"`
Teams []string `json:"teams,omitempty"`
}
type DBer interface {
StoreVolunteer(ctx context.Context, email string, password string) error
CheckVolunteer(ctx context.Context, email string, password string) error
DeleteVolunteer(ctx context.Context, email string) error
CreateTeam(ctx context.Context, name string) error
ListTeams(ctx context.Context) []string
AddVolunteer(ctx context.Context, team string, email string) error
GetVolunteerInfo(ctx context.Context, email string) (VolunteerInfo, error)
Close()
}
func NewDBer(conn string) (DBer, error) {
if conn == "" {
return NewMockDB(), nil
}
return NewPostgresDB(conn)
}
// Users is a set of users
// NOT thread safe, helper for MockDB, so hidden by RWMutex
type Users struct {
Users map[string]bool
}
func NewUsers() *Users {
return &Users{Users: make(map[string]bool)}
}
func (u *Users) Add(user string) error {
if !u.Has(user) {
u.Users[user] = true
return nil
} else {
return errVolunteerAlreadyStored
}
}
func (u *Users) Has(user string) bool {
_, ok := u.Users[user]
return ok
}
func (u *Users) Del(user string) error {
if u.Has(user) {
delete(u.Users, user)
return nil
} else {
return errVolunteerNotFound
}
}
func (u *Users) List() []string {
r := make([]string, len(u.Users))
i := 0
for u := range u.Users {
r[i] = u
i++
}
sort.Strings(r)
return r
}
type MockDB struct {
Passwd map[string]Passwd `json:"passwd"`
Team map[string]Users
m *sync.RWMutex
}
func NewMockDB() DBer {
return &MockDB{
Passwd: make(map[string]Passwd),
Team: make(map[string]Users),
m: &sync.RWMutex{},
}
}
func (d *MockDB) StoreVolunteer(_ context.Context, email string, password string) error {
d.m.Lock()
_, ok := d.Passwd[email]
if ok {
d.m.Unlock()
return errVolunteerAlreadyStored
}
p, err := HashPassword(password)
if err != nil {
d.m.Unlock()
return err
}
d.Passwd[email] = p
d.m.Unlock()
return nil
}
func (d *MockDB) CheckVolunteer(_ context.Context, email string, password string) error {
d.m.RLock()
p, ok := d.Passwd[email]
if !ok {
d.m.RUnlock()
return errVolunteerCheckFailed
}
err := p.Check(password)
if err != nil {
d.m.RUnlock()
return err
}
d.m.RUnlock()
return nil
}
func (d *MockDB) DeleteVolunteer(_ context.Context, email string) error {
d.m.Lock()
delete(d.Passwd, email)
d.m.Unlock()
return nil // we ignore non existing user errors
}
func (d *MockDB) CreateTeam(_ context.Context, name string) error {
d.m.Lock()
var err error
err = nil
if _, ok := d.Team[name]; !ok {
d.Team[name] = *NewUsers()
} else {
err = errTeamAlreadyStored
}
d.m.Unlock()
return err
}
func (d *MockDB) ListTeams(_ context.Context) []string {
d.m.RLock()
r := make([]string, len(d.Team))
i := 0
for t := range d.Team {
r[i] = t
i++
}
d.m.RUnlock()
sort.Strings(r)
return r
}
func (d *MockDB) AddVolunteer(_ context.Context, team string, email string) error {
d.m.Lock()
if _, ok := d.Team[team]; !ok {
d.m.Unlock()
return errTeamNotFound
}
if _, ok := d.Passwd[email]; !ok {
d.m.Unlock()
return errVolunteerNotFound
}
t := d.Team[team]
err := t.Add(email)
d.m.Unlock()
return err
}
func (d *MockDB) GetVolunteerInfo(_ context.Context, email string) (VolunteerInfo, error) {
v := VolunteerInfo{}
d.m.RLock()
if _, ok := d.Passwd[email]; !ok {
d.m.RUnlock()
return v, errVolunteerNotFound
}
v.User = email
v.Teams = make([]string, 0)
//XXX: O(n) complexity, but fine for mock
for t, u := range d.Team {
if u.Has(email) {
v.Teams = append(v.Teams, t)
}
}
sort.Strings(v.Teams)
d.m.RUnlock()
return v, nil
}
func (d *MockDB) Close() {
}
<file_sep>package main
import (
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestTokenService(t *testing.T) {
assert := assert.New(t)
require := require.New(t)
psvc := NewTokenService(PasswdPrivateKeyBytes)
// can generate the link
token1, err := psvc.Encode("<EMAIL>")
require.NoError(err)
assert.True(len(token1) > 0)
// we can decode valid token and read email
email, valid := psvc.Decode(token1)
require.True(valid)
assert.Equal("<EMAIL>", email)
// can't decode changed token
token1[0] = byte('z')
_, valid = psvc.Decode(token1)
require.False(valid)
// can't decode token encoded with different private key
psvc2 := NewTokenService([]byte("42"))
_, valid = psvc2.Decode(token1)
require.False(valid)
}
<file_sep>#!/bin/bash
die() {
printf "${@}" >&2
exit 1
}
#go test || die
#go test -race || die
# smoke test
HOST="http://localhost:8765"
set -x
ACCESS_TOKEN=$(curl ${HOST}/api/v1/volunteers --data '{"user": "<EMAIL>", "grant_type": "password", "password": "<PASSWORD>!"}' | jq -r .access_token)
set +x
[[ -n "${ACCESS_TOKEN}" ]] || die "Empty ACCESS_TOKEN"
[[ "${ACCESS_TOKEN}" != "null" ]] || die "Empty ACCESS_TOKEN"
curl_auth() {
local url
url=${HOST}${1}
shift 1
set -x
curl -v -H "Authorization: Bearer ${ACCESS_TOKEN}" "${@}" "${url}"
set +x
}
curl_nauth() {
local url
url="${HOST}${1}"
shift 1
set -x
curl -v "${@}" "${url}"
set +x
}
curl_auth /api/v1/volunteers --data '{"user": "<EMAIL>", "grant_type": "password", "password": "<PASSWORD>!"}'
#{"error":"Volunteer already stored"}
curl_auth /api/v1/volunteers -X GET | jq
curl_nauth /api/v1/volunteers -X GET | jq
# create team
curl_auth /api/v1/teams -X POST --data '{"name": "TEAMA"}'
curl_auth /api/v1/teams -X POST --data '{"name": "TEAMB"}'
# create team twice
curl_auth /api/v1/teams -X POST --data '{"name": "TEAMB"}'
## list the teams
curl_auth /api/v1/teams -X GET | jq
curl_auth /api/v1/teams/TEAMA -X PUT | jq
curl_auth /api/v1/volunteers | jq
curl_auth /api/v1/teams/TEAMC -X PUT | jq
curl_auth /api/v1/teams/TEAMB -X PUT | jq
curl_auth /api/v1/volunteers | jq
|
5d4fa423f8dd9a44de0c9e667f6116a455780915
|
[
"SQL",
"Markdown",
"Go",
"Go Module",
"Shell"
] | 16 |
Go
|
vyskocilm/for-gwi
|
388ed6ca5c9536eb99e0d07acac3836dd1f1e1ff
|
ff105d4a2e1919e01351c66974f50330ca7f81d9
|
refs/heads/main
|
<file_sep>const siteContent = {
nav: {
'nav-item-1': 'Services',
'nav-item-2': 'Product',
'nav-item-3': 'Vision',
'nav-item-4': 'Features',
'nav-item-5': 'About',
'nav-item-6': 'Contact',
'img-src': 'img/logo.png',
},
cta: {
h1: 'DOM Is Awesome',
button: 'Get Started',
'img-src': 'img/header-img.png',
},
'main-content': {
'features-h4': 'Features',
'features-content':
'Features content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
'about-h4': 'About',
'about-content':
'About content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
'middle-img-src': 'img/mid-page.jpg',
'services-h4': 'Services',
'services-content':
'Services content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
'product-h4': 'Product',
'product-content':
'Product content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
'vision-h4': 'Vision',
'vision-content':
'Vision content elementum magna eros, ac posuere elvit tempus et. Suspendisse vel tempus odio, in interdutm nisi. Suspendisse eu ornare nisl. Nullam convallis augue justo, at imperdiet metus scelerisque quis.',
},
contact: {
'contact-h4': 'Contact',
address: '123 Way 456 Street Somewhere, USA',
phone: '1 (888) 888-8888',
email: '<EMAIL>',
},
footer: {
copyright: 'Copyright Great Idea! 2020',
},
};
const a1=document.querySelector("header > nav ");
a1.getElementsByTagName("a")[0].textContent=siteContent.nav["nav-item-1"];
a1.getElementsByTagName("a")[0].style.color="#33cc99";
console.log(a1);
const a2=document.querySelector("header > nav ");
a2.getElementsByTagName("a")[1].textContent=siteContent.nav["nav-item-2"];
a1.getElementsByTagName("a")[1].style.color="#33cc99";
console.log(a2);
const a3=document.querySelector("header > nav ");
a3.getElementsByTagName("a")[2].textContent=siteContent.nav["nav-item-3"];
a1.getElementsByTagName("a")[2].style.color="#33cc99";
console.log(a3);
const a4=document.querySelector("header > nav ");
a4.getElementsByTagName("a")[3].textContent=siteContent.nav["nav-item-4"];
a1.getElementsByTagName("a")[3].style.color="#33cc99";
console.log(a4);
const a5=document.querySelector("header > nav ");
a5.getElementsByTagName("a")[4].textContent=siteContent.nav["nav-item-5"];
a1.getElementsByTagName("a")[4].style.color="#33cc99";
console.log(a5);
const a6=document.querySelector("header > nav ");
a6.getElementsByTagName("a")[5].textContent=siteContent.nav["nav-item-6"];
a1.getElementsByTagName("a")[5].style.color="#33cc99";
console.log(a6);
const nav =document.querySelector("nav");
const a7=document.createElement('a');
a7.textContent="Other";
a7.style.color="#33cc99";
nav.appendChild(a7);
const a8=document.createElement('a');
a8.textContent="Last";
a8.style.color="#33cc99";
nav.appendChild(a8);
document.getElementById("logo-img").src=siteContent.nav["img-src"];
document.querySelector("div > h1").textContent=siteContent.cta.h1;
document.querySelector("div > button").textContent=siteContent.cta.button;
document.getElementById("cta-img").src=siteContent.cta["img-src"];
const list = document.getElementsByClassName("text-content")[0];
list.querySelector("h4").textContent=siteContent["main-content"]["features-h4"];
const list1 = document.getElementsByClassName("text-content")[0];
list1.querySelector("p").textContent=siteContent["main-content"]["features-content"];
const list3 = document.getElementsByClassName("text-content")[1];
list3.querySelector("h4").textContent=siteContent["main-content"]["about-h4"];
const list4 = document.getElementsByClassName("text-content")[1];
list4.querySelector("p").textContent=siteContent["main-content"]["about-content"];
document.getElementById("middle-img").src=siteContent["main-content"]["middle-img-src"];
const list5 = document.getElementsByClassName("text-content")[2];
list5.querySelector("h4").textContent=siteContent["main-content"]["services-h4"];
const list6 = document.getElementsByClassName("text-content")[2];
list6.querySelector("p").textContent=siteContent["main-content"]["services-content"];
const list7 = document.getElementsByClassName("text-content")[3];
list7.querySelector("h4").textContent=siteContent["main-content"]["product-h4"]
const list8 = document.getElementsByClassName("text-content")[3];
list8.querySelector("p").textContent=siteContent["main-content"]["product-content"]
const list9 = document.getElementsByClassName("text-content")[4];
list9.querySelector("h4").textContent=siteContent["main-content"]["vision-h4"];
const list10 = document.getElementsByClassName("text-content")[4];
list10.querySelector("p").textContent=siteContent["main-content"]["vision-content"];
const list11 = document.getElementsByClassName("contact")[0].querySelector("h4").textContent=siteContent.contact["contact-h4"];
const list12 = document.getElementsByClassName("contact")[0].querySelectorAll("p")
list12[0].textContent=siteContent.contact.address;
const list13 = document.getElementsByClassName("contact")[0].querySelectorAll("p")
list13[1].textContent=siteContent.contact.phone;
const list14 = document.getElementsByClassName("contact")[0].querySelectorAll("p")
list14[2].textContent=siteContent.contact.email;
const footer=document.querySelector("footer > p ");
footer.textContent=siteContent.footer.copyright;
// const list12 = document.getElementsByClassName("contact")[0];
// list12.querySelector("p")[0]; = "red";
//console.log(q);
//q.textContent=siteContent.contact.address;
// const list13 = document.getElementsByClassName("contact")[0];
// let w =list13.querySelector("p")[1];
// w.textContent=siteContent.contact.phone;
// const list14 = document.getElementsByClassName("contact")[0];
// let r =list14.querySelector("p")[2];
// r.textContent=siteContent.contact.email;
|
9c83ca8cfeab511ae326973fdda5d952502685d0
|
[
"JavaScript"
] | 1 |
JavaScript
|
IsraaAhmad/domHW
|
d56ce4e6b18bd667897446819b0495de978663d7
|
770ae9d753985bd15f9d6aab725e196901342d34
|
refs/heads/master
|
<repo_name>RafaelFBezerra/Quebra-Cabeca-de-Oito-Pecas<file_sep>/TRAB01_IA.py
import numpy
import copy
import pandas as pd
matriz = []
for i in range(3):
linha = []
for j in range (3):
linha.append(input())
matriz.append(linha)
global matriz_usuario
matriz_usuario = matriz
matriz_orig = copy.deepcopy(matriz_usuario)
def imprime_matriz():
for linha in matriz_usuario:
print(linha)
print('\n')
print('\n', 'MATRIZ DIGITADA: ')
imprime_matriz()
def func_manhattan():
#func = matriz_usuario()
matriz_user = matriz_usuario
i=0
j=0
a=0
b=0
matriz_base = [[1,2,3],[4,5,6],[7,8,0]]
vet_custos = []
for i in range(3):
for j in range (3):
if int(matriz_user[i][j]) == int(matriz_base[i][j]):
custo = 0
vet_custos.append(custo)
if int(matriz_user[i][j]) != int(matriz_base[i][j]):
aux = matriz_user[i][j]
for a in range (3):
for b in range (3):
if int(aux) == int(matriz_base[a][b]) and int(aux) != 0 : #O nรบmero zero nรฃo entra no calculo
custo_lin = abs(i - a)
custo_col = abs(j - b)
custo_total = int(custo_lin) + int(custo_col)
vet_custos.append(custo_total)
global manhathan
manhathan = sum(vet_custos)
#print('\n',vet_custos)
#print('\n','CUSTO DA MATRIZ: ',manhathan)
return vet_custos,matriz_user, matriz_base
def atualiza_matriz():
func_manhattan()
global custo_manhathaninicio
custo_manhathaninicio = manhathan
ok = False
for i in range (3):
for j in range (3):
if int(matriz_usuario[i][j]) == 0:
soma_i = i - 1
if soma_i < 0:
#posiรงรฃo acima do elemento zero nรฃo existe
vizinho_c = -1
else:
vizinho_c = matriz_usuario[i-1][j]
soma_i = 0
soma_i = i+1
if soma_i > 2:
#posiรงรฃo abaixo do elemento zero nรฃo existe
vizinho_b = -1
else:
vizinho_b = matriz_usuario[i+1][j]
soma_j = j-1
if soma_j < 0:
#posiรงรฃo ร esquerda do elemento zero nรฃo existe
vizinho_e = -1
else:
vizinho_e = matriz_usuario[i][j-1]
soma_j=0
soma_j = j+1
if soma_j > 2:
#posiรงรฃo ร esquerda do elemento zero nรฃo existe
vizinho_d = -1
else:
vizinho_d = matriz_usuario[i][j+1]
ok = True
pos_i = i
pos_j = j
break
if ok:
break
return vizinho_c,vizinho_b,vizinho_e,vizinho_d,pos_i,pos_j
def troca_acima():
func = atualiza_matriz()
vizinho_c = func[0]
i = func[4]
j = func[5]
if(int(vizinho_c) != -1):
matriz_usuario[i-1][j] = matriz_usuario[i][j]
matriz_usuario[i][j] = vizinho_c
valid = True
else:
valid = False
func_manhattan()
return valid
def recursiva_acima():
func = atualiza_matriz()
vizinho_b = func[1]
i = func[4]
j = func[5]
matriz_usuario[i+1][j] = matriz_usuario[i][j]
matriz_usuario[i][j] = vizinho_b
func_manhattan()
def troca_abaixo():
func = atualiza_matriz()
vizinho_b = func[1]
i = func[4]
j = func[5]
if(int(vizinho_b) != -1):
matriz_usuario[i+1][j] = matriz_usuario[i][j]
matriz_usuario[i][j] = vizinho_b
valid = True
else:
valid = False
func_manhattan()
return valid
def recursiva_abaixo():
func = atualiza_matriz()
vizinho_c = func[0]
i = func[4]
j = func[5]
matriz_usuario[i-1][j] = matriz_usuario[i][j]
matriz_usuario[i][j] = vizinho_c
func_manhattan()
def troca_esquerda():
func = atualiza_matriz()
vizinho_e = func[2]
i = func[4]
j = func[5]
if (int(vizinho_e) != -1):
matriz_usuario[i][j-1] = matriz_usuario[i][j]
matriz_usuario[i][j] = vizinho_e
valid = True
else:
valid = False
func_manhattan()
return valid
def recursiva_esquerda():
func = atualiza_matriz()
vizinho_d = func[3]
i = func[4]
j = func[5]
matriz_usuario[i][j+1] = matriz_usuario[i][j]
matriz_usuario[i][j] = vizinho_d
func_manhattan()
def troca_direita():
func = atualiza_matriz()
vizinho_d = func[3]
i = func[4]
j = func[5]
if(int(vizinho_d)!= -1):
matriz_usuario[i][j+1] = matriz_usuario[i][j]
matriz_usuario[i][j] = vizinho_d
valid = True
else:
valid = False
func_manhattan()
return valid
def recursiva_direita():
func = atualiza_matriz()
vizinho_e = func[2]
i = func[4]
j = func[5]
matriz_usuario[i][j-1] = matriz_usuario[i][j]
matriz_usuario[i][j] = vizinho_e
func_manhattan()
def avaliaรงรฃo_manhatthan():
func_c = troca_acima()
valid_c = func_c
if valid_c == True:
#imprime_matriz()
troca_c = manhathan
recursiva_acima()
#imprime_matriz()
else:
troca_c = 50
func_b = troca_abaixo()
valid_b = func_b
if valid_b == True:
#imprime_matriz()
troca_b = manhathan
recursiva_abaixo()
#imprime_matriz()
else:
troca_b = 50
func_e = troca_esquerda()
valid_e = func_e
if valid_e == True:
#imprime_matriz()
troca_e = manhathan
recursiva_esquerda()
#imprime_matriz()
else:
troca_e = 50
func_d = troca_direita()
valid_d = func_d
if valid_d == True:
#imprime_matriz()
troca_d = manhathan
recursiva_direita()
#imprime_matriz()
else:
troca_d = 50
return troca_c, troca_b, troca_e, troca_d
def a_estrela():
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
global a
#itens para criaรงรฃo do df
vizinhos = [['Troca_c',int(troca_c)],['Troca_b',int(troca_b)],['Troca_e',int(troca_e)],['Troca_d', int(troca_d)]]
#criaรงรฃo df
vet_custosvizinhos = pd.DataFrame(vizinhos,columns=['Vizinhos','Custo_Troca'])
#print('\n',vet_custosvizinhos,'\n')
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = 0
check_a = False
check_b = False
check_c = False
check_d = False
while manhathan != 0:
if(vet_custosvizinhos['Vizinhos'].iloc[0]) == 'Troca_c' and check_b != True:
troca_acima()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = True
check_b = False
check_c = False
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[0]) == 'Troca_b' and check_a != True:
troca_abaixo()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = True
check_c = False
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[0]) == 'Troca_e' and check_d != True:
troca_esquerda()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = False
check_c = True
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[0]) == 'Troca_d' and check_c != True:
troca_direita()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = False
check_c = False
check_d = True
continue
if(vet_custosvizinhos['Vizinhos'].iloc[1]) == 'Troca_c' and check_b != True:
troca_acima()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = True
check_b = False
check_c = False
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[1]) == 'Troca_b' and check_a != True:
troca_abaixo()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = True
check_c = False
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[1]) == 'Troca_e' and check_d != True:
troca_esquerda()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = False
check_c = True
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[1]) == 'Troca_d' and check_c != True:
troca_direita()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = False
check_c = False
check_d = True
continue
if(vet_custosvizinhos['Vizinhos'].iloc[2]) == 'Troca_c' and check_b != True:
troca_acima()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = True
check_b = False
check_c = False
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[2]) == 'Troca_b' and check_a != True:
troca_abaixo()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = True
check_c = False
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[2]) == 'Troca_e' and check_d != True:
troca_esquerda()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = False
check_c = True
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[2]) == 'Troca_d' and check_c != True:
troca_direita()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = False
check_c = False
check_d = True
continue
if(vet_custosvizinhos['Vizinhos'].iloc[3]) == 'Troca_c' and check_b != True:
troca_acima()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = True
check_b = False
check_c = False
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[3]) == 'Troca_b' and check_a != True:
troca_abaixo()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = True
check_c = False
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[3]) == 'Troca_e' and check_d != True:
troca_esquerda()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = False
check_c = True
check_d = False
continue
if(vet_custosvizinhos['Vizinhos'].iloc[3]) == 'Troca_d' and check_c != True:
troca_direita()
imprime_matriz()
func = avaliaรงรฃo_manhatthan()
troca_c = func[0]
troca_b = func[1]
troca_e = func[2]
troca_d = func[3]
vet_custosvizinhos = vet_custosvizinhos.sort_index()
vet_custosvizinhos.iloc[0,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_c)
vet_custosvizinhos.iloc[1,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_b)
vet_custosvizinhos.iloc[2,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_e)
vet_custosvizinhos.iloc[3,vet_custosvizinhos.columns.get_loc('Custo_Troca')] = int(troca_d)
#ordenaรงรฃo por elemento
vet_custosvizinhos = vet_custosvizinhos.sort_values(['Custo_Troca'])
print('\n',vet_custosvizinhos,'\n')
a = a + 1
check_a = False
check_b = False
check_c = False
check_d = True
continue
a_estrela()
print('O PROBLEMA FOI SOLUCIONADO COM', a, 'MOVIMENTOS')
#ARMAZENAR CAMINHOS POSSรVEIS NA FILA DE PRIORIDADES
|
0e9fef573cb0010f9428df156f2ae100148ec063
|
[
"Python"
] | 1 |
Python
|
RafaelFBezerra/Quebra-Cabeca-de-Oito-Pecas
|
e467fdb04ac037f639b8f17f6a2af8697ba02a2b
|
9937950d9a7f534848fc51e96fa5bb226b96017f
|
refs/heads/master
|
<repo_name>juliabouv/js-adagrams<file_sep>/src/adagrams.js
const Adagrams = {
drawLetters() {
const distribution = {
A: 9,
B: 2,
C: 2,
D: 4,
E: 12,
F: 2,
G: 3,
H: 2,
I: 9,
J: 1,
K: 1,
L: 4,
M: 2,
N: 6,
O: 8,
P: 2,
Q: 1,
R: 6,
S: 4,
T: 6,
U: 4,
V: 2,
W: 2,
X: 1,
Y: 2,
Z: 1
}
// convert distribution hash to letters array with all available letters
let letters = [];
for (const letter in distribution) {
for (let i = 0; i < distribution[letter]; i ++) {
letters.push(letter);
}
}
// push 10 random letters to drawnLetters array, removing letter from letters array each time to prevent repitition. This does not effect the distribution hash/the deck
let drawnLetters = [];
for (let i = 0; i < 10; i ++) {
letters.sort(() => Math.random() - 0.5);
drawnLetters.push(letters.pop());
}
return drawnLetters;
},
usesAvailableLetters(input, lettersInHand) {
let currentLetters = lettersInHand;
const string = input.toUpperCase();
for (let i = 0; i < string.length; i++) {
// returns first matching index number
let index = currentLetters.indexOf(string[i]);
if (index !== -1) {
currentLetters.splice(index, 1);
} else {
return false;
}
}
return true;
},
scoreWord(word) {
const string = word.toUpperCase();
let score = (string.length >= 7) ? 8 : 0;
for (let i = 0; i < string.length; i++) {
switch (string[i]) {
case 'A':
case 'E':
case 'I':
case 'O':
case 'U':
case 'L':
case 'N':
case 'R':
case 'S':
case 'T':
score ++;
break;
case 'D':
case 'G':
score += 2;
break;
case 'B':
case 'C':
case 'M':
case 'P':
score += 3;
break;
case 'F':
case 'H':
case 'V':
case 'W':
case 'Y':
score += 4;
break;
case 'K':
score += 5;
break;
case 'J':
case 'X':
score += 8;
break;
case 'Q':
case 'Z':
score += 10
break;
}
}
return score
},
};
// Do not remove this line or your tests will break!
export default Adagrams;
|
b14f60a0d9b9855e37a3dd7a051d5c2549b6ad1c
|
[
"JavaScript"
] | 1 |
JavaScript
|
juliabouv/js-adagrams
|
ef68de100c033d596258938459277c1a2fd307c8
|
1c98ecd608c0c7112578bf2f1c78d862df3e9c6e
|
refs/heads/master
|
<file_sep>package com.nationwide.dashboard.client.exception;
/**
* Created by abdelm2 on 5/4/2015.
*/
public class DashBoardClientException extends Exception {
public DashBoardClientException(String s) {
super(s);
}
public DashBoardClientException(Exception e) {
super(e);
}
}
<file_sep>package com.nationwide.dashboard.client.model.service;
/**
* Created by abdelm2 on 5/4/2015.
*/
public class RetrieveTokenSettingsRequest {
private String env;
private String app;
private String token;
public RetrieveTokenSettingsRequest(String env, String app, String token) {
this.env = env;
this.app = app;
this.token = token;
}
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
}
<file_sep>package com.nationwide.dashboard.client.model.service;
import com.nationwide.dashboard.client.model.Service;
import java.util.List;
/**
* Created by abdelm2 on 5/4/2015.
*/
public class CreateDefaultSettingsRequest {
private String userName;
private String password;
private String env;
private String app;
private List<Service> services;
public CreateDefaultSettingsRequest() {
}
public CreateDefaultSettingsRequest(String userName, String password, String env, String app, List<Service> services) {
this.userName = userName;
this.password = <PASSWORD>;
this.env = env;
this.app = app;
this.services = services;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = <PASSWORD>;
}
public String getEnv() {
return env;
}
public void setEnv(String env) {
this.env = env;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
public List<Service> getServices() {
return services;
}
public void setServices(List<Service> services) {
this.services = services;
}
}
<file_sep>package com.nationwide.dashboard.client.service;
import com.google.gson.Gson;
import com.nationwide.dashboard.client.exception.DashBoardClientException;
import com.nationwide.dashboard.client.model.service.*;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
/**
* Created by abdelm2 on 5/4/2015.
*/
public class DefaultSettingsService extends Service {
public DefaultSettingsService(String dashBoardHost, String dashBoardPort) {
super(dashBoardHost, dashBoardPort);
}
public RetrieveApplicationTemplateResponse retrieveApplicationTemplate(RetrieveApplicationTemplateRequest req)throws DashBoardClientException{
WebResource webResource = getClientResource();
try{
ClientResponse response = webResource.path("/api/settings/template/" + req.getApp()).get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new DashBoardClientException("Failed : HTTP error code : "+ response.getStatus());
}
String output = response.getEntity(String.class);
RetrieveApplicationTemplateResponse res= new Gson().fromJson(output, RetrieveApplicationTemplateResponse.class);
return res;
}
catch (Exception e){
e.printStackTrace();
throw new DashBoardClientException(e);
}
}
public CreateDefaultSettingsResponse createDefaultSettings(CreateDefaultSettingsRequest req)throws DashBoardClientException{
WebResource webResource = getClientResource();
try{
String servicesJsonStr=new Gson().toJson(req.getServices());
String body="{\"auth\":{\"user\":\""+req.getUserName()+"\",\"password\":\""+<PASSWORD>()+"\"},\"services\":"+servicesJsonStr+"}";
ClientResponse response = webResource.path("/api/settings/default/" + req.getEnv()+"/"+req.getApp()).type("application/json").post(ClientResponse.class,body);
if (response.getStatus() != 200) {
throw new DashBoardClientException("Failed : HTTP error code : "+ response.getStatus());
}
String output = response.getEntity(String.class);
return new CreateDefaultSettingsResponse();
}
catch (Exception e){
e.printStackTrace();
throw new DashBoardClientException(e);
}
}
}
<file_sep># DashBoard
use vagrant up from Devops folder
<file_sep>package com.nationwide.dashboard.client.service;
import com.google.gson.Gson;
import com.nationwide.dashboard.client.exception.DashBoardClientException;
import com.nationwide.dashboard.client.model.service.RetrieveServiceSettingsRequest;
import com.nationwide.dashboard.client.model.service.RetrieveServiceSettingsResponse;
import com.nationwide.dashboard.client.model.service.RetrieveTokenSettingsRequest;
import com.nationwide.dashboard.client.model.service.RetrieveTokenSettingsResponse;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
/**
* Created by abdelm2 on 5/4/2015.
*/
public class TokenSettingsService extends Service{
public TokenSettingsService(String dashBoardHost, String dashBoardPort) {
super(dashBoardHost, dashBoardPort);
}
public RetrieveTokenSettingsResponse retrieveTokenSettings(RetrieveTokenSettingsRequest req)throws DashBoardClientException {
WebResource webResource = getClientResource();
try{
ClientResponse response = webResource.path("/api/settings/" + req.getEnv()+"/"+req.getApp()+"/"+req.getToken()).get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new DashBoardClientException("Failed : HTTP error code : "+ response.getStatus());
}
String output = response.getEntity(String.class);
RetrieveTokenSettingsResponse res= new Gson().fromJson(output, RetrieveTokenSettingsResponse.class);
return res;
}
catch (Exception e){
e.printStackTrace();
throw new DashBoardClientException(e);
}
}
public RetrieveServiceSettingsResponse retrieveServiceSettings(RetrieveServiceSettingsRequest req) throws DashBoardClientException{
WebResource webResource = getClientResource();
try{
ClientResponse response = webResource.path("/api/settings/" + req.getEnv()+"/"+req.getApp()+"/"+req.getToken()+"/"+req.getService()).get(ClientResponse.class);
if (response.getStatus() != 200) {
throw new DashBoardClientException("Failed : "+response);
}
String output = response.getEntity(String.class);
RetrieveServiceSettingsResponse res= new Gson().fromJson(output, RetrieveServiceSettingsResponse.class);
return res;
}
catch (Exception e){
e.printStackTrace();
throw new DashBoardClientException(e);
}
}
}
<file_sep>package com.nationwide.dashboard.client.model;
import java.util.List;
/**
* Created by abdelm2 on 5/4/2015.
*/
public class Service {
private String name;
private List<Property> properties;
public Service() {
}
public Service(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public List<Property> getProperties() {
return properties;
}
public void setProperties(List<Property> properties) {
this.properties = properties;
}
}
<file_sep>package com.nationwide.dashboard.client.model.service;
/**
* Created by abdelm2 on 5/4/2015.
*/
public class RetrieveApplicationTemplateRequest {
private String app;
public RetrieveApplicationTemplateRequest(String app) {
this.app = app;
}
public String getApp() {
return app;
}
public void setApp(String app) {
this.app = app;
}
}
|
a2dad9ddbbae90ef7068ba0518638398d4b20c21
|
[
"Markdown",
"Java"
] | 8 |
Java
|
mrfawy/DashBoard
|
f230762b4e227c646794e5278842cd0b1585432a
|
fe7f6b554c39b992224a13ffd3197e53da8fcdc5
|
refs/heads/master
|
<repo_name>mw866/echo<file_sep>/echo.py
import socket, datetime
from flask import Flask, request, render_template, make_response
app = Flask(__name__)
@app.route('/')
def echo():
request_headers_tuple_sorted = sorted(request.headers.items())
time_str = str(datetime.datetime.utcnow())
hostname_str = socket.gethostname()
response = make_response(render_template('index.html' , time=time_str, hostname=hostname_str, request_headers=request_headers_tuple_sorted))
# response.headers['Cache-Control'] = 'no-cache'
# response.headers['Cache-Control'] = 'max-cache=10'
if request.args.get('max_age'):
response.cache_control.max_age = request.args.get('max_age')
else:
response.cache_control.max_age = 0
response.add_etag()
response.last_modified = datetime.datetime.utcnow()
return response
if __name__ == "__main__":
app.run(host='0.0.0.0')
<file_sep>/echo.ini
[uwsgi]
module = wsgi:app
master = true
processes = 5
socket = 127.0.0.1:3031
chmod-socket = 660
vacuum = true
die-on-term = true
logto = /var/log/uwsgi/echo.log
<file_sep>/README.md
## Echo
A Flask application that echos the HTTP request headers sent by you and received by the origin web server.

## Usage
* Run locally:
```
export FLASK_APP=echo.py
export FLASK_DEBUG=1
flask run
```
* Test locally: ` curl localhost -H "Host:echo.chriswang.tech"`
* Restart echo service: ` systemctl restart echo`
* Restart NGINX service: `service nginx restart`
* Check syslog: `tail -f /var/log/syslog`
* Check nginx log: `tail -f /var/log/nginx/error.log`
* Check uwsgi log: `tail -f /var/log/uwsgi/echo.log`
## Installation
```sh
sudo apt-get update
sudo apt-get install nginx python3 python3-pip
pip3 install -r requirements.txt
git clone <EMAIL>:mw866/echo.git
ln -s ~/echo/echo.chriswang.tech /etc/nginx/sites-enabled/
ln ~/echo/echo.service /etc/systemd/system/
```
## Reference
* [Flask Quick Start](http://flask.pocoo.org/docs/0.12/quickstart/)
* [Serve Flask Applications with uWSGI and Nginx on Ubuntu 16.04](https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-16-04)
## Troubleshooting
### "*23 connect() to unix:/root/echo/echo.sock failed (13: Permission denied) while connecting to upstream, client: xxx.xxx.xxx.xxx server: echo.chriswang.tech, request: "GET / HTTP/1.0", upstream: "uwsgi://unix:/root/echo/echo.sock:"
Cause: `namei -l /root/echo/echo.sock` shows that the parent directory of `echo`, i.e. `root` does not permit access by group `www-data`.
Solution: Use local port insted onf Unix socket.
Reference:
* https://www.digitalocean.com/community/tutorials/how-to-serve-flask-applications-with-uwsgi-and-nginx-on-ubuntu-16-04?comment=61900
* http://uwsgi-docs.readthedocs.io/en/latest/Nginx.html
### `uwsgi` is unable to write log to `/var/log/uwsgi/echo.log` in syslog
Solution:
Run `mkdir /var/log/uwsgi/`
|
df7225c57d2fe828f06f3058d3426ffc2f96bbc2
|
[
"Markdown",
"Python",
"INI"
] | 3 |
Python
|
mw866/echo
|
45221b58d7fbb57b953326788b729fda08fdcb8f
|
cd2280e4a6c6f37d9917a58fe2afa57481f5fe8d
|
refs/heads/master
|
<file_sep>artifactId=tallerPiezas1
groupId=es.ucavila.web2
version=1.0
<file_sep>package es.ucavila.web2.tallerpiezas1;
import java.sql.Connection;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author <NAME>
*/
public class ConexionUtil {
Connection cn;
/**
*
* @return
* @throws javax.naming.NamingException
*/
public Connection getConnection() throws NamingException, Exception {
Context ctx = new InitialContext();
if (ctx == null) {
throw new Exception("Error en context");
}
DataSource dataSource = (DataSource) ctx.lookup("java:comp/env/jdbc/empresapiezas");
this.cn = dataSource.getConnection();
return cn;
}
}
<file_sep>/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package es.ucavila.web2.tallerpiezas1;
/**
*
* @author <NAME>
*/
public class Pieza {
private int idPieza;
private String nombrePieza;
private String tipoPieza;
private String descripcionPieza;
private String marca;
private String modelo;
private int numeroPieza;
public Pieza(Pieza p) {
idPieza=p.getIdPieza();
nombrePieza=p.getNombrePieza();
tipoPieza=p.getTipoPieza();
descripcionPieza=p.getDescripcionPieza();
marca=p.getMarca();
modelo=p.getModelo();
numeroPieza=p.getNumeroPieza();
}
public Pieza(){
}
/**
* @return the idPieza
*/
public int getIdPieza() {
return idPieza;
}
/**
* @param idPieza the idPieza to set
*/
public void setIdPieza(int idPieza) {
this.idPieza = idPieza;
}
/**
* @return the nombrePieza
*/
public String getNombrePieza() {
return nombrePieza;
}
/**
* @param nombrePieza the nombrePieza to set
*/
public void setNombrePieza(String nombrePieza) {
this.nombrePieza = nombrePieza;
}
/**
* @return the tipoPieza
*/
public String getTipoPieza() {
return tipoPieza;
}
/**
* @param tipoPieza the tipoPieza to set
*/
public void setTipoPieza(String tipoPieza) {
this.tipoPieza = tipoPieza;
}
/**
* @return the descripcionPieza
*/
public String getDescripcionPieza() {
return descripcionPieza;
}
/**
* @param descripcionPieza the descripcionPieza to set
*/
public void setDescripcionPieza(String descripcionPieza) {
this.descripcionPieza = descripcionPieza;
}
/**
* @return the marca
*/
public String getMarca() {
return marca;
}
/**
* @param marca the marca to set
*/
public void setMarca(String marca) {
this.marca = marca;
}
/**
* @return the modelo
*/
public String getModelo() {
return modelo;
}
/**
* @param modelo the modelo to set
*/
public void setModelo(String modelo) {
this.modelo = modelo;
}
/**
* @return the numeroPieza
*/
public int getNumeroPieza() {
return numeroPieza;
}
/**
* @param numeroPieza the numeroPieza to set
*/
public void setNumeroPieza(int numeroPieza) {
this.numeroPieza = numeroPieza;
}
}
<file_sep>/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package es.ucavila.web2.tallerpiezas1;
import static com.opensymphony.xwork2.Action.ERROR;
import static com.opensymphony.xwork2.Action.SUCCESS;
import java.awt.HeadlessException;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JOptionPane;
/**
*
* @author gonza
*/
public class PiezaAction_Buscar {
private int codigo;
private PiezaDAO dao;
private Pieza pieza;
public PiezaAction_Buscar() {
dao = new PiezaDAO();
pieza = new Pieza();
}
/**
* @return the codigo
*/
public int getCodigo() {
return codigo;
}
/**
* @param codigo the codigo to set
*/
public void setCodigo(int codigo) {
this.codigo = codigo;
}
/**
* @return the dao
*/
public PiezaDAO getDao() {
return dao;
}
/**
* @param dao the dao to set
*/
public void setDao(PiezaDAO dao) {
this.dao = dao;
}
/**
* @return the pieza
*/
public Pieza getPieza() {
return pieza;
}
/**
* @param pieza the pieza to set
*/
public void setPieza(Pieza pieza) {
this.pieza = pieza;
}
public String execute() throws Exception {
try {
ConexionUtil con = new ConexionUtil();
Connection access = con.getConnection();
Statement s = access.createStatement();
String queryId = "select * from usuarios where id='" + codigo + "'";
ResultSet rs = s.executeQuery(queryId);
//Comprobamos si existe previamente el NIF introducido
if (rs.next()) {
//Cargamos el objecto con los datos de la busqueda.
pieza.setDescripcionPieza(rs.getString("descripcion_pieza"));
pieza.setIdPieza(rs.getInt("id_pieza"));
pieza.setMarca(rs.getString("marca"));
pieza.setModelo(rs.getString("modelo"));
pieza.setNombrePieza(rs.getString("nombre_pieza"));
pieza.setTipoPieza(rs.getString("tipo_pieza"));
pieza.setNumeroPieza(rs.getInt("numero_piezas"));
rs.close();
s.close();
access.close();
return SUCCESS;
} //Comprobamos si existe o no el nombre de usuario
else {
JOptionPane.showMessageDialog(null, "No existe la pieza con numero de identificacion: "
+ codigo, "Atenciรณn", JOptionPane.WARNING_MESSAGE);
codigo = 0;
return ERROR;
}
} catch (HeadlessException | SQLException e) {
JOptionPane.showMessageDialog(null, "Error en la busqueda: " + e, "ERROR", JOptionPane.ERROR_MESSAGE);
return ERROR;
}
}
}
|
008e3bcdde1713086941dfb6d1ddbcabf94cbd65
|
[
"Java",
"INI"
] | 4 |
INI
|
gonzaleez17/repositorio-inicial
|
fccb6fbc1587fa2c58a29377c338bddaac50fc65
|
08272a851a1a449edc8b3f18a5b32c304f74cecc
|
refs/heads/master
|
<file_sep>//app.js
var http = require('http'),
util = require('util'),
formidable = require('formidable'),
server;
var fs = require('fs.extra');
var path = require('path')
var settings = require('./settings');
var url = require('url');
var ejs = require('ejs');
var template = fs.readFileSync(settings.viewer_tempate, 'utf-8');
var index = fs.readFileSync('index.ejs', 'utf-8');
var TEST_TMP="./img";
var TEST_PORT=settings.port;//3000;
var exec = require('child_process').exec;
var rmdir = require('rmdir');
var nodemailer = require("nodemailer");
server = http.createServer(function(req, res) {
if (req.url == '/') {
res.writeHead(200, {'content-type': 'text/html'});
var datai = ejs.render(index, {
email: settings.sender
});
res.write(datai);
res.end();
} else if (req.url == '/upload') {
var form = new formidable.IncomingForm(),
files = [],
fields = [];
form.uploadDir = TEST_TMP;
form
.on('field', function(field, value) {
console.log(field, value);
fields.push([field, value]);
})
.on('file', function(field, file) {
console.log(field, file);
files.push([field, file]);
})
.on('end', function() {
var now = new Date().getTime();
console.log('-> upload done');
console.log('received fields:\n\n '+util.inspect(fields));
// res.writeHead(200, {'content-type': 'text/html'});
// res.write('Uploaded: <a href="' + vl + '" target="_blank">viewer link</a>');
// res.end();
if (
(fields.length == 0) ||
(files.length != 1) ||
(fields[1][0] == 'honeypot' && fields[1][1] != '') ||
(files[0][1]['type'].lastIndexOf('image', 0) != 0) ||
(files[0][1]['size'] == 0)
){
res.writeHead(503);
res.write("error.");
res.end();
for (var j=0;i<files.length;j++){
fs.unlinkSync(files[j][1]['path']);
}
return;
}
var filestr = '';
// for(var i =0;i<files.length;i++){
var pat = files[0][1]['path'];
var dir = now.toString();
var child = exec(settings.exepath + " " + pat + " " + now + " 400x400", function(err, stdout, stderr) {
if (!err) {
//console.log('stdout: ' + stdout);
//console.log('stderr: ' + stderr);
//manipulate output
var gifpat = now + '/icon_movie.gif';
//var movpat = pat + '.mp4';
var movpat = now + '/icon_movie.mp4';
// fs.readFile(gifpat,function(err,data){
// if(err){
// console.log(err);
// deleteFiles(pat,dir);
// return;
// }
// var str = data.toString('base64');
fs.readFile(movpat,function(err,datam){
if(err){
console.log(err);
deleteFiles(pat,dir);
return;
}
var strm = datam.toString('base64');
var data = ejs.render(template, {
// imgs: "'data:image/gif;base64," + str + "'",
rotation: "'data:video/mp4;base64," + strm + "'",
// speed: movpat
});
res.writeHead(200, {'Content-Type': 'text/html'});
res.write(data);
res.end();
if (fields[0][0] == 'email' && fields[0][1] != ''){
var emailad = fields[0][1];
var smtpTransport = nodemailer.createTransport("SMTP", {
service: "Gmail",
auth: {
user: settings.GmailAddress,
pass: settings.GmailPass
}
});
var mailOptions={
from:settings.GmailAddress,
to:emailad,
subject:"The Universal Background Filter created your SNS profile image.",
text:"Here is your image. Have fun! (Ignore me if you have no idea why you got this mail.)",
attachments:[
{
filename:"icon.mp4",
filePath:movpat
}
]
};
smtpTransport.sendMail(mailOptions,function(error,response){
if(error){
console.log(error);
}else {
console.log("OK "+ response.message);
}
deleteFiles(pat,dir);
smtpTransport.close();
});
}else{
console.log(pat);
deleteFiles(pat,dir);
}
});
// });
} else {
console.log(err);
// err.code will be the exit code of the child process
console.log(err.code);
//err.signal will be set to the signal that terminated the process
console.log(err.signal);
deleteFiles(pat,dir);
}
});
// }
});
form.parse(req);
} else {
fs.readFile(__dirname + req.url,function(err,data){
if(err){
res.writeHead(500);
return res.end('Error: ' + err);
}
res.writeHead(200);
res.write(data);
res.end();
});
// res.writeHead(404, {'content-type': 'text/plain'});
// res.end('404');
}
});
server.listen(TEST_PORT);
console.log('listening on http://localhost:'+TEST_PORT+'/');
function deleteFiles(pat,dir){
fs.unlinkSync(pat);
rmdir(dir, function (err, dirs, files) {
// console.log(dirs);
// console.log(files);
// console.log('all files are removed');
});
}
String.prototype.endsWith = function(suffix) {
return this.indexOf(suffix, this.length - suffix.length) !== -1;
};
<file_sep>#!/bin/sh
# get public domain flag images from wilipedia
mkdir flags_raw
cd flags_raw
wget -l 1 -r -Apng -H "https://en.wikipedia.org/wiki/Gallery_of_sovereign_state_flags"
#ใใฉใซใๆง้ ใใงใใกใใฃใใฎใงใ็ปๅใ ใใพใจใใฆๆฝๅบใ
mkdir ../flags
find . -name \*Flag_of_\*.png -exec cp {} ../flags/ \;
cd ..
rm -rf flags_raw
exit 0
<file_sep>#!/bin/sh
img=$1
dir=$2
size=$3
# create a directory
mkdir $dir
# resize the flag images and rename them in order
mkdir $dir/flags_resized
#convert flags/*.png -resize $size! $dir/flags_resized/resize_%04d.png
cp flags_resized/* $dir/flags_resized/
# make it an animated gif
#convert -delay 5 -loop 0 $dir/flags_resized/resize_*.png movie.gif
# resize the icon
convert $img -resize $size! $dir/resize_icon.png
# mix the icon and the flags
mkdir $dir/flags_resized_mixed
cd $dir/flags_resized
find . -name \*.png -exec composite -dissolve 10%x100% {} ../resize_icon.png ../flags_resized_mixed/{} \;
cd ../..
# make it an animated gif
#convert -delay 1 -loop 0 $dir/flags_resized_mixed/resize_*.png $dir/icon_movie.gif
# make it an movie
#ffmpeg -r 30 -i $dir/flags_resized_mixed/resize_%4d.png -c:v libx264 -pix_fmt yuv420p -s $size $dir/icon_movie.mp4
ffmpeg -r 30 -i $dir/flags_resized_mixed/resize_%4d.png -vcodec libx264 -pix_fmt yuv420p -s $size $dir/icon_movie.mp4
#cp $dir/icon_movie.mp4 $img.mp4
exit 0
<file_sep># The Universal Background Filter for SNS Profile Picture
A web app that creates your SNS profile picture that contains ALL the national flags in the world. No terrorism, and pray for peace.
SNSใฎใใญใใฃใผใซๅ็ใฎ่ๆฏใซไธ็ไธญใฎใในใฆใฎๅฝใฎๅฝๆใใขใใกใผใทใงใณใใใ็ปๅใ็ๆใใใๅนณๅใฎใใใฎใตใผใในใ

ใใซใฎใผใจใใใฉใณในใจใ็นๅฎใฎๅฝใซ้ๅฎใใใไธ็ไธญใฎใในใฆใฎๅฝใฎๅนณๅใๆใฃใฆใใใใฉใใใใฏใคใพใใฉใฎๅฝใใใใใฆๆใฃใฆใใชใใฎใจๅใใงใใใใงใใใญใฏๆใ
ใฎ้ๅฐๅๅฟใๅพใใฎใ็ฎ็ใฎไธใคใงใใใใใไบใใในใฆใฎๅฝใธใฎ้
ๆ
ฎใ่กจๆใใฆใใใฐใใใญใซไธใใชใใจใใๆๆใฏ่กจๆใงใใใปใปใใใ
# How to use
## Install imagemagick, wget, ffmpeg
```
brew install imagemagick
brew install wget
brew install ffmpeg
```
## Start server
```
npm install
node app
```
And access the app with your browser (default: http://localhost:3000 ).
# For your info: Download public domain flag pictures from wikipedia
```
sh get_flags.sh
```
<file_sep>exports.port = '3000';
exports.exepath = './make.sh';
exports.viewer_tempate = './viewer_nogif.ejs';
exports.sender = 'x@x';
exports.GmailAddress = 'x@x';
exports.GmailPass = 'xxx';
|
026fdfe74f7625e2d408339b5bd8348394f33bca
|
[
"JavaScript",
"Markdown",
"Shell"
] | 5 |
JavaScript
|
qurihara/NationalFlagIcon
|
876d88bca0fcf77c41a4a426802785506fce407f
|
81c4df2f9873f3426afcdaac47cd89c1124fd16d
|
refs/heads/develop
|
<repo_name>lirad/events-manager<file_sep>/app/views/event_atendees/index.json.jbuilder
json.array! @event_atendees, partial: 'event_atendees/event_atendee', as: :event_atendee
<file_sep>/app/models/event_atendee.rb
class EventAtendee < ApplicationRecord
belongs_to :attendees, foreign_key: 'atendee_id', class_name: 'User'
belongs_to :attended_events, foreign_key: 'event_id', class_name: 'Event'
end
<file_sep>/db/migrate/20201014122952_add_foreing_key_events.rb
class AddForeingKeyEvents < ActiveRecord::Migration[6.0]
def change
add_column :events, :user_id, :integer
add_foreign_key :events, :users
end
end
<file_sep>/spec/features/sing_up_and_create_user_spec.rb
require 'rails_helper'
RSpec.feature 'SingUpAndCreateUsers', type: :feature do
scenario 'they can sign up and create events' do
visit new_user_registration_path
fill_in 'user_name', with: '<NAME>'
fill_in 'user_email', with: '<EMAIL>'
fill_in 'user_password', with: '<PASSWORD>'
fill_in 'user_password_confirmation', with: '<PASSWORD>'
click_button 'Sign up'
expect(page).to have_content('Events')
visit new_event_path
expect(page).to have_content('New Event')
fill_in 'event[name]', with: 'Event Name Test'
fill_in 'event[description]', with: 'Event Description Teste'
have_select('event[date(1i)]', selected: 'Option 2')
have_select('event[date(2i)]', selected: 'Option 2')
have_select('event[date(3i)]', selected: 'Option 2')
click_button 'Create Event'
expect(page).to have_content('Event Name Test')
expect(page).to have_content('Event Description Teste')
end
end
<file_sep>/app/controllers/event_atendees_controller.rb
class EventAtendeesController < ApplicationController
before_action :set_event_atendee, only: %i[show edit update destroy]
# GET /event_atendees
# GET /event_atendees.json
def index
@event_atendees = EventAtendee.all
end
# GET /event_atendees/1
# GET /event_atendees/1.json
def show; end
# GET /event_atendees/new
def new
@event_atendee = EventAtendee.new
end
# GET /event_atendees/1/edit
def edit; end
def join_event
event = EventAtendee.create(event_id: params[:format], atendee_id: current_user[:id])
event.save
flash[:notice] = 'Thank you for joining our event!'
redirect_to event_path(params[:format])
end
# POST /event_atendees
# POST /event_atendees.json
def create
@event_atendee = EventAtendee.new(event_atendee_params)
respond_to do |format|
if @event_atendee.save
format.html { redirect_to @event_atendee, notice: 'Event atendee was successfully created.' }
format.json { render :show, status: :created, location: @event_atendee }
else
format.html { render :new }
format.json { render json: @event_atendee.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /event_atendees/1
# PATCH/PUT /event_atendees/1.json
def update
respond_to do |format|
if @event_atendee.update(event_atendee_params)
format.html { redirect_to @event_atendee, notice: 'Event atendee was successfully updated.' }
format.json { render :show, status: :ok, location: @event_atendee }
else
format.html { render :edit }
format.json { render json: @event_atendee.errors, status: :unprocessable_entity }
end
end
end
# DELETE /event_atendees/1
# DELETE /event_atendees/1.json
def destroy
@event_atendee.destroy
respond_to do |format|
format.html { redirect_to event_atendees_url, notice: 'Event atendee was successfully destroyed.' }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_event_atendee
@event_atendee = EventAtendee.find(params[:id])
end
# Only allow a list of trusted parameters through.
def event_atendee_params
params.require(:event_atendee).permit(:event_id, :user_id)
end
end
<file_sep>/spec/models/user_spec.rb
require 'rails_helper'
RSpec.describe User, type: :model do
before :each do
@user = User.create!(name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>')
@event_future = @user.events.create(date: '18.11.2100', name: 'Event name 1', description: 'Description text 1')
@event_past = @user.events.create(date: '18.11.2020', name: 'Event name 2', description: 'Description text 2')
@event_attended = EventAtendee.create(event_id: @event_future.id, atendee_id: @user.id)
end
context 'check for user actions' do
it 'user creation' do
expect(User.first).to eq(@user)
end
it 'user can create events' do
expect(@user.events).to eq([@event_future, @event_past])
end
it 'user can attend events' do
expect(@user.event_atendees.first).to eq(@event_attended)
end
end
end
<file_sep>/spec/models/event_atendee_spec.rb
require 'rails_helper'
RSpec.describe EventAtendee, type: :model do
before :each do
@user = User.create!(name: '<NAME>', email: '<EMAIL>', password: '<PASSWORD>')
@event_future = @user.events.create(date: '18.11.2100', name: 'Event name 1', description: 'Description text 1')
@event_attended = EventAtendee.create(event_id: @event_future.id, atendee_id: @user.id)
end
context 'can have an attendee' do
it 'can be created' do
expect(@user.attended_events.first.user).to eq(@user)
end
it 'can have events that will be attended to' do
expect(Event.first).to eq(@event_future)
end
end
end
<file_sep>/app/helpers/events_helper.rb
module EventsHelper
def joinable_event(user, event)
if user == true && event.date >= Time.now
1
elsif user == 'Not registered' && event.date >= Time.now
2
elsif event.date < Time.now
3
else
4
end
end
end
<file_sep>/test/system/event_atendees_test.rb
require 'application_system_test_case'
class EventAtendeesTest < ApplicationSystemTestCase
setup do
@event_atendee = event_atendees(:one)
end
test 'visiting the index' do
visit event_atendees_url
assert_selector 'h1', text: 'Event Atendees'
end
test 'creating a Event atendee' do
visit event_atendees_url
click_on 'New Event Atendee'
fill_in 'Event', with: @event_atendee.event_id
fill_in 'User', with: @event_atendee.user_id
click_on 'Create Event atendee'
assert_text 'Event atendee was successfully created'
click_on 'Back'
end
test 'updating a Event atendee' do
visit event_atendees_url
click_on 'Edit', match: :first
fill_in 'Event', with: @event_atendee.event_id
fill_in 'User', with: @event_atendee.user_id
click_on 'Update Event atendee'
assert_text 'Event atendee was successfully updated'
click_on 'Back'
end
test 'destroying a Event atendee' do
visit event_atendees_url
page.accept_confirm do
click_on 'Destroy', match: :first
end
assert_text 'Event atendee was successfully destroyed'
end
end
<file_sep>/test/controllers/event_atendees_controller_test.rb
require 'test_helper'
class EventAtendeesControllerTest < ActionDispatch::IntegrationTest
setup do
@event_atendee = event_atendees(:one)
end
test 'should get index' do
get event_atendees_url
assert_response :success
end
test 'should get new' do
get new_event_atendee_url
assert_response :success
end
test 'should create event_atendee' do
assert_difference('EventAtendee.count') do
post event_atendees_url, params:
{ event_atendee: { event_id: @event_atendee.event_id, user_id: @event_atendee.user_id } }
end
assert_redirected_to event_atendee_url(EventAtendee.last)
end
test 'should show event_atendee' do
get event_atendee_url(@event_atendee)
assert_response :success
end
test 'should get edit' do
get edit_event_atendee_url(@event_atendee)
assert_response :success
end
test 'should update event_atendee' do
patch event_atendee_url(@event_atendee), params:
{ event_atendee: { event_id: @event_atendee.event_id, user_id: @event_atendee.user_id } }
assert_redirected_to event_atendee_url(@event_atendee)
end
test 'should destroy event_atendee' do
assert_difference('EventAtendee.count', -1) do
delete event_atendee_url(@event_atendee)
end
assert_redirected_to event_atendees_url
end
end
<file_sep>/README.md
# Events Manager

> This project consists in a event manager platform, where user can Create and Join events. The motivation is to study and apply database relationship concepts while building this application.
## Screenshot

## Live Demo
๐ [Live Demo Link](https://events-manager-microverse.herokuapp.com/)
## Description
I have built this project to function a working Reddit app which lets you create users, posts and comments which are unique to the users. Please follow below to get started.
## Built With ๐
```
- Ruby: 2.6.3
- Ruby on Rails: 6.0.3.4
- Devise for authentication
- UIKit CSS
- Postgres
- VS Code
```
## Install โณ
> Follow these steps below to get my application working
1. - [ ] Git clone or download this repo to your machine
2. - [ ] Inside the `events-manager` folder run `bundle install`
3. - [ ] Run `rails db:create` to create the database
4. - [ ] Run `rails server`
5. - [ ] Visit `localhost:3000` to see the application in action
## Testing โณ
> Follow these steps below to get my application working
Run `rspec` to run the tests
## Authors
### ๐จโ๐ป <NAME>
[](https://github.com/lirad) <br>
[](https://www.linkedin.com/in/diegoalira/) <br>
[](mailto:<EMAIL>) <br>
### ๐ค Contributing
Contributions, issues and feature requests are welcome!
Feel free to check the [issues page](enter issues url here).
### Show your support
Give a โญ๏ธ if you like this project!
### License

<file_sep>/app/views/event_atendees/_event_atendee.json.jbuilder
json.extract! event_atendee, :id, :event_id, :user_id, :created_at, :updated_at
json.url event_atendee_url(event_atendee, format: :json)
<file_sep>/app/controllers/users_controller.rb
class UsersController < ApplicationController
before_action :authenticate_user!
def index
@user = current_user
@events_attended = @user.attended_events
@events_created = @user.events
@past_events_user = @user.attended_events.past_events
@future_events_user = @user.attended_events.future_events
end
def show; end
end
<file_sep>/db/migrate/20201014132404_custom_foreign_key_atendees_table.rb
class CustomForeignKeyAtendeesTable < ActiveRecord::Migration[6.0]
def change
remove_foreign_key :event_atendees, :users
remove_column :event_atendees, :user_id
add_reference :event_atendees, :atendee, references: :users, index:true
add_foreign_key :event_atendees, :users, column: :atendee_id
end
end
<file_sep>/app/models/event.rb
class Event < ApplicationRecord
belongs_to :user, foreign_key: 'creator_id'
has_many :event_atendees
has_many :attendees, through: :event_atendees, foreign_key: 'atendee_id'
scope :past_events, -> { where('date < ?', Time.now.end_of_day) }
scope :future_events, -> { where('date >= ?', Time.now.end_of_day) }
end
<file_sep>/app/views/event_atendees/show.json.jbuilder
json.partial! 'event_atendees/event_atendee', event_atendee: @event_atendee
|
c388e9df7a423e74151c9895d504e2a830efab3a
|
[
"Markdown",
"Ruby"
] | 16 |
Ruby
|
lirad/events-manager
|
02f2db97f66f4dcd1bb107ba4c922793bf440d7f
|
f4a117c181f401fff4a5dfc4f5a12a933592f097
|
refs/heads/master
|
<file_sep>#!/bin/bash
# ignore shutdown in the beginning of the uptime - let's the system settle down
UPTIME=`cat /proc/uptime | sed 's/[\. ].*//'`
if [ $UPTIME -lt 1800 ]; then
exit 0
fi
if [ -e /tmp/do-not-shutdown ]; then
exit 0
fi
logger "Shutting down node due to lack of work!"
/sbin/shutdown -h now
exit 0
<file_sep>#!/bin/bash
/etc/init.d/salt-master stop
/etc/init.d/salt-minion stop
/etc/init.d/crond stop
/etc/init.d/condor stop
/etc/init.d/autofs stop
rm -f /etc/salt/minion_id
chkconfig mdmonitor off
yum -y remove gdm realvnc-vnc-server novnc gnome-session
<file_sep>#!/bin/bash
PREFIX="js-"
LOG=/var/log/atmo/dhcp_hostname.log
# Sync OS time using the host's hardware time
echo $(date +"%m%d%y %H:%M:%S") "Syncing system time with hardware time" >> $LOG
echo " DEBUG: Date BEFORE sync:" $(date) >> $LOG
hwclock -s
rc=$?
echo " DEBUG: Date AFTER sync:" $(date) "hwclock exit status: $rc" >> $LOG
# Function: get_hostname()
# Description: Gets the hostname, depending on the distro
get_hostname() {
local is_centos5=0
if [ -e /etc/redhat-release ]; then
s=$(grep 'CentOS release 5' /etc/redhat-release)
if [ $? -eq 0 ]; then
is_centos5=1
fi
fi
if [ $is_centos5 -eq 1 ]; then
hostname_value=$(curl -s 'http://169.254.169.254/openstack/latest/meta_data.json' | python -c'from simplejson.tool import main; main()' | sed -n -e '/"public-hostname":/ s/^.*"\(.*\)".*/\1/p')
else
hostname_value=$(curl -s 'http://169.254.169.254/openstack/latest/meta_data.json' | python -mjson.tool | sed -n -e '/"public-hostname":/ s/^.*"\(.*\)".*/\1/p')
fi
}
# This function will lookup the ip address
reverse_lookup () {
if [ -n "$1" ]; then
local ip=$1
local htemp=$(dig -x $ip +short)
echo $(date +"%m%d%y %H:%M:%S") " DEBUG: hostname returned from dig = $htemp" >> $LOG
if [ $? -eq 0 -a -n "$htemp" ]; then
hostname_value=$(echo $htemp | sed 's/\.$//')
fi
fi
}
MAX_ATTEMPTS=5
retry=0
hostname_value=""
echo $(date +"%m%d%y %H:%M:%S") "dhclient hostname hook started" >> $LOG
while [ $retry -lt $MAX_ATTEMPTS -a -z "$hostname_value" ]; do
retry=$((retry+1))
echo $(date +"%m%d%y %H:%M:%S") " Attempt #${retry}" >> $LOG
# Note: gobal hostname_value is returned
get_hostname
sleep 1
done
# retest hostname value
if [ -z $hostname_value ]; then
domainname=".$(dnsdomainname)"
if [ $domainname = ".(none)" ];then
domainname=""
fi
third_octet=$(echo $myip | cut -f 3 -d '.')
fourth_octet=$(echo $myip | cut -f 4 -d '.')
fallback_hostname=${PREFIX}${third_octet}-${fourth_octet}${domainname}
# Set hostname to constructed hostname, not machine default
hostname $fallback_hostname
echo $(date +"%m%d%y %H:%M:%S") " Hostname could not be determined. using `hostname`" >> $LOG
else
hostname $hostname_value
echo $hostname_value > /etc/hostname
hostname_value_short=$(echo $hostname_value | sed "s/\..*//")
myip=$(dig $hostname_value +short)
sed -ri "/^.*vm[0-9]+-[0-9]+\.cyverse\.org.*$/d" /etc/hosts
grep -q "$myip $hostname_value $hostname_value_short" /etc/hosts || echo "$myip $hostname_value $hostname_value_short" >> /etc/hosts
echo $(date +"%m%d%y %H:%M:%S") " Hostname has been set to `hostname`" >> $LOG
fi
<file_sep>#!/bin/bash
cd /srv/ariella
git pull
cd jetstream
./bootstrap.sh
<file_sep>#!/bin/bash
set -e
function usage()
{
echo "Usage: bootstrap.sh" 1>&2
exit 1
}
# make sure the base image is up to date
yum -y upgrade
yum -y install epel-release yum-plugin-priorities
# base packages - based on https://github.com/rynge/osgvo-docker
#yum -y install http://repo.grid.iu.edu/osg/3.3/osg-3.3-el7-release-latest.rpm
yum -y groupinstall "Compatibility Libraries" \
"Development Tools" \
"Scientific Support"
yum -y install tcsh wget curl rsync which time bc octave octave-devel \
libtool libtool-ltdl libtool-ltdl-devel \
fontconfig libxml2 openssl098e libGLU libXpm \
binutils-devel gcc libgfortran libgomp \
subversion git gcc-gfortran gcc-c++ binutils binutils-devel \
libquadmath libicu \
python-devel libxml2-devel mesa-libGL-devel \
numpy scipy python-astropy astropy-tools \
glew-devel libX11-devel libXpm-devel libXft-devel libXt \
libXext-devel libXmu-devel tk-devel tcl-devel \
glib-devel glib2-devel gsl-devel \
java-1.8.0-openjdk java-1.8.0-openjdk-devel \
R-devel
# bootstrap salt
yum install -y salt-master salt-minion
mkdir -p /etc/salt/minion.d /etc/salt/master.d
#echo "master: "`hostname -f` >/srv/ariella/jetstream/salt/salt/master.conf
cp /srv/ariella/jetstream/salt/salt/*.conf /etc/salt/minion.d/
cp /srv/ariella/jetstream/salt/salt/jetstream-osg.conf /etc/salt/master.d/
#hostname -f >/etc/salt/minion_id
/etc/init.d/salt-master restart
# run the recipe
salt-call state.highstate >/dev/null 2>&1 || true
if [ -e /etc/salt/pki/master/minions_pre/$HOSTNAME ]; then
mv /etc/salt/pki/master/minions_pre/$HOSTNAME /etc/salt/pki/master/minions/$HOSTNAME
fi
salt-call state.highstate
salt-call state.highstate
yum -y clean all
/etc/init.d/salt-master restart
<file_sep># HTCondor worker setup for Jetstream
To bootstrap:
- Base OS should be CentOS 6
- Log in to the VM as root
- Check out this git repo into /srv/ariella/jetstream
- ./bootstrap.sh {centralmanager} {poolpassword}
<file_sep>#!/bin/bash
# hack - we need an extra reboot to get the disk correctly resized
#if [ ! -e /tmp/.ariella.reboot.1 ]; then
# touch /tmp/.ariella.reboot.1
# cd /srv/ariella
# git fetch --all
# git reset --hard origin/master
#
# cd /srv/ariella/jetstream
# ./bootstrap.sh
# reboot
# exit 0
#fi
find /tmp/ -maxdepth 1 -name .ariella.auto-update -mmin +60 -exec rm -f {} \;
if [ -e /tmp/.ariella.auto-update ]; then
exit 0
fi
cd /srv/ariella
git fetch --all
git reset --hard origin/master
touch /tmp/.ariella.auto-update
|
9204b2e5fdf3d10f67d7136850b5438176a28662
|
[
"Markdown",
"Shell"
] | 7 |
Shell
|
rynge/ariella
|
05d04bb43271b6ef3c139523fdd07dcde926f062
|
847991e436cd38538bce61481cbabb19e3baa52c
|
refs/heads/master
|
<file_sep># baseAlgorithm
### test11111
<file_sep>// export default (string) => {
// return string.split(' ').map(item => {
// return item.split('').reverse().join('');
// }).join(' ');
// }
// export default (string) => {
// return string.split(/\s/g).map(item => {
// return item.split('').reverse().join('');
// }).join(' ');
// }
export default (string) => {
return string.match(/[\w"']+/g).map(item => {
return item.split('').reverse().join('');
}).join(' ');
}<file_sep>function generateRandomArray (n, rangeL, rangeR) {
let arr = [];
for (let i = 0; i < n; i++) {
arr.push(Math.ceil(rangeL + Math.random() * (rangeR - rangeL)));
}
return arr;
}
let arr = generateRandomArray(100, 50, 1500);
// arr.sort((a, b) => a - b);
// console.log(arr)
// ้ๆฉๆๅบ
function selectionSort(arr, n){
for(let i = 0 ; i < n ; i ++){
// ๅฏปๆพ[i, n)ๅบ้ด้็ๆๅฐๅผ
let minIndex = i;
for( let j = i + 1 ; j < n ; j ++ )
if( arr[j] < arr[minIndex] ) minIndex = j;
let temp = arr[i];
arr[i] = arr[minIndex];
arr[minIndex] = temp;
}
}
selectionSort(arr, arr.length);
console.log(arr)
|
fa849c8850cf411f24c07892ab3e89e693d2d14c
|
[
"Markdown",
"JavaScript"
] | 3 |
Markdown
|
tobyjwt/baseAlgorithm
|
6cccfdb623d55f1a0f210f5ec2fed5b327fcb681
|
9d938b8cb2671ec4118619b79487203cb34c6719
|
refs/heads/master
|
<file_sep>import { ApplicationConfig } from './iconfiguration';
export const CONFIG: ApplicationConfig = {
apiURL: 'http://172.16.17.32'
}<file_sep>package com.pichincha.calculadora;
import static org.hamcrest.CoreMatchers.startsWith;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.servlet.MockMvc;
import com.fasterxml.jackson.databind.ObjectMapper;
@RunWith(SpringRunner.class)
@SpringBootTest
@AutoConfigureMockMvc
public class ControllerTest {
@Autowired
private MockMvc mvc;
@Test
public void operaciones_matematicas_numerica() throws Exception {
EntityOperacion entityOperacion = new EntityOperacion();
entityOperacion.setOperacion("5+3");
this.mvc.perform(post("/hello/calculadora").contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
.content(new ObjectMapper().writeValueAsString(entityOperacion))).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"))
.andExpect(content().json("{\r\n" + "\"status\":true,\r\n" + "\"operacion\": 8\r\n" + "}"));
entityOperacion.setOperacion("(5+3)*3+(2*3)");
this.mvc.perform(post("/hello/calculadora").contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
.content(new ObjectMapper().writeValueAsString(entityOperacion))).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"))
.andExpect(content().json("{\r\n" + "\"status\":true,\r\n" + "\"operacion\": 30\r\n" + "}"));
}
@Test
public void operaciones_matematicas_letras() throws Exception {
EntityOperacion entityOperacion = new EntityOperacion();
entityOperacion.setOperacion("dos+cuatro");
this.mvc.perform(post("/hello/calculadora").contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
.content(new ObjectMapper().writeValueAsString(entityOperacion))).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"))
.andExpect(content().json("{\r\n" + "\"status\":false,\r\n" + "\"operacion\": -1\r\n" + "}"));
entityOperacion.setOperacion("dos+tres");
this.mvc.perform(post("/hello/calculadora").contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
.content(new ObjectMapper().writeValueAsString(entityOperacion))).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"))
.andExpect(content().json("{\r\n" + "\"status\":false,\r\n" + "\"operacion\": -1\r\n" + "}"));
}
@Test
public void operaciones_matematicas_error_parentesis() throws Exception {
EntityOperacion entityOperacion = new EntityOperacion();
entityOperacion.setOperacion("((2+3)");
this.mvc.perform(post("/hello/calculadora").contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
.content(new ObjectMapper().writeValueAsString(entityOperacion))).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"))
.andExpect(content().json("{\r\n" + "\"status\":false,\r\n" + "\"operacion\": -1\r\n" + "}"));
entityOperacion.setOperacion("5+3((5");
this.mvc.perform(post("/hello/calculadora").contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
.content(new ObjectMapper().writeValueAsString(entityOperacion))).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"))
.andExpect(content().json("{\r\n" + "\"status\":false,\r\n" + "\"operacion\": -1\r\n" + "}"));
}
@Test
public void operaciones_matematicas_error_aceptacion() throws Exception {
EntityOperacion entityOperacion = new EntityOperacion();
entityOperacion.setOperacion("2+3*3");
this.mvc.perform(post("/hello/calculadora").contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
.content(new ObjectMapper().writeValueAsString(entityOperacion))).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"))
.andExpect(content().json("{\r\n" + "\"status\":true,\r\n" + "\"operacion\": 11\r\n" + "}"));
entityOperacion.setOperacion("(2+4)");
this.mvc.perform(post("/hello/calculadora").contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8")
.content(new ObjectMapper().writeValueAsString(entityOperacion))).andExpect(status().isOk())
.andExpect(content().contentType(MediaType.APPLICATION_JSON_VALUE + ";charset=UTF-8"))
.andExpect(content().json("{\r\n" + "\"status\":true,\r\n" + "\"operacion\": 6\r\n" + "}"));
}
}
<file_sep>import { TestBed, inject } from '@angular/core/testing';
import { AppService } from './app.service';
import { HttpClientModule } from '@angular/common/http';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { Operation } from '../entities/operation.entity';
import { Result } from '../entities/hello-world.entity';
import { CONFIG } from '../../assets/config/configuration';
describe('AppService', () => {
beforeEach(() => TestBed.configureTestingModule({
imports: [
HttpClientModule,
HttpClientTestingModule
]
}));
it('should be created', () => {
const service: AppService = TestBed.get(AppService);
expect(service).toBeTruthy();
});
it('expects service to fetch data with proper sorting',
inject([HttpTestingController, AppService],
(httpMock: HttpTestingController, service: AppService) => {
let operation = new Operation();
let result = new Result();
result.operacion = '7';
result.status = true;
operation.operacion = "5+2";
// We call the service
service.getOperationResult(operation).subscribe(data => {
expect(data.operacion).toBe("7");
expect(data.status).toBeTruthy();
});
// We set the expectations for the HttpClient mock
const req = httpMock.expectOne(CONFIG.apiURL + '/hello/calculadora');
expect(req.request.method).toEqual('POST');
// Then we set the fake data to be returned by the mock
req.flush({ operacion: '7', status: true });
}));
});
<file_sep>#!/bin/bash
apiUrl="//[A-Za-z0-9_.]+"
replaceUrl="//${HOSTNAME}"
filename="./src/assets/config/configuration.ts"
echo sed -i "s/($apiUrl)/(${replaceUrl})/g" "$filename"
<file_sep>### STAGE 1: Build ###
FROM node:10-alpine as build
ARG LOCAL_ENV=false
COPY ./src /app/src/
COPY ./*.json /app/
WORKDIR /app
RUN test $LOCAL_ENV="false" && npm i
## Build angular app in production mode and store the artifacts
RUN $(npm bin)/ng build --prod --output-path=dist
### STAGE 2: Setup ###
FROM nginx:alpine
ENV HOSTNAME=localhost
RUN rm -rf /usr/share/nginx/html/*
COPY nginx.conf /etc/nginx/nginx.conf
WORKDIR /usr/share/nginx/html
COPY --from=build /app/dist/ .
<file_sep>import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
import { Result } from '../entities/hello-world.entity';
import { Operation } from '../entities/operation.entity';
import { CONFIG } from '../../assets/config/configuration'
@Injectable({
providedIn: 'root'
})
export class AppService {
private baseURL: string = CONFIG.apiURL;
constructor(private httpClient: HttpClient) {
}
getOperationResult(operation: Operation): Observable<Result> {
return this.httpClient.post(this.baseURL + "/hello/calculadora", operation);
}
// getConfigJson(): Observable<any> {
// return this.httpClient.get("./assets/config/configuration.json");
// }
}
<file_sep>export class Result {
constructor(public operacion?: string,
public status?: boolean) {
}
}<file_sep>package com.pichincha.calculadora;
import org.springframework.web.bind.annotation.RequestAttribute;
public class EntityOperacion {
private String operacion="";
public String getOperacion() {
return operacion;
}
public void setOperacion(String operacion) {
this.operacion = operacion;
}
public EntityOperacion() {
super();
}
}
<file_sep># Calculadora base application
Calculadora base code
## Getting Started
These instructions will get you a copy of the project up and running on your local machine for development and testing purposes.
See deployment for notes on how to deploy the project on a live system.
### Prerequisites
Docker & Docker compose installed
### Installing
Generate the images
In the application folder run
**Backend:**
docker build -t pichincha/backend backend/.
**Frontend:**
docker build -t pichincha/frontend frontend/.
**Docker Compose:**
docker-compose up
## Running the tests
Run [mvn surefire:test]
## Built With
* [Maven](https://maven.apache.org/) - Dependency Management
## Authors
* **<NAME>** - *Initial work*
* **<NAME>** - *Gitlab upload & Documentation*
<file_sep>import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { MatButtonModule, MatGridListModule, MatInputModule } from '@angular/material';
import { HttpClientModule } from '@angular/common/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { By } from 'protractor';
describe('AppComponent', () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule,
FormsModule,
MatButtonModule,
MatGridListModule,
MatInputModule,
HttpClientModule,
BrowserAnimationsModule
],
declarations: [
AppComponent
],
providers:[]
}).compileComponents();
}));
it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
// it('should add the operation to input and update model', async(()=>{
// const fixture = TestBed.createComponent(AppComponent);
// let field : HTMLInputElement = fixture.debugElement.
// field.value = '5+2';
// field.dispatchEvent(new Event('input'));
// fixture.detectChanges();
// expect(field.textContent).toBe('5+2');
// // expect(operation.operacion)
// }));
// it(`should have a input`, () => {
// const fixture = TestBed.createComponent(AppComponent);
// const compiled = fixture.debugElement.nativeElement;
// expect(compiled.querySelector('input')).;
// });
// it('should render title in a h1 tag', () => {
// const fixture = TestBed.createComponent(AppComponent);
// fixture.detectChanges();
// const compiled = fixture.debugElement.nativeElement;
// expect(compiled.querySelector('h1').textContent).toContain('Welcome to helloWorld!');
// });
});
<file_sep>### STAGE 1: Build ###
FROM maven as build
ARG LOCAL_ENV=false
COPY ./src /app/src/
COPY ./pom.xml /app/
WORKDIR /app
RUN test $LOCAL_ENV="false" && mvn clean install
### STAGE 2: Setup ###
FROM openjdk:11.0.1-jdk-stretch
VOLUME /tmp
COPY --from=build /app/target/calculadora.jar calculadora.jar
ENTRYPOINT ["java","-Djava.security.egd=file:/dev/./urandom","-jar","/calculadora.jar"]
<file_sep>package com.pichincha.calculadora;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
* 30/01/2019
*
* @author dbello
*
*/
@RestController
@RequestMapping("/hello")
public class Controller {
@CrossOrigin(origins = "*")
@PostMapping(path = "/calculadora", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE)
public EntityResultado calculadora(@RequestBody EntityOperacion operacion) {
Calculadora calculadora = new Calculadora();
double resultado = calculadora.operacion(operacion.getOperacion());
EntityResultado entityResultado = new EntityResultado();
entityResultado.setOperacion(resultado);
if (resultado == -1 || resultado==Double.POSITIVE_INFINITY) {
entityResultado.setStatus(false);
} else {
entityResultado.setStatus(true);
}
return entityResultado;
}
}
<file_sep>export class Operation {
constructor(public operacion?: string) { }
}<file_sep>import { Component, OnInit } from '@angular/core';
import { AppService } from './services/app.service';
import { Operation } from './entities/operation.entity';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
result: string;
operation: Operation;
ngOnInit() {
this.operation = new Operation();
this.operation.operacion = '';
this.result = '';
}
firstRow: Tile[] = [
{ text: '7', cols: 1, rows: 1, color: 'lightblue' },
{ text: '8', cols: 1, rows: 1, color: 'lightgreen' },
{ text: '9', cols: 1, rows: 1, color: 'lightpink' },
{ text: '/', cols: 1, rows: 1, color: '#DDBDF1' },
];
secondRow: Tile[] = [
{ text: '4', cols: 1, rows: 1, color: 'lightblue' },
{ text: '5', cols: 1, rows: 1, color: 'lightgreen' },
{ text: '6', cols: 1, rows: 1, color: 'lightpink' },
{ text: '*', cols: 1, rows: 1, color: '#DDBDF1' },
];
thirdRow: Tile[] = [
{ text: '1', cols: 1, rows: 1, color: 'lightblue' },
{ text: '2', cols: 1, rows: 1, color: 'lightgreen' },
{ text: '3', cols: 1, rows: 1, color: 'lightpink' },
{ text: '-', cols: 1, rows: 1, color: '#DDBDF1' },
];
forthRow: Tile[] = [
{ text: 'clear', cols: 1, rows: 1, color: 'lightblue' },
{ text: '0', cols: 1, rows: 1, color: 'lightgreen' },
{ text: '=', cols: 2, rows: 1, color: '#DDBDF1' },
];
fifthRow: Tile[] = [
{ text: '(', cols: 2, rows: 1, color: 'lightblue' },
{ text: ')', cols: 2, rows: 1, color: 'lightgreen' }
];
constructor(private helloWorldService: AppService) {
}
addToOperation(value: string) {
if (value == '=') {
this.helloWorldService.getOperationResult(this.operation).subscribe(response => {
if(response.status == true){
this.result = response.operacion;
}else{
this.result = "ERROR";
}
},error => {
this.result ="Error en comunicaciรณn";
});
} else if (value == 'clear') {
this.operation.operacion = this.operation.operacion.substring(0, this.operation.operacion.length - 1);
// } else if (value == '.') {
// if (this.operation.indexOf('.') == -1) {
// this.operation = this.operation.concat(value);
// }
}
else {
this.operation.operacion = this.operation.operacion.concat(value);
}
}
}
export interface Tile {
color: string;
cols: number;
rows: number;
text: string;
}
|
0d2e86e9aeadc6db254754b81893ea6c46146a7d
|
[
"Markdown",
"Java",
"TypeScript",
"Dockerfile",
"Shell"
] | 14 |
TypeScript
|
scrumtroopersleyends/calculadora
|
4e4c410f4cb8e507b69bdb89879f3c24d0256345
|
333ae61410c75992edc9b494395c482fc7bf8619
|
refs/heads/main
|
<repo_name>Ibrasalma/Banabana<file_sep>/db.php
<?php
$host_name = 'localhost';
$user_name = 'root';
$password = '';
$database_name = 'banabana';
$table_name = 'login';
$conn = mysqli_connect($host_name, $user_name, $password);
if (!$conn) {
die('connection impossible '.mysqli_error());
}
?><file_sep>/README.md
# Banabana
site de service
<file_sep>/login_deal.php
<?php
session_start();
require('db.php');
mysqli_select_db($conn,$database_name);
if(isset($_POST['username']) && isset($_POST['password'])){
$user = htmlspecialchars($_POST['username']);
$pass = htmlspecialchars($_POST['password']);
}
$_SESSION['utilisateur'] = $user;
$query = "SELECT * FROM $table_name WHERE username = '$user' and motdepasse = '$pass'";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
echo mysqli_num_rows($result);
if(mysqli_num_rows($result)==1){
header('location:admin.php');
}else{
echo "Erreur!";
}
?>
|
b1fe5ffb86ea1009eab7ba24aa4013c31681a488
|
[
"Markdown",
"PHP"
] | 3 |
PHP
|
Ibrasalma/Banabana
|
e32fbd510683aa4b8c3bfd73cfeddefb814a77c6
|
7caaec260c7209f9735324b4a695a00bf5b1bc44
|
refs/heads/master
|
<file_sep>const assert = require('assert');
const expect = require('chai').expect;
const fs = require('fs');
const cliUtil = require('../../cli/utils');
const packageJson = require('../../package.json');
const { revertTempDir, testInTempDir } = require('../utils/utils');
describe('jhipster cli utils test', () => {
describe('toString', () => {
describe('should convert primitives to string', () => {
it('returns a string', () => {
expect(cliUtil.toString('test')).to.equal('test');
expect(cliUtil.toString(10)).to.equal('10');
expect(cliUtil.toString(true)).to.equal('true');
});
});
describe('should convert array to string', () => {
it('returns a string', () => {
expect(cliUtil.toString(['test', 'foo'])).to.equal('test, foo');
expect(cliUtil.toString([10, true, 'test'])).to.equal('10, true, test');
});
});
describe('should convert simple objects to string', () => {
it('returns a string', () => {
expect(cliUtil.toString({ string: 'test', bool: true, int: 10 })).to.equal('string: test, bool: true, int: 10');
});
});
describe('should convert complex objects to string', () => {
it('returns a string', () => {
expect(cliUtil.toString({ string: 'test', bool: true, int: 10, array: [1, 2], obj: { test: 1 } })).to.equal(
'string: test, bool: true, int: 10, array: Object, obj: Object'
);
});
});
});
describe('getArgs', () => {
describe('when called without argument', () => {
it('returns an empty string', () => {
expect(cliUtil.getArgs({})).to.equal('');
});
});
describe('when called with argument array', () => {
const argument = ['test', 'foo'];
it('returns a joined string', () => {
expect(cliUtil.getArgs({ argument })).to.equal('[test foo]');
});
});
});
describe('getOptionsFromArgs', () => {
describe('when called with empty args', () => {
it('returns an empty array', () => {
expect(cliUtil.getOptionsFromArgs([])).to.eql([]);
});
});
describe('when called with string arguments', () => {
const argument = ['test', 'foo'];
it('returns an array with strings', () => {
expect(cliUtil.getOptionsFromArgs(argument)).to.eql(['test', 'foo']);
});
});
describe('when called with array & string argument', () => {
const argument = [['bar', 'test'], 'foo'];
it('returns an array with strings', () => {
expect(cliUtil.getOptionsFromArgs(argument)).to.eql(['bar', 'test', 'foo']);
});
});
describe('when called with array & object argument', () => {
const argument = [['bar'], { foo: 'foo' }];
it('returns an array with valid strings', () => {
expect(cliUtil.getOptionsFromArgs(argument)).to.eql(['bar']);
});
});
});
describe('getOptionAsArgs', () => {
describe('when called with empty args', () => {
it('returns a default string array', () => {
expect(cliUtil.getOptionAsArgs({})).to.eql(['--from-cli']);
});
});
describe('when called with valid arguments', () => {
const argument = { foo: true, bar: '123' };
it('returns an array of truthy string args', () => {
expect(cliUtil.getOptionAsArgs(argument)).to.eql(['--foo', '--bar', '123', '--from-cli']);
});
});
describe('when called with valid argument having false value', () => {
const argument = { foo: true, bar: '123', insight: false };
it('returns an array of truthy string args', () => {
expect(cliUtil.getOptionAsArgs(argument)).to.eql(['--foo', '--bar', '123', '--no-insight', '--from-cli']);
});
});
describe('when called with valid arguments and withEntities', () => {
const argument = { foo: true, bar: '123' };
it('returns an array of string args', () => {
expect(cliUtil.getOptionAsArgs(argument, true)).to.eql(['--foo', '--bar', '123', '--with-entities', '--from-cli']);
});
});
describe('when called with valid arguments and force', () => {
const argument = { foo: true, bar: '123' };
it('returns an array of string args', () => {
expect(cliUtil.getOptionAsArgs(argument, false, true)).to.eql(['--foo', '--bar', '123', '--force', '--from-cli']);
});
});
describe('when called with valid arguments with duplicates in different case', () => {
const argument = { fooBar: true, bar: '123', 'foo-bar': true, foo_bar: true };
it('returns an array of string args', () => {
expect(cliUtil.getOptionAsArgs(argument, false, true)).to.eql(['--foo-bar', '--bar', '123', '--force', '--from-cli']);
});
});
describe('when called with valid arguments with single char keys', () => {
const argument = { foo: true, bar: '123', d: true };
it('returns an array of string args', () => {
expect(cliUtil.getOptionAsArgs(argument)).to.eql(['--foo', '--bar', '123', '-d', '--from-cli']);
});
});
});
describe('getCommand', () => {
describe('when called with only cmd', () => {
it('returns a default command', () => {
expect(cliUtil.getCommand('app')).to.eql('app');
});
});
describe('when called with cmd & invalid opts', () => {
it('returns a default command', () => {
expect(cliUtil.getCommand('app', {}, {})).to.eql('app');
});
});
describe('when called with cmd, args & valid opts', () => {
const argument = [['bar', 'foo']];
it('returns a command with argument', () => {
expect(cliUtil.getCommand('app', argument, { argument })).to.eql('app bar foo');
});
});
});
describe('getCommandOptions', () => {
describe('when called with empty argv', () => {
it('returns the default object', () => {
expect(cliUtil.getCommandOptions(packageJson, [])).to.eql({ 'from-cli': true });
});
});
describe('when called with argv flags', () => {
const argv = ['--force', '--skip-install'];
it('returns an object with camelcase and dashcase keys', () => {
expect(cliUtil.getCommandOptions(packageJson, argv)).to.eql({
force: true,
'skip-install': true,
skipInstall: true,
'from-cli': true,
});
});
});
describe('when called with argv flags with value', () => {
const argv = ['--force', '--skip-install', '--foo', 'bar'];
it('returns an object with camelcase and dashcase keys', () => {
expect(cliUtil.getCommandOptions(packageJson, argv)).to.eql({
force: true,
'skip-install': true,
skipInstall: true,
foo: 'bar',
'from-cli': true,
});
});
});
describe('when called with argv flags with value array', () => {
const argv = ['--force', '--skip-install', '--foo', 'bar,who'];
it('returns an object with camelcase and dashcase keys', () => {
expect(cliUtil.getCommandOptions(packageJson, argv)).to.eql({
force: true,
'skip-install': true,
skipInstall: true,
foo: 'bar,who',
'from-cli': true,
});
});
});
});
describe('loadAllBlueprintsWithVersion', () => {
describe('when there is no .yo-rc.json', () => {
let oldCwd;
before(() => {
oldCwd = testInTempDir(() => {}, true);
assert(!fs.existsSync('.yo-rc.json'));
});
after(() => {
revertTempDir(oldCwd);
});
it('returns an empty object', () => {
expect(cliUtil.loadAllBlueprintsWithVersion()).to.deep.equal({});
});
});
describe('when blueprints was passed by command', () => {
let oldCwd;
let oldArgv;
let returned;
before(() => {
oldCwd = testInTempDir(() => {}, true);
oldArgv = process.argv;
process.argv = ['--blueprints', 'vuejs,dotnet'];
assert(!fs.existsSync('.yo-rc.json'));
returned = cliUtil.loadAllBlueprintsWithVersion();
});
after(() => {
process.argv = oldArgv;
revertTempDir(oldCwd);
});
it('returns blueprints with no version', () => {
expect(returned).to.deep.equal({
'generator-jhipster-vuejs': undefined,
'generator-jhipster-dotnet': undefined,
});
});
});
describe('when there are no blueprints on .yo-rc.json', () => {
let oldCwd;
let returned;
before(() => {
oldCwd = testInTempDir(() => {}, true);
const yoRcContent = {
'generator-jhipster': {
blueprints: [],
},
};
fs.writeFileSync('.yo-rc.json', JSON.stringify(yoRcContent));
returned = cliUtil.loadAllBlueprintsWithVersion();
});
after(() => {
fs.unlinkSync('.yo-rc.json');
revertTempDir(oldCwd);
});
it('returns an empty object', () => {
expect(returned).to.deep.equal({});
});
});
describe('when there are blueprints on .yo-rc.json', () => {
let returned;
let oldCwd;
before(() => {
oldCwd = testInTempDir(() => {}, true);
const yoRcContent = {
'generator-jhipster': {
blueprints: [
{ name: 'generator-jhipster-beeblebrox', version: 'latest' },
{ name: 'generator-jhipster-h2g2-answer', version: '42' },
],
},
};
fs.writeFileSync('.yo-rc.json', JSON.stringify(yoRcContent));
returned = cliUtil.loadAllBlueprintsWithVersion();
});
after(() => {
fs.unlinkSync('.yo-rc.json');
revertTempDir(oldCwd);
});
it('returns the blueprints names & versions', () => {
expect(returned).to.deep.equal({
'generator-jhipster-beeblebrox': 'latest',
'generator-jhipster-h2g2-answer': '42',
});
});
});
describe('when blueprints are defined in both command and .yo-rc.json', () => {
let oldCwd;
let oldArgv;
let returned;
before(() => {
oldCwd = testInTempDir(() => {}, true);
oldArgv = process.argv;
assert(!fs.existsSync('.yo-rc.json'));
process.argv = ['--blueprints', 'vuejs,dotnet'];
const yoRcContent = {
'generator-jhipster': {
blueprints: [
{ name: 'generator-jhipster-vuejs', version: 'latest' },
{ name: 'generator-jhipster-h2g2-answer', version: '42' },
],
},
};
fs.writeFileSync('.yo-rc.json', JSON.stringify(yoRcContent));
returned = cliUtil.loadAllBlueprintsWithVersion();
});
after(() => {
fs.unlinkSync('.yo-rc.json');
process.argv = oldArgv;
revertTempDir(oldCwd);
});
it('returns the blueprints names & versions, .yo-rc taking precedence', () => {
expect(returned).to.deep.equal({
'generator-jhipster-vuejs': 'latest',
'generator-jhipster-dotnet': undefined,
'generator-jhipster-h2g2-answer': '42',
});
});
});
});
});
|
87623e20bad170c995e584893ff300913f585fa0
|
[
"JavaScript"
] | 1 |
JavaScript
|
Shaolans/generator-jhipster
|
09020465dc4a6fb608a5bc3a404539e965938254
|
fb753627be32c1053d858161a6a7a45d8762e115
|
refs/heads/master
|
<repo_name>moorn/redis-dns-server<file_sep>/redis_dns_server.go
package main
import (
"encoding/json"
"github.com/hoisie/redis"
"github.com/miekg/dns"
"log"
"net"
"strconv"
"strings"
"time"
)
// TTL Time to Live in seconds
const TTL uint32 = 300
// The key used to read the serial number
const serialNumberKey = "redis-dns-server-serial-no"
// Record is the json format message that is stored in Redis
type Record struct {
CName string `json:"cname"`
PublicIP net.IP `json:"public_ip"`
PrivateIP net.IP `json:"private_ip"`
ValidUntil time.Time `json:"valid_until"`
IPv4PublicIP net.IP `json:"ipv4_public_ip"`
IPv6PublicIP net.IP `json:"ipv6_public_ip"`
IPv4PrivateIP net.IP `json:"ipv4_private_ip"`
}
// RedisDNSServer contains the configuration details for the server
type RedisDNSServer struct {
domain string
hostname string
redisClient redis.Client
mbox string
}
// response is the dns message
type response struct {
*dns.Msg
}
// NewRedisDNSServer is a convienence for creating a new server
func NewRedisDNSServer(domain string, hostname string, redisClient redis.Client, mbox string) *RedisDNSServer {
if !strings.HasSuffix(domain, ".") {
domain += "."
}
if !strings.HasSuffix(mbox, ".") {
mbox += "."
}
if !strings.HasSuffix(hostname, ".") {
hostname += "."
}
server := &RedisDNSServer{
domain: domain,
hostname: hostname,
redisClient: redisClient,
mbox: mbox,
}
dns.HandleFunc(server.domain, server.handleRequest)
return server
}
func (s *RedisDNSServer) listenAndServe(port, net string) {
server := &dns.Server{Addr: port, Net: net}
if err := server.ListenAndServe(); err != nil {
log.Fatalf("%s", err)
}
}
func (s *RedisDNSServer) handleRequest(w dns.ResponseWriter, request *dns.Msg) {
log.Println("The mbox is", s.mbox)
r := new(dns.Msg)
r.SetReply(request)
r.Authoritative = true
for _, msg := range request.Question {
log.Printf("%v %#v %v (id=%v)", dns.TypeToString[msg.Qtype], msg.Name, w.RemoteAddr(), request.Id)
answers := s.Answer(msg)
if len(answers) > 0 {
log.Println("Answers present")
r.Answer = append(r.Answer, answers...)
} else {
log.Println("No Answers present, sending SOA")
r.Answer = append(r.Ns, s.SOA(msg))
}
}
log.Printf("Sent Reply: %+v", r)
w.WriteMsg(r)
}
// Answer crafts a response to the DNS Question
func (s *RedisDNSServer) Answer(msg dns.Question) []dns.RR {
var answers []dns.RR
record := s.Lookup(msg)
ttl := TTL
// Bail out early if the record isn't found in the key store
if record == nil || record.CName == "" {
log.Println("No record in key store, returning nil")
return nil
}
switch msg.Qtype {
case dns.TypeNS:
log.Println("Processing NS request")
if msg.Name == s.domain {
answers = append(answers, &dns.NS{
Hdr: dns.RR_Header{Name: msg.Name, Rrtype: dns.TypeNS, Class: dns.ClassINET, Ttl: 300},
Ns: s.hostname,
})
}
case dns.TypeSOA:
log.Println("Processing SOA request")
log.Println(" Domain is", s.domain)
if msg.Name == s.domain {
log.Println(" msg.Name == s.domain", msg.Name, s.domain)
r := new(dns.SOA)
r.Hdr = dns.RR_Header{Name: msg.Name, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 60}
r.Ns = s.hostname
r.Mbox = s.mbox
r.Serial = s.getSerialNumber()
r.Refresh = 60
r.Retry = 60
r.Expire = 86400
r.Minttl = 60
answers = append(answers, r)
} else {
log.Println(" no match!", msg.Name, s.domain)
}
case dns.TypeA:
log.Println("Processing A request")
addr := record.IPv4PublicIP
// bail if no ip address
if addr == nil {
log.Println("No ip address, returning nil")
return nil
}
r := new(dns.A)
r.Hdr = dns.RR_Header{Name: msg.Name, Rrtype: dns.TypeA, Class: dns.ClassINET, Ttl: ttl}
r.A = addr
answers = append(answers, r)
case dns.TypeAAAA:
log.Println("Processing AAAA request")
addr := record.IPv6PublicIP
// bail if no ip address
if addr == nil {
return nil
}
r := new(dns.AAAA)
r.Hdr = dns.RR_Header{Name: msg.Name, Rrtype: dns.TypeAAAA, Class: dns.ClassINET, Ttl: ttl}
r.AAAA = addr
answers = append(answers, r)
case dns.TypeCNAME:
log.Println("Processing CNAME request")
r := new(dns.CNAME)
r.Hdr = dns.RR_Header{Name: msg.Name, Rrtype: dns.TypeCNAME, Class: dns.ClassINET, Ttl: ttl}
r.Target = msg.Name
answers = append(answers, r)
case dns.TypeMX:
log.Println("Processing MX request")
r := new(dns.MX)
r.Hdr = dns.RR_Header{Name: msg.Name, Rrtype: dns.TypeMX, Class: dns.ClassINET, Ttl: ttl}
r.Preference = 10
r.Mx = msg.Name
answers = append(answers, r)
}
return answers
}
func (s *RedisDNSServer) getSerialNumber() uint32 {
sn, err := s.redisClient.Get(serialNumberKey)
if err != nil {
log.Println("Error reading SN", err)
return uint32(0)
}
x, _ := strconv.Atoi(string(sn))
log.Println("Serial Number is", uint32(x))
return uint32(x)
}
// Lookup will locate the details in Redis for the fqdn, if not found
// lookup will try to locate a wildcard entry for the fqdn
func (s *RedisDNSServer) Lookup(msg dns.Question) *Record {
log.Printf("LOOKUP: Looking for '%s'\n", msg.Name)
str, err := s.redisClient.Get(msg.Name)
log.Printf(" found str\n%s", str)
var result Record
// error indicates that the record was not found
if err != nil {
wildcard := WildCardHostName(msg.Name)
log.Printf("No record for %s, trying wildcard %s\n", msg.Name, wildcard)
domainDots := strings.Count(s.domain, ".") + 1
msgDots := strings.Count(msg.Name, ".")
if msgDots <= domainDots {
log.Printf("msgDots <= domainDots returning nil")
return nil
}
str, err = s.redisClient.Get(wildcard)
if err != nil {
log.Printf("No record for %s\n", wildcard)
return nil
}
}
json.Unmarshal([]byte(str), &result)
return &result
}
func WildCardHostName(hostName string) string {
nameParts := strings.SplitAfterN(hostName, ".", 2)
return "*." + nameParts[1]
}
// SOA returns the Server of Authority record response
func (s *RedisDNSServer) SOA(msg dns.Question) dns.RR {
r := new(dns.SOA)
r.Hdr = dns.RR_Header{Name: s.domain, Rrtype: dns.TypeSOA, Class: dns.ClassINET, Ttl: 60}
r.Ns = s.hostname
r.Mbox = s.mbox
r.Serial = s.getSerialNumber()
r.Refresh = 86400
r.Retry = 7200
r.Expire = 86400
r.Minttl = 60
return r
}
<file_sep>/redis_dns_server_test.go
package main
import (
"testing"
)
func TestWildCardHostName(t *testing.T) {
given := "server.domain.local."
wcName := WildCardHostName(given)
if wcName != "*.domain.local." {
t.Error("Expected *.server.domain.local., got ", wcName)
}
}
<file_sep>/main.go
package main
import (
"flag"
"fmt"
"log"
"net"
"os"
"strings"
"time"
"github.com/elcuervo/redisurl"
"github.com/hoisie/redis"
)
func main() {
flag.Usage = func() {
fmt.Printf("\nUsage: redis-dns-server -domain <domain> -redis-server-url <redis-server-url>\n\n")
flag.PrintDefaults()
fmt.Printf("\nThe dns-server needs permission to bind to given port, default is 53.\n\n")
}
domain := flag.String("domain", "", "Domain for which the server serves")
redisServerURLStr := flag.String("redis-server-url", "", "redis://[:password]@]host:port[/db-number][?option=value]")
hostname := flag.String("hostname", "", "Public hostname of *this* server")
port := flag.Int("port", 53, "Port")
help := flag.Bool("help", false, "Get help")
emailAddr := "admin." + *domain
mbox := flag.String("mbox", emailAddr, "Domain Admin Email Address")
flag.Parse()
if *help {
flag.Usage()
os.Exit(0)
} else if *domain == "" || *redisServerURLStr == "" {
flag.Usage()
fmt.Println(" -domain and -redis-server-url are required parameters")
os.Exit(1)
}
if strings.Contains(*mbox, "@") {
fmt.Println("Email addresses in DNS can not contain the character @")
os.Exit(0)
}
if *hostname == "" {
*hostname, _ = os.Hostname()
}
redisClient := RedisClient(*redisServerURLStr)
server := NewRedisDNSServer(*domain, *hostname, redisClient, *mbox)
portStr := fmt.Sprintf(":%d", *port)
log.Printf("Serving DNS records for *.%s from %s port %s", server.domain,
server.hostname, portStr)
go checkNSRecordMatches(server.domain, server.hostname)
go server.listenAndServe(portStr, "udp")
server.listenAndServe(portStr, "tcp")
}
// RedisClient is a client to the Redis server given by urlStr
func RedisClient(urlStr string) redis.Client {
url := redisurl.Parse(urlStr)
fmt.Println("HOST: ", url.Host)
fmt.Println("DB: ", url.Database)
var client redis.Client
address := fmt.Sprintf("%s:%d", url.Host, url.Port)
client.Addr = address
client.Db = url.Database
log.Printf("Redis DB is %d", url.Database)
client.Password = url.Password
return client
}
func checkNSRecordMatches(domain, hostname string) {
time.Sleep(1 * time.Second)
results, err := net.LookupNS(domain)
if err != nil {
log.Printf("No working NS records found for %s", domain)
}
matched := false
if len(results) > 0 {
for _, record := range results {
if record.Host == hostname {
matched = true
}
}
if !matched {
log.Printf("The NS record for %s is %s", domain, results[0].Host)
log.Printf(" --hostname is %s", hostname)
log.Printf("These must match for DNS to work")
}
}
}
<file_sep>/Dockerfile
FROM alpine
ADD redis-dns-server.linux /redis-dns-server
ADD scripts/docker-entrypoint.sh /docker-entrypoint.sh
# FROM golang:latest
# ADD . /go/src/github.com/dustacio/redis-dns-server
# RUN go get github.com/miekg/dns
# RUN go get github.com/elcuervo/redisurl
# RUN go get github.com/hoisie/redis
# RUN go install github.com/dustacio/redis-dns-server
# ENV is not parsed in CMD/ENTRYPOINT?
# ENTRYPOINT ["/go/src/github.com/dustacio/redis-dns-server/scripts/docker-entrypoint.sh"]
ENTRYPOINT ["/docker-entrypoint.sh"]
EXPOSE 53
|
ebbc3135bf69aaf04e3596555b0dcfb147d0a317
|
[
"Go",
"Dockerfile"
] | 4 |
Go
|
moorn/redis-dns-server
|
b158fe777052ecf1a181735cf71544d7cb3f24bb
|
129f64d6d356355183f883226b4284026dd4a4da
|
refs/heads/master
|
<repo_name>noriondaniel/Aes<file_sep>/src/Template/Purchases/index.ctp
<?php
/* @var $this \Cake\View\View */
$this->extend('../Layout/TwitterBootstrap/dashboard');
$this->start('tb_actions');
?>
<li><?= $this->Html->link(__('New Purchase'), ['action' => 'add']); ?></li>
<li><?= $this->Html->link(__('List Ballots'), ['controller' => 'Ballots', 'action' => 'index']); ?></li>
<li><?= $this->Html->link(__('New Ballot'), ['controller' => 'Ballots', 'action' => 'add']); ?></li>
<li><?= $this->Html->link(__('List Products'), ['controller' => 'Products', 'action' => 'index']); ?></li>
<li><?= $this->Html->link(__('New Product'), ['controller' => 'Products', 'action' => 'add']); ?></li>
<?php $this->end(); ?>
<?php $this->assign('tb_sidebar', '<ul class="nav nav-sidebar">' . $this->fetch('tb_actions') . '</ul>'); ?>
<table class="table table-striped" cellpadding="0" cellspacing="0">
<thead>
<tr>
<th><?= $this->Paginator->sort('id'); ?></th>
<th><?= $this->Paginator->sort('ballot_id'); ?></th>
<th><?= $this->Paginator->sort('product_id'); ?></th>
<th><?= $this->Paginator->sort('quantity'); ?></th>
<th><?= $this->Paginator->sort('created'); ?></th>
<th><?= $this->Paginator->sort('modified'); ?></th>
<th class="actions"><?= __('Actions'); ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($purchases as $purchase): ?>
<tr>
<td><?= $this->Number->format($purchase->id) ?></td>
<td>
<?= $purchase->has('ballot') ? $this->Html->link($purchase->ballot->id, ['controller' => 'Ballots', 'action' => 'view', $purchase->ballot->id]) : '' ?>
</td>
<td>
<?= $purchase->has('product') ? $this->Html->link($purchase->product->name, ['controller' => 'Products', 'action' => 'view', $purchase->product->id]) : '' ?>
</td>
<td><?= $this->Number->format($purchase->quantity) ?></td>
<td><?= h($purchase->created) ?></td>
<td><?= h($purchase->modified) ?></td>
<td class="actions">
<?= $this->Html->link('', ['action' => 'view', $purchase->id], ['title' => __('View'), 'class' => 'btn btn-default glyphicon glyphicon-eye-open']) ?>
<?= $this->Html->link('', ['action' => 'edit', $purchase->id], ['title' => __('Edit'), 'class' => 'btn btn-default glyphicon glyphicon-pencil']) ?>
<?= $this->Form->postLink('', ['action' => 'delete', $purchase->id], ['confirm' => __('Are you sure you want to delete # {0}?', $purchase->id), 'title' => __('Delete'), 'class' => 'btn btn-default glyphicon glyphicon-trash']) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<div class="paginator">
<ul class="pagination">
<?= $this->Paginator->prev('< ' . __('previous')) ?>
<?= $this->Paginator->numbers(['before' => '', 'after' => '']) ?>
<?= $this->Paginator->next(__('next') . ' >') ?>
</ul>
<p><?= $this->Paginator->counter() ?></p>
</div>
<file_sep>/src/Template/Users/verification.ctp
<h3>Your email has been verified, and please login now</h3>
<?php echo $this->Html->link('Login here',['action'=>'login']); ?><file_sep>/tests/TestCase/Model/Table/BoxsTableTest.php
<?php
namespace App\Test\TestCase\Model\Table;
use App\Model\Table\BoxsTable;
use Cake\ORM\TableRegistry;
use Cake\TestSuite\TestCase;
/**
* App\Model\Table\BoxsTable Test Case
*/
class BoxsTableTest extends TestCase
{
/**
* Test subject
*
* @var \App\Model\Table\BoxsTable
*/
public $Boxs;
/**
* Fixtures
*
* @var array
*/
public $fixtures = [
'app.Boxs',
'app.Rentals'
];
/**
* setUp method
*
* @return void
*/
public function setUp()
{
parent::setUp();
$config = TableRegistry::getTableLocator()->exists('Boxs') ? [] : ['className' => BoxsTable::class];
$this->Boxs = TableRegistry::getTableLocator()->get('Boxs', $config);
}
/**
* tearDown method
*
* @return void
*/
public function tearDown()
{
unset($this->Boxs);
parent::tearDown();
}
/**
* Test initialize method
*
* @return void
*/
public function testInitialize()
{
$this->markTestIncomplete('Not implemented yet.');
}
/**
* Test validationDefault method
*
* @return void
*/
public function testValidationDefault()
{
$this->markTestIncomplete('Not implemented yet.');
}
}
<file_sep>/src/Template/Rentals/edit.ctp
<?php
/**
* @var \App\View\AppView $this
* @var \App\Model\Entity\Rental $rental
*/
?>
<?php
$this->extend('../Layout/TwitterBootstrap/dashboard');
$this->start('tb_actions');
?>
<li><?=
$this->Form->postLink(
__('Delete'),
['action' => 'delete', $rental->id],
['confirm' => __('Are you sure you want to delete # {0}?', $rental->id)]
)
?>
</li>
<li><?= $this->Html->link(__('List Rentals'), ['action' => 'index']) ?></li>
<li><?= $this->Html->link(__('List Clients'), ['controller' => 'Clients', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Client'), ['controller' => 'Clients', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Boxs'), ['controller' => 'Boxs', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Box'), ['controller' => 'Boxs', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Workers'), ['controller' => 'Workers', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Worker'), ['controller' => 'Workers', 'action' => 'add']) ?> </li>
<?php
$this->end();
$this->start('tb_sidebar');
?>
<ul class="nav nav-sidebar">
<li><?=
$this->Form->postLink(
__('Delete'),
['action' => 'delete', $rental->id],
['confirm' => __('Are you sure you want to delete # {0}?', $rental->id)]
)
?>
</li>
<li><?= $this->Html->link(__('List Rentals'), ['action' => 'index']) ?></li>
<li><?= $this->Html->link(__('List Clients'), ['controller' => 'Clients', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Client'), ['controller' => 'Clients', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Boxs'), ['controller' => 'Boxs', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Box'), ['controller' => 'Boxs', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Workers'), ['controller' => 'Workers', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Worker'), ['controller' => 'Workers', 'action' => 'add']) ?> </li>
</ul>
<?php
$this->end();
?>
<?= $this->Form->create($rental); ?>
<fieldset>
<legend><?= __('Edit {0}', ['Rental']) ?></legend>
<?php
echo $this->Form->control('client_id', ['options' => $clients]);
echo $this->Form->control('box_id', ['options' => $boxs]);
echo $this->Form->control('worker_id', ['options' => $workers]);
echo $this->Form->control('number_of_people');
echo $this->Form->control('time');
echo $this->Form->control('status');
?>
</fieldset>
<?= $this->Form->button(__("Save")); ?>
<?= $this->Form->end() ?>
<file_sep>/src/Template/Pages/home.ctp
<?php
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 0.10.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
use Cake\Cache\Cache;
use Cake\Core\Configure;
use Cake\Core\Plugin;
use Cake\Datasource\ConnectionManager;
use Cake\Error\Debugger;
use Cake\Http\Exception\NotFoundException;
$this->layout = false;
if (!Configure::read('debug')) :
throw new NotFoundException(
'Please replace src/Template/Pages/home.ctp with your own version or re-enable debug mode.'
);
endif;
$cakeDescription = 'CakePHP: the rapid development PHP framework';
?>
<!DOCTYPE html>
<html>
<head>
<title>Fell Your Voice</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/fotorama/4.6.4/fotorama.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
h1 {
color: white;
text-align: right;
}
body{
background-image: url(http://www.tacadallas.com/wp-content/uploads/2017/04/singing-classes.jpg);
background-position: center center;
background-repeat: no-repeat;
background-attachment: fixed;
background-color: #66999;
background-size: cover;
}
.topnav {
overflow: hidden;
background-color: #333;
}
.topnav a {
float: left;
display: block;
color: #f2f2f2;
text-align: center;
padding: 14px 16px;
text-decoration: none;
font-size: 17px;
}
.topnav a:hover {
background-color: #ddd;
color: black;
}
.topnav a.active {
background-color: #4CAF50;
color: white;
}
.topnav .icon {
display: none;
}
@media screen and (max-width: 600px) {
.topnav a:not(:first-child) {display: none;}
.topnav a.icon {
float: right;
display: block;
}
}
@media screen and (max-width: 600px) {
.topnav.responsive {position: relative;}
.topnav.responsive .icon {
position: absolute;
right: 0;
top: 0;
}
.topnav.responsive a {
float: none;
display: block;
text-align: left;
}
}
.social {
position: relative;
top: -200px;
left: -10px;
/*left: 100;*/
/*top: 200px;*/
/*z-index: 0;*/
}
.social ul {
list-style: none;
}
.social ul li a {
display: inline-block;
color:#fff;
background: #000;
padding: 10px 15px;
text-decoration: none;
-webkit-transition:all 500ms ease;
-o-transition:all 500ms ease;
transition:all 500ms ease;
}
.social ul li a:hover {
background: #000;
padding: 10px 30px;
}
</style>
</head>
<body>
<div class="topnav" id="myTopnav">
<a href="#" class="active" >Home</a>
<a href="users">Users</a>
<a href="clients">Clients</a>
<a href="workers">Workers</a>
<a href="reservations">Reservations</a>
<a href="rentals">Rentals</a>
<a href="punishments">Punishments</a>
<a href="purchases">Purchases</a>
<a href="products">Products</a>
<a href="ballots">Ballots</a>
<a href="boxs">Boxs</a>
<a href="javascript:void(0);" class="icon" onclick="myFunction()">
<i class="fa fa-bars"></i>
</a>
</div>
<script>
function myFunction() {
var x = document.getElementById("myTopnav");
if (x.className === "topnav") {
x.className += " responsive";
} else {
x.className = "topnav";
}
}
</script>
<h1> Box Feel Your Voice</h1>
<div class="fotorama" align="right";
data-width="45%"
data-height="50%"
data-nav="thumbs">
>
<img src="https://scontent.faqp2-2.fna.fbcdn.net/v/t1.0-9/18056703_803548333143500_5756806423038912195_n.jpg?_nc_cat=109&_nc_oc=AQkIXhNuRg5QLeeonv6hm8Jcy7NXbhyoH5Zm4yrwYlWs3RC65qUwNpW6Y0bEopEe9OU&_nc_ht=scontent.faqp2-2.fna&oh=d11a4a6696a38fc96d1c2629fe5078a7&oe=5DB99FC8">
<img src="https://scontent.faqp2-1.fna.fbcdn.net/v/t1.0-9/16708612_767425096755824_5639798534228850308_n.jpg?_nc_cat=111&_nc_oc=AQmbEIhV20xvnIf_sF8yf5iL1ptGZXavCdIkR6yQuPtnUzYYYWTo5D1gZJ1MqvFg2zA&_nc_ht=scontent.faqp2-1.fna&oh=49233ed17033b5880d88abeb6b9c8e80&oe=5D7BC4BC">
<img src="https://scontent.faqp2-2.fna.fbcdn.net/v/t1.0-9/61047198_1291870214311307_6693920815324332032_n.jpg?_nc_cat=104&_nc_oc=AQlSr1rkeaXq42_CbPNBpHkSua807Iof5x46xO65AGzFMtA5FJ5WxrNTH3T6OTF3AGs&_nc_ht=scontent.faqp2-2.fna&oh=df1a177265c70958db5bdf8dc3e4b431&oe=5DAF6574">
</div>
<div class="social">
<ul>
<li><a href="https://www.facebook.com/KaraokeFeelYourVoice/" target="_blank"><img alt="Sรญguenos en Facebook" height="35" width="35" src="https://2.bp.blogspot.com/-28mh2hZK3HE/XCrIxxSCW0I/AAAAAAAAH_M/XniFGT5c2lsaVNgf7UTbPufVmIkBPnWQQCLcBGAs/s1600/facebook.png" title="Sรญguenos en Facebook"/></a>
<li><a href="https://www.youtube.com/?hl=es-419&gl=PE" target="_blank"><img alt="Ir a Youtube" height="35" width="35" src="https://1.bp.blogspot.com/-CUKx1kAd-ls/XCrI4UAvNqI/AAAAAAAAIBI/-i1neUt8kZwP6YOsFOXX5p0Bnqa29m-JgCLcBGAs/s1600/youtube2.png" title="Ir a Youtube"/></a>
<li><a href="https://www.netflix.com/browse" target="_blank"><img alt="Ir a Netflix" height="35" width="35" src="https://images-na.ssl-images-amazon.com/images/I/41Ix1vMUK7L.png" title="Ir a Netflix"/></a>
</ul>
</div>
</body>
</html>
<file_sep>/src/Template/Rentals/view.ctp
<?php
$this->extend('../Layout/TwitterBootstrap/dashboard');
$this->start('tb_actions');
?>
<li><?= $this->Html->link(__('Edit Rental'), ['action' => 'edit', $rental->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Rental'), ['action' => 'delete', $rental->id], ['confirm' => __('Are you sure you want to delete # {0}?', $rental->id)]) ?> </li>
<li><?= $this->Html->link(__('List Rentals'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Rental'), ['action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Clients'), ['controller' => 'Clients', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Client'), ['controller' => 'Clients', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Boxs'), ['controller' => 'Boxs', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Box'), ['controller' => 'Boxs', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Workers'), ['controller' => 'Workers', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Worker'), ['controller' => 'Workers', 'action' => 'add']) ?> </li>
<?php
$this->end();
$this->start('tb_sidebar');
?>
<ul class="nav nav-sidebar">
<li><?= $this->Html->link(__('Edit Rental'), ['action' => 'edit', $rental->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Rental'), ['action' => 'delete', $rental->id], ['confirm' => __('Are you sure you want to delete # {0}?', $rental->id)]) ?> </li>
<li><?= $this->Html->link(__('List Rentals'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Rental'), ['action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Clients'), ['controller' => 'Clients', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Client'), ['controller' => 'Clients', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Boxs'), ['controller' => 'Boxs', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Box'), ['controller' => 'Boxs', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Workers'), ['controller' => 'Workers', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Worker'), ['controller' => 'Workers', 'action' => 'add']) ?> </li>
</ul>
<?php
$this->end();
?>
<div class="panel panel-default">
<!-- Panel header -->
<div class="panel-heading">
<h3 class="panel-title"><?= h($rental->id) ?></h3>
</div>
<table class="table table-striped" cellpadding="0" cellspacing="0">
<tr>
<td><?= __('Client') ?></td>
<td><?= $rental->has('client') ? $this->Html->link($rental->client->id, ['controller' => 'Clients', 'action' => 'view', $rental->client->id]) : '' ?></td>
</tr>
<tr>
<td><?= __('Box') ?></td>
<td><?= $rental->has('box') ? $this->Html->link($rental->box->id, ['controller' => 'Boxs', 'action' => 'view', $rental->box->id]) : '' ?></td>
</tr>
<tr>
<td><?= __('Worker') ?></td>
<td><?= $rental->has('worker') ? $this->Html->link($rental->worker->id, ['controller' => 'Workers', 'action' => 'view', $rental->worker->id]) : '' ?></td>
</tr>
<tr>
<td><?= __('Id') ?></td>
<td><?= $this->Number->format($rental->id) ?></td>
</tr>
<tr>
<td><?= __('Number Of People') ?></td>
<td><?= $this->Number->format($rental->number_of_people) ?></td>
</tr>
<tr>
<td><?= __('Time') ?></td>
<td><?= $this->Number->format($rental->time) ?></td>
</tr>
<tr>
<td><?= __('Created') ?></td>
<td><?= h($rental->created) ?></td>
</tr>
<tr>
<td><?= __('Modified') ?></td>
<td><?= h($rental->modified) ?></td>
</tr>
<tr>
<td><?= __('Status') ?></td>
<td><?= $rental->status ? __('Yes') : __('No'); ?></td>
</tr>
</table>
</div>
<file_sep>/src/Template/Purchases/view.ctp
<?php
$this->extend('../Layout/TwitterBootstrap/dashboard');
$this->start('tb_actions');
?>
<li><?= $this->Html->link(__('Edit Purchase'), ['action' => 'edit', $purchase->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Purchase'), ['action' => 'delete', $purchase->id], ['confirm' => __('Are you sure you want to delete # {0}?', $purchase->id)]) ?> </li>
<li><?= $this->Html->link(__('List Purchases'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Purchase'), ['action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Ballots'), ['controller' => 'Ballots', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Ballot'), ['controller' => 'Ballots', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Products'), ['controller' => 'Products', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Product'), ['controller' => 'Products', 'action' => 'add']) ?> </li>
<?php
$this->end();
$this->start('tb_sidebar');
?>
<ul class="nav nav-sidebar">
<li><?= $this->Html->link(__('Edit Purchase'), ['action' => 'edit', $purchase->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Purchase'), ['action' => 'delete', $purchase->id], ['confirm' => __('Are you sure you want to delete # {0}?', $purchase->id)]) ?> </li>
<li><?= $this->Html->link(__('List Purchases'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Purchase'), ['action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Ballots'), ['controller' => 'Ballots', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Ballot'), ['controller' => 'Ballots', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Products'), ['controller' => 'Products', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Product'), ['controller' => 'Products', 'action' => 'add']) ?> </li>
</ul>
<?php
$this->end();
?>
<div class="panel panel-default">
<!-- Panel header -->
<div class="panel-heading">
<h3 class="panel-title"><?= h($purchase->id) ?></h3>
</div>
<table class="table table-striped" cellpadding="0" cellspacing="0">
<tr>
<td><?= __('Ballot') ?></td>
<td><?= $purchase->has('ballot') ? $this->Html->link($purchase->ballot->id, ['controller' => 'Ballots', 'action' => 'view', $purchase->ballot->id]) : '' ?></td>
</tr>
<tr>
<td><?= __('Product') ?></td>
<td><?= $purchase->has('product') ? $this->Html->link($purchase->product->name, ['controller' => 'Products', 'action' => 'view', $purchase->product->id]) : '' ?></td>
</tr>
<tr>
<td><?= __('Id') ?></td>
<td><?= $this->Number->format($purchase->id) ?></td>
</tr>
<tr>
<td><?= __('Quantity') ?></td>
<td><?= $this->Number->format($purchase->quantity) ?></td>
</tr>
<tr>
<td><?= __('Created') ?></td>
<td><?= h($purchase->created) ?></td>
</tr>
<tr>
<td><?= __('Modified') ?></td>
<td><?= h($purchase->modified) ?></td>
</tr>
</table>
</div>
<file_sep>/src/Template/Ballots/pdf/view.ctp
<div class="ballots view">
<h2>User</h2>
<dl>
<dt><?= __('Client') ?></dt>
<dd>
<?= $this->Number->format($ballot->client->id) ?>
</dd>
<dt><?= __('Id') ?></dt>
<dd>
<?= $this->Number->format($ballot->id) ?>
</dd>
<dt><?= __('Created') ?></dt>
<dd>
<?= h($ballot->created) ?>
</dd>
<dt><?= __('Modified') ?></dt>
<dd>
<?= h($ballot->modified) ?>
</dd>
</dl>
<div class="related">
<h2>Compras</h2>
<?php if (!empty($ballot->purchases)): ?>
<table cellpadding="0" cellspacing="0">
<tr>
<th scope="col"><?= __('Product Id') ?></th>
<th scope="col"><?= __('Created') ?></th>
<th scope="col"><?= __('Modified') ?></th>
</tr>
<?php foreach ($ballot->purchases as $purchases): ?>
<tr>
<td><?= h($purchases->product_id) ?></td>
<td><?= h($purchases->created) ?></td>
<td><?= h($purchases->modified) ?></td>
</tr>
<?php endforeach; ?>
</table>
<?php endif; ?>
</div>
</div><file_sep>/src/Template/Clients/add.ctp
<?php
/**
* @var \App\View\AppView $this
* @var \App\Model\Entity\Client $client
*/
?>
<?php
$this->extend('../Layout/TwitterBootstrap/dashboard');
$this->start('tb_actions');
?>
<li><?= $this->Html->link(__('List Clients'), ['action' => 'index']) ?></li>
<li><?= $this->Html->link(__('List Users'), ['controller' => 'Users', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New User'), ['controller' => 'Users', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Ballots'), ['controller' => 'Ballots', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Ballot'), ['controller' => 'Ballots', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Punishments'), ['controller' => 'Punishments', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Punishment'), ['controller' => 'Punishments', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Rentals'), ['controller' => 'Rentals', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Rental'), ['controller' => 'Rentals', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Reservations'), ['controller' => 'Reservations', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Reservation'), ['controller' => 'Reservations', 'action' => 'add']) ?> </li>
<?php
$this->end();
$this->start('tb_sidebar');
?>
<ul class="nav nav-sidebar">
<li><?= $this->Html->link(__('List Clients'), ['action' => 'index']) ?></li>
<li><?= $this->Html->link(__('List Users'), ['controller' => 'Users', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New User'), ['controller' => 'Users', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Ballots'), ['controller' => 'Ballots', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Ballot'), ['controller' => 'Ballots', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Punishments'), ['controller' => 'Punishments', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Punishment'), ['controller' => 'Punishments', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Rentals'), ['controller' => 'Rentals', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Rental'), ['controller' => 'Rentals', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Reservations'), ['controller' => 'Reservations', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Reservation'), ['controller' => 'Reservations', 'action' => 'add']) ?> </li>
</ul>
<?php
$this->end();
?>
<?= $this->Form->create($client); ?>
<fieldset>
<legend><?= __('Add {0}', ['Client']) ?></legend>
<?php
echo $this->Form->control('user_id', ['options' => $users]);
echo $this->Form->control('dni');
echo $this->Form->control('cell_phone_number');
?>
</fieldset>
<?= $this->Form->button(__("Add")); ?>
<?= $this->Form->end() ?>
<file_sep>/src/Template/Users/add.ctp
<?php
/**
* @var \App\View\AppView $this
* @var \App\Model\Entity\User $user
*/
?>
<?= $this->Html->css(captcha_layout_stylesheet_url(), ['inline' => false]) ?>
<?php
$this->extend('../Layout/TwitterBootstrap/dashboard');
$this->start('tb_actions');
?>
<li><?= $this->Html->link(__('List Users'), ['action' => 'index']) ?></li>
<li><?= $this->Html->link(__('List Clients'), ['controller' => 'Clients', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Client'), ['controller' => 'Clients', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Workers'), ['controller' => 'Workers', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Worker'), ['controller' => 'Workers', 'action' => 'add']) ?> </li>
<?php
$this->end();
$this->start('tb_sidebar');
?>
<ul class="nav nav-sidebar">
<li><?= $this->Html->link(__('List Users'), ['action' => 'index']) ?></li>
<li><?= $this->Html->link(__('List Clients'), ['controller' => 'Clients', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Client'), ['controller' => 'Clients', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Workers'), ['controller' => 'Workers', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Worker'), ['controller' => 'Workers', 'action' => 'add']) ?> </li>
</ul>
<?php
$this->end();
?>
<?= $this->Form->create($user); ?>
<fieldset>
<legend><?= __('Add {0}', ['User']) ?></legend>
<?php
echo $this->Form->control('name');
echo $this->Form->control('email');
echo $this->Form->control('password');
echo $this->Form->control('status');
echo $this->Form->control('role');
?>
</fieldset>
<!-- show captcha image -->
<?= captcha_image_html() ?>
<!-- Captcha code user input textbox -->
<?= $this->Form->input('CaptchaCode', [
'label' => 'Retype the characters from the picture:',
'maxlength' => '10',
'style' => 'width: 270px;',
'id' => 'CaptchaCode'
]) ?>
<?= $this->Form->button(__("Add")); ?>
<?= $this->Form->end() ?>
<file_sep>/src/Controller/UsersController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
use Cake\Utility\Security;
use Cake\Mailer\Email;
use Cake\ORM\TableRegistry;
use Cake\ORM\Entity;
use Cake\Datasource\ConnectionManager;
/**
* Users Controller
*
* @property \App\Model\Table\UsersTable $Users
*
* @method \App\Model\Entity\User[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class UsersController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|void
*/
public function index()
{
$users = $this->paginate($this->Users);
$this->set(compact('users'));
}
/**
* View method
*
* @param string|null $id User id.
* @return \Cake\Http\Response|void
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$user = $this->Users->get($id, [
'contain' => ['Clients', 'Workers']
]);
$this->set('user', $user);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$user = $this->Users->newEntity();
if ($this->request->is('post')) {
// validate the user-entered Captcha code
$isHuman = captcha_validate($this->request->data['CaptchaCode']);
// clear previous user input, since each Captcha code can only be validated once
unset($this->request->data['CaptchaCode']);
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($isHuman && $this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
Email::configTransport('mailtrap', [
'host' => 'smtp.mailtrap.io',
'port' => 2525,
'username' => '55c3<PASSWORD>c',
'password' => '<PASSWORD>',
'className' => 'Smtp'
]);
$emailTo=$user->email;
$mytoken=$user->id;
$email=new Email('default');
$email->transport('mailtrap');
$email->emailFormat('html');
$email->from('<EMAIL>','<NAME>');
$email->subject('Please confirm your email');
$email->to($emailTo);
$email->send('Hi <br/>Please confirm your email link below<br/><a href="http://localhost/plantillaFinal/users/verification/'.$mytoken.'">Verification Email</a><br/>Thank you for joining us');
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact('user'));
}
public function verification($id)
{
$connection = ConnectionManager::get('default');
$connection->update('users', ['status' => 1], ['id'=>$id]);
}
/**
* Edit method
*
* @param string|null $id User id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$user = $this->Users->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$user = $this->Users->patchEntity($user, $this->request->getData());
if ($this->Users->save($user)) {
$this->Flash->success(__('The user has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The user could not be saved. Please, try again.'));
}
$this->set(compact('user'));
}
/**
* Delete method
*
* @param string|null $id User id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$user = $this->Users->get($id);
if ($this->Users->delete($user)) {
$this->Flash->success(__('The user has been deleted.'));
} else {
$this->Flash->error(__('The user could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
public function login()
{
if ($this->request->is('post')) {
// validate the user-entered Captcha code
$isHuman = captcha_validate($this->request->data['CaptchaCode']);
// clear previous user input, since each Captcha code can only be validated once
unset($this->request->data['CaptchaCode']);
$user = $this->Auth->identify();
if ($user && $isHuman) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
}
$this->Flash->error('Your username or password is incorrect.');
}
}
public function initialize()
{
parent::initialize();
$this->Auth->allow(['logout', 'add','verification']);
// load the Captcha component and set its parameter
$this->loadComponent('CakeCaptcha.Captcha', [
'captchaConfig' => 'ExampleCaptcha'
]);
}
public function logout()
{
$this->Flash->success('You are now logged out.');
return $this->redirect($this->Auth->logout());
}
}
<file_sep>/src/Controller/BallotsController.php
<?php
namespace App\Controller;
use App\Controller\AppController;
/**
* Ballots Controller
*
* @property \App\Model\Table\BallotsTable $Ballots
*
* @method \App\Model\Entity\Ballot[]|\Cake\Datasource\ResultSetInterface paginate($object = null, array $settings = [])
*/
class BallotsController extends AppController
{
/**
* Index method
*
* @return \Cake\Http\Response|void
*/
public function index()
{
$this->paginate = [
'contain' => ['Clients']
];
$ballots = $this->paginate($this->Ballots);
$this->set(compact('ballots'));
}
/**
* View method
*
* @param string|null $id Ballot id.
* @return \Cake\Http\Response|void
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function view($id = null)
{
$ballot = $this->Ballots->get($id, [
'contain' => ['Clients', 'Purchases']
]);
$this->viewBuilder()->options([
'pdfConfig' => [
'orientation' => 'portrait',
'filename' => 'Ballot_' . $id . '.pdf'
]
]);
$this->set('ballot', $ballot);
}
/**
* Add method
*
* @return \Cake\Http\Response|null Redirects on successful add, renders view otherwise.
*/
public function add()
{
$ballot = $this->Ballots->newEntity();
if ($this->request->is('post')) {
$ballot = $this->Ballots->patchEntity($ballot, $this->request->getData());
if ($this->Ballots->save($ballot)) {
$this->Flash->success(__('The ballot has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The ballot could not be saved. Please, try again.'));
}
$clients = $this->Ballots->Clients->find('list', ['limit' => 200]);
$this->set(compact('ballot', 'clients'));
}
/**
* Edit method
*
* @param string|null $id Ballot id.
* @return \Cake\Http\Response|null Redirects on successful edit, renders view otherwise.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function edit($id = null)
{
$ballot = $this->Ballots->get($id, [
'contain' => []
]);
if ($this->request->is(['patch', 'post', 'put'])) {
$ballot = $this->Ballots->patchEntity($ballot, $this->request->getData());
if ($this->Ballots->save($ballot)) {
$this->Flash->success(__('The ballot has been saved.'));
return $this->redirect(['action' => 'index']);
}
$this->Flash->error(__('The ballot could not be saved. Please, try again.'));
}
$clients = $this->Ballots->Clients->find('list', ['limit' => 200]);
$this->set(compact('ballot', 'clients'));
}
/**
* Delete method
*
* @param string|null $id Ballot id.
* @return \Cake\Http\Response|null Redirects to index.
* @throws \Cake\Datasource\Exception\RecordNotFoundException When record not found.
*/
public function delete($id = null)
{
$this->request->allowMethod(['post', 'delete']);
$ballot = $this->Ballots->get($id);
if ($this->Ballots->delete($ballot)) {
$this->Flash->success(__('The ballot has been deleted.'));
} else {
$this->Flash->error(__('The ballot could not be deleted. Please, try again.'));
}
return $this->redirect(['action' => 'index']);
}
}
<file_sep>/src/Template/Clients/view.ctp
<?php
$this->extend('../Layout/TwitterBootstrap/dashboard');
$this->start('tb_actions');
?>
<li><?= $this->Html->link(__('Edit Client'), ['action' => 'edit', $client->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Client'), ['action' => 'delete', $client->id], ['confirm' => __('Are you sure you want to delete # {0}?', $client->id)]) ?> </li>
<li><?= $this->Html->link(__('List Clients'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Client'), ['action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Users'), ['controller' => 'Users', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New User'), ['controller' => 'Users', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Ballots'), ['controller' => 'Ballots', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Ballot'), ['controller' => 'Ballots', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Punishments'), ['controller' => 'Punishments', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Punishment'), ['controller' => 'Punishments', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Rentals'), ['controller' => 'Rentals', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Rental'), ['controller' => 'Rentals', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Reservations'), ['controller' => 'Reservations', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Reservation'), ['controller' => 'Reservations', 'action' => 'add']) ?> </li>
<?php
$this->end();
$this->start('tb_sidebar');
?>
<ul class="nav nav-sidebar">
<li><?= $this->Html->link(__('Edit Client'), ['action' => 'edit', $client->id]) ?> </li>
<li><?= $this->Form->postLink(__('Delete Client'), ['action' => 'delete', $client->id], ['confirm' => __('Are you sure you want to delete # {0}?', $client->id)]) ?> </li>
<li><?= $this->Html->link(__('List Clients'), ['action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Client'), ['action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Users'), ['controller' => 'Users', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New User'), ['controller' => 'Users', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Ballots'), ['controller' => 'Ballots', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Ballot'), ['controller' => 'Ballots', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Punishments'), ['controller' => 'Punishments', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Punishment'), ['controller' => 'Punishments', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Rentals'), ['controller' => 'Rentals', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Rental'), ['controller' => 'Rentals', 'action' => 'add']) ?> </li>
<li><?= $this->Html->link(__('List Reservations'), ['controller' => 'Reservations', 'action' => 'index']) ?> </li>
<li><?= $this->Html->link(__('New Reservation'), ['controller' => 'Reservations', 'action' => 'add']) ?> </li>
</ul>
<?php
$this->end();
?>
<div class="panel panel-default">
<!-- Panel header -->
<div class="panel-heading">
<h3 class="panel-title"><?= h($client->id) ?></h3>
</div>
<table class="table table-striped" cellpadding="0" cellspacing="0">
<tr>
<td><?= __('User') ?></td>
<td><?= $client->has('user') ? $this->Html->link($client->user->name, ['controller' => 'Users', 'action' => 'view', $client->user->id]) : '' ?></td>
</tr>
<tr>
<td><?= __('Dni') ?></td>
<td><?= h($client->dni) ?></td>
</tr>
<tr>
<td><?= __('Id') ?></td>
<td><?= $this->Number->format($client->id) ?></td>
</tr>
<tr>
<td><?= __('Cell Phone Number') ?></td>
<td><?= $this->Number->format($client->cell_phone_number) ?></td>
</tr>
<tr>
<td><?= __('Created') ?></td>
<td><?= h($client->created) ?></td>
</tr>
<tr>
<td><?= __('Modified') ?></td>
<td><?= h($client->modified) ?></td>
</tr>
</table>
</div>
<div class="panel panel-default">
<!-- Panel header -->
<div class="panel-heading">
<h3 class="panel-title"><?= __('Related Ballots') ?></h3>
</div>
<?php if (!empty($client->ballots)): ?>
<table class="table table-striped">
<thead>
<tr>
<th><?= __('Id') ?></th>
<th><?= __('Client Id') ?></th>
<th><?= __('Created') ?></th>
<th><?= __('Modified') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($client->ballots as $ballots): ?>
<tr>
<td><?= h($ballots->id) ?></td>
<td><?= h($ballots->client_id) ?></td>
<td><?= h($ballots->created) ?></td>
<td><?= h($ballots->modified) ?></td>
<td class="actions">
<?= $this->Html->link('', ['controller' => 'Ballots', 'action' => 'view', $ballots->id], ['title' => __('View'), 'class' => 'btn btn-default glyphicon glyphicon-eye-open']) ?>
<?= $this->Html->link('', ['controller' => 'Ballots', 'action' => 'edit', $ballots->id], ['title' => __('Edit'), 'class' => 'btn btn-default glyphicon glyphicon-pencil']) ?>
<?= $this->Form->postLink('', ['controller' => 'Ballots', 'action' => 'delete', $ballots->id], ['confirm' => __('Are you sure you want to delete # {0}?', $ballots->id), 'title' => __('Delete'), 'class' => 'btn btn-default glyphicon glyphicon-trash']) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="panel-body">no related Ballots</p>
<?php endif; ?>
</div>
<div class="panel panel-default">
<!-- Panel header -->
<div class="panel-heading">
<h3 class="panel-title"><?= __('Related Punishments') ?></h3>
</div>
<?php if (!empty($client->punishments)): ?>
<table class="table table-striped">
<thead>
<tr>
<th><?= __('Id') ?></th>
<th><?= __('Client Id') ?></th>
<th><?= __('Status') ?></th>
<th><?= __('Type') ?></th>
<th><?= __('Created') ?></th>
<th><?= __('Modified') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($client->punishments as $punishments): ?>
<tr>
<td><?= h($punishments->id) ?></td>
<td><?= h($punishments->client_id) ?></td>
<td><?= h($punishments->status) ?></td>
<td><?= h($punishments->type) ?></td>
<td><?= h($punishments->created) ?></td>
<td><?= h($punishments->modified) ?></td>
<td class="actions">
<?= $this->Html->link('', ['controller' => 'Punishments', 'action' => 'view', $punishments->id], ['title' => __('View'), 'class' => 'btn btn-default glyphicon glyphicon-eye-open']) ?>
<?= $this->Html->link('', ['controller' => 'Punishments', 'action' => 'edit', $punishments->id], ['title' => __('Edit'), 'class' => 'btn btn-default glyphicon glyphicon-pencil']) ?>
<?= $this->Form->postLink('', ['controller' => 'Punishments', 'action' => 'delete', $punishments->id], ['confirm' => __('Are you sure you want to delete # {0}?', $punishments->id), 'title' => __('Delete'), 'class' => 'btn btn-default glyphicon glyphicon-trash']) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="panel-body">no related Punishments</p>
<?php endif; ?>
</div>
<div class="panel panel-default">
<!-- Panel header -->
<div class="panel-heading">
<h3 class="panel-title"><?= __('Related Rentals') ?></h3>
</div>
<?php if (!empty($client->rentals)): ?>
<table class="table table-striped">
<thead>
<tr>
<th><?= __('Id') ?></th>
<th><?= __('Client Id') ?></th>
<th><?= __('Box Id') ?></th>
<th><?= __('Worker Id') ?></th>
<th><?= __('Number Of People') ?></th>
<th><?= __('Time') ?></th>
<th><?= __('Status') ?></th>
<th><?= __('Created') ?></th>
<th><?= __('Modified') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($client->rentals as $rentals): ?>
<tr>
<td><?= h($rentals->id) ?></td>
<td><?= h($rentals->client_id) ?></td>
<td><?= h($rentals->box_id) ?></td>
<td><?= h($rentals->worker_id) ?></td>
<td><?= h($rentals->number_of_people) ?></td>
<td><?= h($rentals->time) ?></td>
<td><?= h($rentals->status) ?></td>
<td><?= h($rentals->created) ?></td>
<td><?= h($rentals->modified) ?></td>
<td class="actions">
<?= $this->Html->link('', ['controller' => 'Rentals', 'action' => 'view', $rentals->id], ['title' => __('View'), 'class' => 'btn btn-default glyphicon glyphicon-eye-open']) ?>
<?= $this->Html->link('', ['controller' => 'Rentals', 'action' => 'edit', $rentals->id], ['title' => __('Edit'), 'class' => 'btn btn-default glyphicon glyphicon-pencil']) ?>
<?= $this->Form->postLink('', ['controller' => 'Rentals', 'action' => 'delete', $rentals->id], ['confirm' => __('Are you sure you want to delete # {0}?', $rentals->id), 'title' => __('Delete'), 'class' => 'btn btn-default glyphicon glyphicon-trash']) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="panel-body">no related Rentals</p>
<?php endif; ?>
</div>
<div class="panel panel-default">
<!-- Panel header -->
<div class="panel-heading">
<h3 class="panel-title"><?= __('Related Reservations') ?></h3>
</div>
<?php if (!empty($client->reservations)): ?>
<table class="table table-striped">
<thead>
<tr>
<th><?= __('Id') ?></th>
<th><?= __('Client Id') ?></th>
<th><?= __('Number Of People') ?></th>
<th><?= __('Start') ?></th>
<th><?= __('Finished') ?></th>
<th><?= __('Status') ?></th>
<th><?= __('Created') ?></th>
<th><?= __('Modified') ?></th>
<th class="actions"><?= __('Actions') ?></th>
</tr>
</thead>
<tbody>
<?php foreach ($client->reservations as $reservations): ?>
<tr>
<td><?= h($reservations->id) ?></td>
<td><?= h($reservations->client_id) ?></td>
<td><?= h($reservations->number_of_people) ?></td>
<td><?= h($reservations->start) ?></td>
<td><?= h($reservations->finished) ?></td>
<td><?= h($reservations->status) ?></td>
<td><?= h($reservations->created) ?></td>
<td><?= h($reservations->modified) ?></td>
<td class="actions">
<?= $this->Html->link('', ['controller' => 'Reservations', 'action' => 'view', $reservations->id], ['title' => __('View'), 'class' => 'btn btn-default glyphicon glyphicon-eye-open']) ?>
<?= $this->Html->link('', ['controller' => 'Reservations', 'action' => 'edit', $reservations->id], ['title' => __('Edit'), 'class' => 'btn btn-default glyphicon glyphicon-pencil']) ?>
<?= $this->Form->postLink('', ['controller' => 'Reservations', 'action' => 'delete', $reservations->id], ['confirm' => __('Are you sure you want to delete # {0}?', $reservations->id), 'title' => __('Delete'), 'class' => 'btn btn-default glyphicon glyphicon-trash']) ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
<?php else: ?>
<p class="panel-body">no related Reservations</p>
<?php endif; ?>
</div>
|
2e1cbe33081b8820e92b3db46ba271f748143762
|
[
"PHP"
] | 13 |
PHP
|
noriondaniel/Aes
|
2351c5f57af425a24374292a567ec97e6a692991
|
612861ccb0a39712da72e4eab9347fc5b87bed83
|
refs/heads/master
|
<file_sep>import React, { useState } from 'react';
import styled from 'styled-components';
import Avatar from './Components/Avatar';
import Text from './Components/Text';
import image from '../src/assets/images/marymeeker.jpg';
import color from './Components/color';
const Container = styled.div`
margin-top: 24px;
display: flex;
flex: 1;
width: 100%;
background-color: ${color.white};
align-items: center;
justify-content: center;
height: 100vh;
`
const ChatContainer = styled.div`
max-width: 500px;
width: 100%;
height: 100vh;
background-color: ${color.white};
display: flex;
`
const UserContainer = styled.div`
flex: 1;
display: flex;
margin-left: 16px;
`
const TimeAgoContainer = styled.div`
flex: 1;
display: flex;
justify-content: flex-end;
`
const CommentContainerOne = styled.div`
position: absolute;
display: flex;
cursor: pointer;
height: auto;
flex: 1;
max-width: 440px;
width: 100%;
background-color: ${color.whiteSmoke};
border-radius: 6px;
padding: 16px 16px 8px 16px;
margin-left: 8px;
// transition: transform 1s;
// :hover {
// opacity: 1;
// transform: rotate(-360deg);
// }
`
const CommentContainerTwo = styled.div`
position: absolute;
display: flex;
cursor: pointer;
height: auto;
flex: 1;
max-width: 440px;
width: 100%;
background-color: ${color.violentViolet};
border-radius: 6px;
padding: 16px 16px 8px 16px;
margin-left: 8px;
opacity: 0;
transition: transform 1s;
:hover {
opacity: 1;
transform: rotate(360deg);
}
`
const CommentData = styled.div`
width: 440px;
flex: 1;
`
const Thing = styled.div`
display: inline-flex;
width: 100%;
`
const A = styled.div`
position: relative;
transition: transform 0.6s;
transform-style: preserve-3d;
position: relative;
`
function Chat () {
const [isHovered, setIsHovered] = useState(false);
const textString = `<NAME> - @marymeeker`;
return (
<Container>
<ChatContainer>
<div>
<Avatar source={image} height={52} />
</div>
<CommentData>
<Thing>
<UserContainer>
<Text align='left' fontWeight='Regular' color={color.violentViolet} fontSize={12} text={textString} />
</UserContainer>
<TimeAgoContainer>
<Text align='left' fontWeight='Regular' color={color.violentViolet} fontSize={12} text='20 mins ago' />
</TimeAgoContainer>
</Thing>
<A>
<CommentContainerOne isHovered={isHovered} onMouseEnter={() => setIsHovered(!isHovered)} onMouseLeave={() => setIsHovered(!isHovered)}>
<Text align='left' fontWeight='Regular' color={color.violentViolet} fontSize={15} text={'Love the lamb stew from this place'} />
</CommentContainerOne>
<CommentContainerTwo onMouseEnter={() => setIsHovered(!isHovered)} onMouseLeave={() => setIsHovered(!isHovered)}>
<Text align='left' fontWeight='Regular' color={color.white} fontSize={15} text={'active since july 14, 2019'} />
</CommentContainerTwo>
</A>
</CommentData>
</ChatContainer>
</Container>
);
}
export default Chat;
<file_sep>import React from 'react';
import styled from 'styled-components';
const Container = styled.img`
height: ${(props) => props.height || '50'}px;
width: ${(props) => props.height || '50'}px;
vertical-align: middle;
border-radius: 50%;
`
function Avatar ({ height, source }) {
return (
<Container height={height} src={source} />
);
}
export default Avatar;
<file_sep>export const color = {
white: '#FFFFFF',
violentViolet: '#291842',
caribbeanGreen: '#00C397',
whiteSmoke: '#F6F6F6',
jungleMist: '#B1BEBE'
}
export default color<file_sep>import React from 'react';
import styled from 'styled-components';
const Container = styled.div`
alignItems: ${(props) => props.align || 'baseline'};
width: ${(props) => props.ellipsis ? '100%' : ''};
`
const TextStyle = styled.p`
font-size: ${(props) => props.fontSize}px;
font-weight: ${(props) => props.fontWeight};
font-family: 'Roboto';
color: ${(props) => props.color};
`
function Text ({ fontSize, color, text, fontWeight, align, ellipsis }) {
return (
<Container align={align || 'baseline'} ellipsis={ellipsis}>
<TextStyle color={color} fontWeight={fontWeight} fontSize={fontSize}>{text}</TextStyle>
</Container>
);
}
export default Text;
<file_sep>## Chat App
Creating a Chat App!
Clone and run `npm run start`
|
bd65aea45531b3f70ad158f78d72089146dfe59d
|
[
"JavaScript",
"Markdown"
] | 5 |
JavaScript
|
Geccles/chat-app
|
e25c15a0302a72b794dda084817dbf19ced859d9
|
880b4866730c758fe8bc9b3fa5aecbc9800f9ba7
|
refs/heads/master
|
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class FXManager : MonoBehaviour {
[Header("Hit Effects")]
[SerializeField] AudioClip hitSFX;
[SerializeField] [Range(0, 1)] float hitSFXVolume = 1.0f;
[SerializeField] GameObject hitVFX;
[SerializeField] float hitVFXDuration = 1f;
[Header("Death Effects")]
[SerializeField] AudioClip deathSFX;
[SerializeField] [Range(0, 1)] float deathSFXVolume = 1.0f;
[SerializeField] GameObject deathVFX;
[SerializeField] float deathVFXDuration = 1f;
CollisionManager collisionManager;
bool hasDied = false;
void Start() {
collisionManager = GetComponent<CollisionManager>();
collisionManager.onHit += HandleHit;
collisionManager.onDeath += HandleDeath;
}
void OnEnable() {
if (collisionManager) {
collisionManager.onHit += HandleHit;
collisionManager.onDeath += HandleDeath;
}
}
void OnDisable() {
collisionManager.onHit -= HandleHit;
collisionManager.onDeath -= HandleDeath;
}
/** HIT */
private void HandleHit(object sender, EventArgs e) {
if (hitSFX) {
AudioSource.PlayClipAtPoint(hitSFX, Camera.main.transform.position, hitSFXVolume);
}
if (hitVFX) {
var fx = Instantiate(hitVFX, transform.position, Quaternion.identity);
Destroy(fx, hitVFXDuration);
}
}
/** DEATH */
private void HandleDeath(object sender, EventArgs e) {
if (hasDied) return;
hasDied = true;
if (deathVFX) {
var fx = Instantiate(deathVFX, transform.position, Quaternion.identity);
Destroy(fx, deathVFXDuration);
}
if (deathSFX) {
AudioSource.PlayClipAtPoint(deathSFX, Camera.main.transform.position, deathSFXVolume);
}
// USE DEATH HANDLER
var deathHandler = gameObject.GetComponent<DeathHandler>();
if (deathHandler) {
deathHandler.Die();
}
// simply destroy
else {
Destroy(gameObject);
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class DeathHandler : MonoBehaviour {
[SerializeField] [Range(0f, 2.0f)] float deathDelay = 1.5f;
public float GetDeathDelay() { return deathDelay; }
public void Die() {
StartCoroutine(DieAfterDelay());
}
IEnumerator DieAfterDelay() {
yield return new WaitForSeconds(deathDelay);
FindObjectOfType<Level>().LoadGameOver();
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class HealthManager : MonoBehaviour {
[SerializeField] int maxHealth = 100;
[SerializeField] int minHealth = 0;
int currentHealth;
public event EventHandler onHealthChanged;
private void Start() {
currentHealth = maxHealth;
}
public int GetHealth() {
return currentHealth;
}
public int GetMaxHealth() {
return maxHealth;
}
public float GetHealthPercent() {
return (float)currentHealth / maxHealth;
}
public void Damage(int amount) {
int beforeChange = currentHealth;
currentHealth -= Mathf.Abs(amount);
// stop at max
if (currentHealth < minHealth) {
currentHealth = minHealth;
}
// no change - bail
if (currentHealth == beforeChange) return;
if (onHealthChanged != null) onHealthChanged(this, EventArgs.Empty);
}
public void Heal(int amount) {
int beforeChange = currentHealth;
currentHealth += Mathf.Abs(amount);
// stop at max
if (currentHealth > maxHealth) {
currentHealth = maxHealth;
}
// no change - bail
if (currentHealth == beforeChange) return;
// change - signal
if (onHealthChanged != null) onHealthChanged(this, EventArgs.Empty);
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class HealthLabeler : MonoBehaviour {
HealthManager healthManager;
TMP_Text label;
void Start() {
var player = FindObjectOfType<Player>();
if (player) {
healthManager = player.healthManager;
if (healthManager) {
healthManager.onHealthChanged += HandleHealthChange;
}
}
label = GetComponent<TMP_Text>();
UpdateDisplay();
}
private void HandleHealthChange(object sender, EventArgs e) {
UpdateDisplay();
}
void UpdateDisplay() {
if (healthManager) {
label.text = $"{healthManager.GetHealth()}";
var healthPerc = healthManager.GetHealthPercent();
if (healthPerc < .25f) {
label.color = new Color32(255, 0, 0, 255);
} else if (healthPerc < .50f) {
label.color = new Color32(255, 150, 0, 255);
} else if (healthPerc < .75f) {
label.color = new Color32(150, 255, 0, 255);
} else {
label.color = new Color32(0, 255, 0, 255);
}
}
}
void OnEnable() {
if (healthManager) {
healthManager.onHealthChanged += HandleHealthChange;
}
}
void OnDisable() {
if (healthManager) {
healthManager.onHealthChanged -= HandleHealthChange;
}
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Player : MonoBehaviour {
[Header("Player")]
[SerializeField] [Range(0.1f, 100f)] float moveSpeed = 10f;
[SerializeField] [Range(0f, 1.0f)] float yMaxRatio = 0.5f;
[Header("Projectile")]
[SerializeField] GameObject laserPrefab;
[SerializeField] float laserSpeed = 15f;
[SerializeField] float laserFirePeriod = 0.1f;
[SerializeField] AudioClip shootSFX;
[SerializeField] [Range(0, 1)] float shootSFXVolume = 1.0f;
Coroutine firingCoroutine;
public HealthManager healthManager;
float xMin, xMax;
float yMin, yMax;
bool isDead = false;
void Start() {
SetUpMoveBoundaries();
healthManager = GetComponent<HealthManager>();
if (healthManager) {
healthManager.onHealthChanged += HandleHealthChange;
}
}
private void HandleHealthChange(object sender, System.EventArgs e) {
if (healthManager.GetHealth() < 1) {
isDead = true;
SpriteRenderer rend = GetComponent<SpriteRenderer>();
rend.enabled = false;
}
}
void Update() {
if (isDead) return;
Move();
Shoot();
}
void Shoot() {
if (firingCoroutine == null && Input.GetButtonDown("Fire1")) {
firingCoroutine = StartCoroutine(FireContinuously());
} else if (firingCoroutine != null && Input.GetButtonUp("Fire1")) {
StopCoroutine(firingCoroutine);
firingCoroutine = null;
}
}
IEnumerator FireContinuously() {
while (true) {
var laser = Instantiate(laserPrefab, transform.position, Quaternion.identity) as GameObject;
laser.GetComponent<Rigidbody2D>().velocity = new Vector2(0, laserSpeed);
if (shootSFX) {
AudioSource.PlayClipAtPoint(shootSFX, Camera.main.transform.position, shootSFXVolume);
}
yield return new WaitForSeconds(laserFirePeriod);
}
}
void SetUpMoveBoundaries() {
var spriteWidth = GetComponent<Renderer>().bounds.size.x;
var spriteHeight = GetComponent<Renderer>().bounds.size.y;
Camera gameCamera = Camera.main;
xMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).x + (spriteWidth / 2);
xMax = gameCamera.ViewportToWorldPoint(new Vector3(1.0f, 0, 0)).x - (spriteWidth / 2);
yMin = gameCamera.ViewportToWorldPoint(new Vector3(0, 0, 0)).y + (spriteHeight / 2);
yMax = gameCamera.ViewportToWorldPoint(new Vector3(0, yMaxRatio, 0)).y - (spriteHeight / 2);
}
void Move() {
var xDelta = Input.GetAxis("Horizontal") * moveSpeed * Time.deltaTime;
var yDelta = Input.GetAxis("Vertical") * moveSpeed * Time.deltaTime;
if (xDelta == 0 && yDelta == 0) return;
var xNew = transform.position.x + xDelta;
var yNew = transform.position.y + yDelta;
transform.position = new Vector2(Mathf.Clamp(xNew, xMin, xMax), Mathf.Clamp(yNew, yMin, yMax));
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Enemy : MonoBehaviour {
[SerializeField] float minTimeBetweenShots = 0.2f;
[SerializeField] float maxTimeBetweenShots = 3f;
[SerializeField] float projectialSpeed = 8f;
[SerializeField] GameObject projectilePrefab;
[SerializeField] AudioClip shootSFX;
[SerializeField] [Range(0, 1)] float shootSFXVolume = 1.0f;
[SerializeField] [Range(0, 2000)] int scoreValue = 125;
float shotCounter;
CollisionManager collisionManager;
bool hasDied = false;
void Start() {
shotCounter = UnityEngine.Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
// listen for death
collisionManager = GetComponent<CollisionManager>();
collisionManager.onDeath += HandleDeath;
}
void OnEnable() {
if (collisionManager) {
collisionManager.onDeath += HandleDeath;
}
}
void OnDisable() {
collisionManager.onDeath -= HandleDeath;
}
void Update() {
CountDownAndShoot();
}
/** DEATH */
private void HandleDeath(object sender, EventArgs e) {
if (hasDied) return;
var gameSession = FindObjectOfType<GameSession>();
var scoreManager = gameSession.scoreManager;
if (scoreManager != null) {
scoreManager.Increase(scoreValue);
}
}
private void CountDownAndShoot() {
shotCounter -= Time.deltaTime;
if (shotCounter <= 0) {
DoFire();
}
}
private void DoFire() {
// reset shot counter
shotCounter = UnityEngine.Random.Range(minTimeBetweenShots, maxTimeBetweenShots);
if (shootSFX) {
AudioSource.PlayClipAtPoint(shootSFX, Camera.main.transform.position, shootSFXVolume);
}
// fire!
var shot = Instantiate(projectilePrefab, transform.position, Quaternion.identity) as GameObject;
shot.GetComponent<Rigidbody2D>().velocity = new Vector2(0, projectialSpeed * -1);
}
}
<file_sep>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GameSession : MonoBehaviour {
public ScoreManager scoreManager {
get {
return GameSessionSingleton.Instance.scoreManager;
}
}
}
public class GameSessionSingleton {
public ScoreManager scoreManager = new ScoreManager();
private GameSessionSingleton() { }
// ------------------------------------
private static GameSessionSingleton _instance;
public static GameSessionSingleton Instance {
get {
if (_instance == null)
_instance = new GameSessionSingleton();
return _instance;
}
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
public class ScoreLabeler : MonoBehaviour {
ScoreManager scoreManager;
TMP_Text label;
void Start() {
var gsCount = FindObjectsOfType<GameSession>().Length;
var gameSession = FindObjectOfType<GameSession>();
scoreManager = gameSession.scoreManager;
if (scoreManager != null) {
scoreManager.onScoreChange += HandleScoreChange;
}
label = GetComponent<TMP_Text>();
UpdateScore();
}
void UpdateScore() {
if (scoreManager != null) {
label.text = $"{scoreManager.Score}";
}
}
void OnEnable() {
if (scoreManager != null) {
scoreManager.onScoreChange += HandleScoreChange;
}
}
void OnDisable() {
if (scoreManager != null) {
scoreManager.onScoreChange -= HandleScoreChange;
}
}
private void HandleScoreChange(object sender, EventArgs e) {
UpdateScore();
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class ScoreManager {
public event EventHandler onScoreChange;
private int _score = 0;
public int Score {
get { return _score; }
private set {
if (value == _score) return;
_score = value;
SignalScoreChange();
}
}
void SignalScoreChange() {
if (onScoreChange != null) onScoreChange(this, EventArgs.Empty);
}
public void Increase(int amount) {
Score += Mathf.Abs(amount);
}
public void Decrease(int amount) {
Score -= Mathf.Abs(amount);
}
public void Reset() {
Score = 0;
}
}
<file_sep>using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class CollisionManager : MonoBehaviour {
public event EventHandler onHit;
public event EventHandler onDeath;
HealthManager healthManager;
void Start() {
healthManager = GetComponent<HealthManager>();
}
void SignalHit() {
if (onHit != null) onHit(this, EventArgs.Empty);
}
void SignalDeath() {
if (onDeath != null) onDeath(this, EventArgs.Empty);
}
void Damage(int damage) {
// UPDATE HEALTH - send signals
if (healthManager != null) {
healthManager.Damage(damage);
if (healthManager.GetHealth() <= 0) {
SignalDeath();
} else {
SignalHit();
}
}
}
void OnTriggerEnter2D(Collider2D other) {
var damageDealer = other.gameObject.GetComponent<DamageDealer>();
if (null == damageDealer) return;
damageDealer.Hit();
Damage(damageDealer.GetDamage());
}
}
|
e0a411a0753b41d5dd4dce95098cbe303ff2e38d
|
[
"C#"
] | 10 |
C#
|
bladnman/Space-Shooter
|
dcf5431b36bbf2f982ccb49f585cd2fa0b3f3fc6
|
df7aaf98b56973fe6671b0bf3e45c731777140bf
|
refs/heads/master
|
<repo_name>Beast2333/subway_simulation<file_sep>/src/txtToCsv.java
import java.io.*;
import java.util.*;
import java.lang.String;
public class txtToCsv {
public void main(String filename){
File writeFile = new File("./nodeRelation0312.csv");
try{
String line=null;
String[] fieldData;
BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filename), "gb2312"));
// Scanner sinScanner=new Scanner(new FileReader(filename));
BufferedWriter writeText = new BufferedWriter(new FileWriter(writeFile));
while(( line = br.readLine() ) != null) {
// line = sinScanner.nextLine();
fieldData = line.split("\t");
writeText.newLine();
writeText.write(fieldData[0]+','+fieldData[1]+','+fieldData[2]+','+fieldData[3]+','+fieldData[4]+',');
System.out.println(fieldData[2]);
}
writeText.flush();
writeText.close();
}catch (FileNotFoundException e){
System.out.println("ๆฒกๆๆพๅฐๆๅฎๆไปถ");
} catch (IOException e) {
System.out.println("ๆไปถ่ฏปๅๅบ้");
}
}
}
|
9d0cf8f55b02bba5937bb4e61af0460e5ca93154
|
[
"Java"
] | 1 |
Java
|
Beast2333/subway_simulation
|
f25abab738ec3362e7ad1c75ecfbb6a684b22e0d
|
a77506936c5789fd0ff42592a2f42568f7cf6c44
|
refs/heads/v0.7a
|
<file_sep>'use strict';
$(function () {
// JQuery selector initialiation ###
var $comingUpGame = $('#comingUpGame');
var $comingUpCathegory = $('#comingUpCathegory');
var $comingUpSystem = $('#comingUpSystem');
var $comingUpPlayer = $('#comingUpPlayer');
var $justMissedGame = $('#justMissedGame');
var $justMissedCathegory = $('#justMissedCathegory');
var $justMissedSystem = $('#justMissedSystem');
var $justMissedPlayer = $('#justMissedPlayer');
var $runnerInfoElements = $('div.runnerInfo');
var $runnerLogos = $('.runnerLogo');
var isInitialized = false;
var displayTwitchforMilliseconds = 15000;
var intervalToNextTwitchDisplay = 120000;
var timeoutTwitchJustMissed = null;
var timeoutTwitchComingUp = null;
// sceneID must be uniqe for this view, it's used in positioning of elements when using edit mode
// if there are two views with the same sceneID all the elements will not have the correct positions
var sceneID = $('html').attr('data-sceneid');
// NodeCG Message subscription ###
nodecg.listenFor("displayMarqueeInformation", displayMarquee);
nodecg.listenFor("removeMarqueeInformation", removeMarquee);
nodecg.listenFor("forceRefreshIntermission", function() {
isInitialized = false;
if(typeof runDataActiveRunReplicant.value == 'undefined' || runDataActiveRunReplicant.value == "") {
//return;
}
var indexOfCurrentRun = findIndexInDataArrayOfRun(runDataActiveRunReplicant.value, runDataArrayReplicant.value);
var indexOfNextRun = Number(indexOfCurrentRun) + Number(1);
var comingUpRun = undefined;
if(indexOfNextRun >= runDataArrayReplicant.value.length) {
}
else {
comingUpRun = runDataArrayReplicant.value[indexOfNextRun];
}
if(!isInitialized) {
updateMissedComingUp(runDataActiveRunReplicant.value, comingUpRun);
isInitialized = true;
}
});
// Replicants ###
var sceneLayoutConfigurationReplicant = nodecg.Replicant('sceneLayoutConfiguration');
sceneLayoutConfigurationReplicant.on('change', function(oldVal, newVal) {
if(typeof newValue !== 'undefined' && newValue != "") {
applyBackgroundTransparence(newVal.backgroundTransparency);
handleEditMode(newVal.editMode)
}
});
var runDataArrayReplicant = nodecg.Replicant("runDataArray");
runDataArrayReplicant.on("change", function (oldValue, newValue) {
});
var runDataActiveRunReplicant = nodecg.Replicant("runDataActiveRun");
runDataActiveRunReplicant.on("change", function (oldValue, newValue) {
if(typeof newValue == 'undefined' || newValue == "") {
//return;
}
var indexOfCurrentRun = findIndexInDataArrayOfRun(newValue, runDataArrayReplicant.value);
var indexOfNextRun = Number(indexOfCurrentRun) + Number(1);
var comingUpRun = undefined;
if(indexOfNextRun >= runDataArrayReplicant.value.length) {
}
else {
comingUpRun = runDataArrayReplicant.value[indexOfNextRun];
}
if(!isInitialized) {
updateMissedComingUp(newValue, comingUpRun);
isInitialized = true;
}
});
function findIndexInDataArrayOfRun(run, runDataArray) {
var indexOfRun = -1;
$.each(runDataArray, function (index, value) {
if (value && run && value.runID == run.runID) {
indexOfRun = index;
}
});
return indexOfRun;
}
function updateMissedComingUp(currentRun, nextRun) {
changeComingUpRunInformation(nextRun);
changeJustMissedRunInformation(currentRun);
$runnerLogos.each( function(index, element) {
$(this).fadeOut(500, function() {
$(this).removeClass('nameLogo').addClass('twitchLogo').fadeIn(500);
});
});
}
// Replicant functions ###
function changeComingUpRunInformation(runData) {
var game = "END";
var category = "";
var system = "";
var player = "";
var playerTwitch = ""
var playerArray = [];
var playerTwitchArray = [];
if(typeof runData !== "undefined" && runData !== '') {
game = runData.game;
category = runData.category;
system = runData.system;
for (var i = 0; i < runData.players.length; i++) {
playerArray.push(runData.players[i].names.international);
playerTwitchArray.push(getRunnerInformationTwitch(runData.players[i]));
}
player = playerArray.join(', ');
playerTwitch = playerTwitchArray.join(', ');
}
animation_setGameField($comingUpGame,game);
animation_setGameField($comingUpCathegory,category);
animation_setGameField($comingUpSystem,system);
animation_setGameFieldAlternate($comingUpPlayer,playerTwitch);
}
function changeJustMissedRunInformation(runData) {
var game = "START";
var category = "";
var system = "";
var player = "";
var playerTwitch = ""
var playerArray = [];
var playerTwitchArray = [];
if(typeof runData !== "undefined" && runData !== '') {
game = runData.game;
category = runData.category;
system = runData.system;
for (var i = 0; i < runData.players.length; i++) {
playerArray.push(runData.players[i].names.international);
playerTwitchArray.push(getRunnerInformationTwitch(runData.players[i]));
}
player = playerArray.join(', ');
playerTwitch = playerTwitchArray.join(', ');
}
animation_setGameField($justMissedGame,game);
animation_setGameField($justMissedCathegory,category);
animation_setGameField($justMissedSystem,system);
animation_setGameFieldAlternate($justMissedPlayer,playerTwitch);
}
function getRunnerInformationTwitch(runData) {
var twitchUrl = "";
if (runData.twitch != null &&
runData.twitch.uri != null) {
twitchUrl = 'twitch.tv/' + runData.twitch.uri.replace("http://www.twitch.tv/","");
}
else {
twitchUrl = runData.names.international;
}
if (twitchUrl == "") {
twitchUrl = runData.names.international;
}
return twitchUrl;
}
function displayTwitchInstead(justMissed, $element, player, playerTwitch) {
animation_setGameFieldAlternate($element, playerTwitch);
var tm = new TimelineMax({paused: true});
if (!justMissed) {
$runnerLogos.each( function(index, element) {
//animation_showZoomIn($(this));
$(this).fadeOut(500, function() {
$(this).removeClass('nameLogo').addClass('twitchLogo').fadeIn(500);
});
});
}
tm.play();
if (justMissed) {timeoutTwitchJustMissed = setTimeout(function() {hideTwitch(justMissed, $element, player, playerTwitch)},displayTwitchforMilliseconds);}
else {timeoutTwitchComingUp = setTimeout(function() {hideTwitch(justMissed, $element, player, playerTwitch)},displayTwitchforMilliseconds);}
}
function hideTwitch(justMissed, $element, player, playerTwitch) {
animation_setGameFieldAlternate($element, player);
if (!justMissed) {
$runnerLogos.each( function(index, element) {
//animation_hideZoomOut($(this));
$(this).fadeOut(500, function() {
$(this).removeClass('twitchLogo').addClass('nameLogo').fadeIn(500);
});
});
}
if (justMissed) {timeoutTwitchJustMissed = setTimeout(function() {displayTwitchInstead(justMissed, $element, player, playerTwitch)},intervalToNextTwitchDisplay);}
else {timeoutTwitchComingUp = setTimeout(function() {displayTwitchInstead(justMissed, $element, player, playerTwitch)},intervalToNextTwitchDisplay);}
}
// General functions ###
function applyBackgroundTransparence(value) {
if (value == 'On') {
$('#window-container').css('opacity',0.5);
}
else if (value == 'Off') {
$('#window-container').css('opacity',1.0);
}
}
function displayMarquee(text) {
$('#informationMarquee').html(text);
$('#informationMarquee').css('opacity', '1');
var tm = new TimelineMax({paused: true});
tm.to($('#informationMarquee'), 1.0, {opacity: '1', top: "1021px", ease: Bounce.easeOut },'0');
tm.play();
}
function removeMarquee() {
var tm = new TimelineMax({paused: true});
tm.to($('#informationMarquee'), 1.0, {opacity: '1', top: "1080px", ease: Bounce.easeOut , onComplete:function() {
$('#informationMarquee').css('opacity', '0');
}},'0');
tm.play();
}
function loadCSS (href) {
var cssLink = $("<link rel='stylesheet' type='text/css' href='"+href+"'>");
$("head").append(cssLink);
};
loadCSS("/graphics/nodecg-speedcontrol/css/editcss/"+sceneID+".css");
});
|
b872b00209a3f3b7d31e6548550324dd49fa1fd7
|
[
"JavaScript"
] | 1 |
JavaScript
|
j4sp3rr/nodecg-speedcontrol
|
246e33eef0b8a1b5373182a77102a20ede926183
|
17b3b673ba165a1608bf84d13ec18812674a5346
|
refs/heads/master
|
<repo_name>fengchaoWn/newDyCode<file_sep>/weixin-java-open-demo/src/main/java/com/github/binarywang/demo/wechat/utils/GIfUtil.java
package com.github.binarywang.demo.wechat.utils;
import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;
public class GIfUtil {
/**
* ่ทๅGIFๅพ็ไธๅธงๅพ็ - ๅๆญฅๆง่ก
* @param src ๆบๅพ็่ทฏๅพ
* @param target ็ฎๆ ๅพ็่ทฏๅพ
* @param frame ่ทๅ็ฌฌๅ ๅธง
* @throws Exception
*/
public static void saveGif(String src, String target, int frame) throws Exception {
try {
//่ฆๆไฝ็ๅพ็
FileInputStream is=new FileInputStream("http://od710rrnd.bkt.clouddn.com/biz/img/201805181519057276630.gif");
//ๆๅพ็่ฏปๅ่ฏปๅๅฐๅ
ๅญ็ๆต
ByteArrayOutputStream bos=new ByteArrayOutputStream();
//ๅๅพไฟๅญไฝ็ฝฎ
FileOutputStream fos=new FileOutputStream("E:\\test\\02\\t_01.gif");
byte buffer[]=new byte[1024];
int leng=0;
while((leng=is.read(buffer))!=-1){
fos.write(buffer, 0, leng);
bos.write(buffer, 0, leng);
}
is.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* ่ทๅGIFๅพ็ไธๅธงๅพ็ - ๅๆญฅๆง่ก
* @param src ๆบๅพ็่ทฏๅพ
* @param target ็ฎๆ ๅพ็่ทฏๅพ
* @param frame ่ทๅ็ฌฌๅ ๅธง
* @throws Exception
*/
public static void saveGif(InputStream is, String outfilePath) throws Exception {
try {
//ๆๅพ็่ฏปๅ่ฏปๅๅฐๅ
ๅญ็ๆต
ByteArrayOutputStream bos=new ByteArrayOutputStream();
//ๅๅพไฟๅญไฝ็ฝฎ
FileOutputStream fos=new FileOutputStream(outfilePath);
byte buffer[]=new byte[1024];
int leng=0;
while((leng=is.read(buffer))!=-1){
fos.write(buffer, 0, leng);
bos.write(buffer, 0, leng);
}
is.close();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
//InputStream
public static void main(String []ags) throws Exception{
String url = "http://od710rrnd.bkt.clouddn.com/biz/img/201805181519057276630.gif";
URL fileUrl = new URL(url);
URLConnection rulConnection = fileUrl.openConnection();// ๆญคๅค็urlConnectionๅฏน่ฑกๅฎ้
ไธๆฏๆ นๆฎURL็
HttpURLConnection httpUrlConnection = (HttpURLConnection) rulConnection;
InputStream inputStream = httpUrlConnection.getInputStream();
GIfUtil.saveGif(inputStream,"d:\\data\\11.gif");
}
}
<file_sep>/microservice-provider-dal/src/main/java/com/lj/cloud/secrity/dal/SecGroupsMapper.java
package com.lj.cloud.secrity.dal;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.annotations.Param;
import com.weixindev.micro.serv.common.bean.secrity.SecGroups;
public interface SecGroupsMapper {
int deleteByPrimaryKey(Integer id);
int insert(SecGroups record);
int insertSelective(SecGroups record);
SecGroups selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(SecGroups record);
int updateByPrimaryKey(SecGroups record);
/**
* ๆ นๆฎๆกไปถๆฅ่ฏขๅ่กจ
*
* @param example
*/
List<SecGroups> selectByExample(Object mapAndObject);
/**
* ๆ นๆฎๆกไปถๆฅ่ฏขๅ่กจ
*
* @param example
*/
List<Map<String,Object>> selectByPageExample(Object mapAndObject);
List<Map<String, Object>> selectGrouInfoByLogin(@Param("loginNo")String loginNo);
List<Map<String, Object>> selectByInfoKey(Integer id);
List<Map<String, Object>> selectByInfoKeyData();
void deleteByPrimaryGroupId(Integer id);
void insertURL(@Param("gid")Integer gid,@Param("ruiId") Integer ruiId);
List<Integer> selectGrouipId(Integer id);
}<file_sep>/microservice-provider-secrity/src/main/java/com/lj/cloud/secrity/WeixinSecrityApplication.java
package com.lj.cloud.secrity;
import java.io.IOException;
import java.util.HashMap;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.context.annotation.Bean;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import com.lj.cloud.secrity.service.SecAdminUserService;
import com.lj.cloud.secrity.util.JwtUtil;
import com.netflix.client.http.HttpRequest;
import com.weixindev.micro.serv.common.bean.RestAPIResult2;
import com.weixindev.micro.serv.common.bean.secrity.SecAdminUser;
import com.weixindev.micro.serv.common.util.Encrypt;
@SpringBootApplication
@EnableDiscoveryClient
@RestController
public class WeixinSecrityApplication {
@Autowired
SecAdminUserService secAdminUserService;
@GetMapping("/api/usloginaes")
public @ResponseBody Object usLoginaes() {
return "checkingrigth";
}
@GetMapping("/api/protected")
public @ResponseBody Object hellWorld() {
return "Hello World! This is a protected api";
}
@PostMapping("/login")
public Object login(HttpServletResponse response,HttpServletRequest request, @RequestBody final Account account) throws IOException {
RestAPIResult2 RestAPIResult2 = new RestAPIResult2();
if (isValidPassword(account)) {
String loginNo = account.username;
String jwt = JwtUtil.generateToken(account.username);
RestAPIResult2.setRespCode(1);
RestAPIResult2.setLoginNo(loginNo);
RestAPIResult2.setRespMsg("็ปๅฝๆๅ");
RestAPIResult2.setToken(jwt);
request.getSession().setAttribute("loginNo",loginNo);
return RestAPIResult2;
} else {
RestAPIResult2.setRespCode(0);
RestAPIResult2.setRespMsg("็ปๅฝๅคฑ่ดฅ");
return RestAPIResult2;
}
}
@Bean
public FilterRegistrationBean jwtFilter() {
final FilterRegistrationBean registrationBean = new FilterRegistrationBean();
JwtAuthenticationFilter filter = new JwtAuthenticationFilter();
registrationBean.setFilter(filter);
return registrationBean;
}
private boolean isValidPassword(Account ac) {
String enPwd = Encrypt.getEncrypt(ac.password, "<PASSWORD>");
SecAdminUser secAdminUser = secAdminUserService.login(ac.username,enPwd);
if(secAdminUser==null || (secAdminUser!=null &&secAdminUser.getId()==null)) {
return false;
}
return true;
}
public static class Account {
public String username;
public String password;
}
public static void main(String[] args) {
SpringApplication.run(WeixinSecrityApplication.class, args);
}
}
|
90bc3f409fdb627108ee17f28ce5d36285657080
|
[
"Java"
] | 3 |
Java
|
fengchaoWn/newDyCode
|
2c08b2d9594275cfb8f29f0ec3c259b346ae283a
|
4351bde4a448a6f612c5d711921019701b2583cb
|
refs/heads/master
|
<file_sep># elastic-ingest-test-action
Tests a set of testcases against an elasticsearch pipeline definition.
You will have to provide your own elasticsearch container by specifying a service in your workflow (see example).
## Limitations
Currently neither supports https, nor authentication. As we are normally running against service containers, this should not be a problem.
## Inputs
### `elastic_version`
The version tag of elasticsearch to use. See <https://hub.docker.com/_/elasticsearch> for available version. Defaults to `7.6.2`. Default may change (within the 7.x.x major version) without notice, so if you need this to be stable, specify your version explicitly.
### `elastic_host`
The hostname where elasticsearch can be reached. If using a service container this is the name of the service specified in your workflow file (also see example). Defaults to `elasticsearch`.
### `elastic_port`
The port where elasticsearch can be reached. Defaults to `9200`
### `pipelines`
**REQUIRED** A space separated list of files declaring elastic pipelines. The paths are relative to your repository and the pipelines in elasticsearch will be named according to the filename after removing path components and the .json suffix - `tests/my-pipeline.json` becomes `my-pipeline`.
### `testdir`
Directory containing the test definitions. All files in this folder are automatically tested against the specified pipeline inside the respective file.
## Outputs
### `testresults`
PASSED or FAILED, depending if the tests passed or failed. Will globally return "failed", if any single test fails. Will return "PIPEFAILED" if deploying pipelines (`--prepare`) failed.
## Example usage
This requires some kind of external elasticsearch. This example uses GitHub's service feature to set htis up. The env vars specify, that we will not be running a multinode cluster (`discovery.type=single-node`) and that we want to use regexes in ingest pipelines (`script.painless.regex.enabled: "true"`). You may have to adapt this to your needs.
Also note that if you give the service a specific name (`my-elastic`) you will have to pass that name as an input (`elastic_host`).
```yaml
jobs:
check_ingest:
runs-on: ubuntu-latest
name: Check Elasticsearch ingest pipelines
services:
my-elastic:
image: elasticsearch:7.5.2
ports:
- 9200:9200
env:
discovery.type: "single-node"
script.painless.regex.enabled: "true"
steps:
- uses: actions/checkout@v2
- name: Check elastic pipelines
id: check_ingest
uses: pdreker/elastic-ingest-test-action@v1
with:
elastic_host: my-elastic
testdir: 'examples'
```
<file_sep>FROM python:3-alpine
RUN apk add curl \
&& pip install requests ObjectPath
COPY elasticcheck.py /elasticcheck.py
COPY entrypoint.sh /entrypoint.sh
RUN chmod +x /entrypoint.sh
ENTRYPOINT ["/entrypoint.sh"]
<file_sep>import requests
import json
import argparse
import sys
import os
from objectpath import *
parser = argparse.ArgumentParser(description='Check Elasticsearch Pipelines against testcases')
parser.add_argument('--prepare', action='store_true', help='send specified pipelines to elasticsearch')
parser.add_argument('--debug', action='store_true', help='enable debugging output')
parser.add_argument('elasticurl', metavar='ELASTICURL', help='URL to elasticsearch server')
parser.add_argument('pipefile', metavar='FILE', help='URL to elasticsearch server')
cmdline = parser.parse_args()
with open(cmdline.pipefile, 'r') as f:
jsonInput = json.load(f)
if cmdline.prepare:
# input file should have been a pipeline -> send it to elasticsearch
pipeName, _ = os.path.splitext(os.path.basename(cmdline.pipefile))
pipelineDefinition = jsonInput
url = f'{cmdline.elasticurl}/_ingest/pipeline/{pipeName}'
r = requests.put(url, json=pipelineDefinition)
if r.status_code >= 200 and r.status_code < 300:
print(f'SUCCESS: {cmdline.pipefile} Creating pipeline {pipeName} returned {r.status_code} - {r.json()}')
sys.exit(0)
else:
print(f'FAILED: {cmdline.pipefile} Creating pipeline {pipeName} returned {r.status_code} - {r.json()}')
sys.exit(1)
else:
# run actual tests - json input must be a testcase
# We must have "pipeline", "assertions" and "input" in the file
pipeName = jsonInput["pipeline"]
assertions = jsonInput["assertions"]
testdoc = jsonInput["input"]
url = f'{cmdline.elasticurl}/_ingest/pipeline/{pipeName}/_simulate'
elasticinput = {}
elasticinput["docs"] = []
elasticinput["docs"].append(testdoc)
r = requests.post(url, json=elasticinput)
if r.status_code >= 200 and r.status_code < 300:
print(f'SUCCESS: {cmdline.pipefile} Simulating pipeline {pipeName} returned {r.status_code}')
else:
print(f'FAILED: {cmdline.pipefile} Simuating pipeline {pipeName} returned {r.status_code} - {r.json()}')
sys.exit(1)
if "doc" in r.json()["docs"][0]:
# We'll only pass in one doc, so we will only get one doc out
response = r.json()["docs"][0]["doc"]["_source"]
failed = False
elif "error" in r.json()["docs"][0]:
print(f'FAILED: Simulating pipeline returned error:')
print(f'FAILED: {r.json()}')
failed = True
else:
print(f'FAILED: Simulating pipline returned JSON document with neither a "doc" not an "error" key:')
print(f'FAILED: {r.json()}')
failed = True
if not failed:
if cmdline.debug:
print(f'DEBUG: {r.json()["docs"][0]}')
objtree = Tree(response)
for key in assertions:
# Check for existence of asserted key
val = objtree.execute(f'$.{key}')
if not val:
print(f'FAILED: {cmdline.pipefile} Asserted key "{key}" was not found in response.')
failed = True
else:
# check that key value exactly matches the assertion
if val != assertions[key]:
print(f'FAILED: {cmdline.pipefile} Content of asserted key "{key} does not match: Asserted: "{assertions[key]}", found: "{response[key]}"')
failed = True
else:
print(f'SUCCESS: {cmdline.pipefile} Assertion for key {key} matched.')
if failed:
sys.exit(1)
<file_sep>#!/bin/sh
# Wait 100s for elastic to come up
ELASTIC_LIVE=0
echo "WAITING for elasticsearch to become live"
for i in $(seq 1 10); do
curl -s http://$INPUT_ELASTIC_HOST:$INPUT_ELASTIC_PORT
if [ $? -eq 0 ]; then
echo "SUCCESS elasticsearch live"
ELASTIC_LIVE=1
break
else
echo "Elastic not ready yet."
sleep 10
fi
done
if [ $ELASTIC_LIVE -ne 1 ]; then
echo "FAILED: elasticsearch unreachable at $INPUT_ELASTIC_HOST:$INPUT_ELASTIC_PORT"
exit 1
fi
RESULT=0
echo "Deploying pipes from $GITHUB_WORKSPACE/$INPUT_TESTDIR"
for PIPE in $INPUT_PIPELINES; do
python3 /elasticcheck.py --prepare http://$INPUT_ELASTIC_HOST:$INPUT_ELASTIC_PORT $GITHUB_WORKSPACE/$PIPE
if [ $? -ne 0 ]; then
RESULT=1
fi
done
echo "Running tests from $GITHUB_WORKSPACE/$INPUT_TESTDIR"
for TEST in $GITHUB_WORKSPACE/$INPUT_TESTDIR/*.json; do
python3 /elasticcheck.py http://$INPUT_ELASTIC_HOST:$INPUT_ELASTIC_PORT $TEST
if [ $? -ne 0 ]; then
RESULT=2
fi
done
if [ $RESULT -eq 0 ]; then
echo ::set-output name=RESULT::SUCCESS
echo SUCCESS
elif [ $RESULT -eq 1 ]; then
echo ::set-output name=RESULT::PIPEFAILED
echo PIPEFAILED
exit 1
elif [ $RESULT -eq 2 ]; then
echo ::set-output name=RESULT::FAILED
echo FAILED
exit 2
fi
|
f8bb48dd04d410e3058b3143b1be042b5a82a3ef
|
[
"Markdown",
"Python",
"Dockerfile",
"Shell"
] | 4 |
Markdown
|
pdreker/elastic-ingest-test-action
|
2abf4214946e9461c7c914a7a504c194ade8d97d
|
ba43e5c1753e1a163ba478a1549b5a4df80b4faf
|
refs/heads/main
|
<file_sep>
// ่ฏฆๆ
้กต
$('.header_main').mouseover(function(){
$('.Navigation1_left').css('display','block');
})
$('.Navigation1_left').mouseout(function(){
$(this).css('display','none');
}).mousemove(function(){
$(this).css('display','block');
})
$('.header_main').mouseout(function(){
$('.Navigation1_left').css('display','none');
})
$('.Navigation1_left >ul >li').mouseover(function(){
$('.Navigation1_left >.pho_details').css('display','block');
})
$('.Navigation1_left >.pho_details').mouseout(function(){
$(this).css('display','none');
}).mousemove(function(){
$(this).css('display','block');
})
$('.Navigation1_left >ul >li').mouseout(function(){
$('.Navigation1_left >.pho_details').css('display','none');
})
// ๅๅๅพ็ๆพๅคง้
$(function(){
$('.details_sml >ul >li').mouseover(function(){
// $(this).index();
// console.log(ol);
// $(this).css('border','2px solid #E53E41');
$('.details_sml >ul >li').eq($(this).index()).css('border','2px solid #E53E41');
$('.details_sml >ul >li').eq($(this).index()).siblings().css('border','2px solid #fff');
$('.details_pic >img').eq($(this).index()).css('display','block');
$('.details_pic >img').eq($(this).index()).siblings().css('display','none');
$('.big_pic >img').eq($(this).index()).css('display','block');
$('.big_pic >img').eq($(this).index()).siblings().css('display','none');
})
$('.details_pic').mouseover(function() {
$('.big_pic').css('display', 'block');
}).mouseout(function() {
$('.big_pic').css('display', 'none');
}).mousemove(function(evn) {
// ๆฑ้ผ ๆ ็ธๅฏนๅพๅ็่ท็ฆป
var x = evn.clientX - $('.details_pic').position().left;
var y = evn.clientY - $('.details_pic').position().top;
// document.title = x + ':' + y;
// ๆฑๆฏไพ
// var blx = 1100 / 440;
var blx = $('.big_pic > img').width() / $('.details_pic > img').width() ;
// var bly = 1400 / 560;
var bly = $('.big_pic > img').height() / $('.details_pic > img').height() ;
// ่ฎฉๅคงๅพๅบ็ฐๅจไธญๅฟ็น
var resX = x * blx - ($('.details_pic > img').width() /2);
var resY = y * bly - ($('.details_pic > img').height() /2);
// ่ฎพ็ฝฎๆปๅจๆก็ไฝ็ฝฎ
$('.big_pic').scrollLeft(resX).scrollTop(resY);
});
});
// ๅๅไป็ปๆ
$(function(){
$(window).scroll(function(){
if($(this).scrollTop() >$('.main_w').offset().top){
$('#top_fix').css('display','block');
}else{
$('#top_fix').css('display','none');
}
})
})
// ๅณไพงๆปๅจๆ
$(function(){
var ji;
$('.ri_slide >ul >li').mouseover(function(){
ji =$(this).index();
move($('.ri_slide >ul >li >div').eq(ji),1254,ji);
$(this).children().eq(0).css('background','#C81623');
}).mouseout(function(){
move($('.ri_slide >ul >li >div').eq(ji),1324,ji);
$(this).children().eq(0).css('background','#7A6E6E');
})
var time=[0,1,2,3,4,5,6,7];
function move(obj,dis,ji){
console.log(obj);
clearInterval(time[ji]);
time[ji] = setInterval(function(){
var kl = obj.offset().left;
var speed = (dis-kl)/8;
if(speed>0){
speed = Math.ceil(speed);
}else{
speed = Math.floor(speed);
}
if(kl+speed == dis){
clearInterval(time[ji]);
}else{
obj.offset({left:kl+speed});
}
},30)
}
})<file_sep><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>ไบฌไธ่ฏฆๆ
้กต</title>
<link rel="stylesheet" href="./css/header.css">
<link rel="stylesheet" href="./css/detailspage.css">
<link rel="stylesheet" href="./css/footer.css">
<script src="./jquery/jquery.min.js"></script>
</head>
<body>
<!-- ๅณไพง่พน็บฟๆก -->
<div class="jdright"></div>
<!-- ๅณไพงๆปๅจๆ -->
<div class="ri_slide">
<ul>
<li>
<p><i></i></p>
<div>ไบฌไธไผๅ</div>
</li>
<li>
<p><i></i></p>
<div>ไบฌไธไผๅ</div>
</li>
<li>
<p><i></i></p>
<div>ไบฌไธไผๅ</div>
</li>
<li>
<p><i></i></p>
<div>ไบฌไธไผๅ</div>
</li>
<li>
<p><i></i></p>
<div>ไบฌไธไผๅ</div>
</li>
<li>
<p><i></i></p>
<div>ไบฌไธไผๅ</div>
</li>
<li>
<p><i></i></p>
<div>ไบฌไธไผๅ</div>
</li>
<li>
<p><i></i></p>
<div>ไบฌไธไผๅ</div>
</li>
</ul>
</div>
<!-- ๅณ่พนๅบ้จๆ -->
<div class="ri_t_nav">
</div>
<!-- ๅฟซๆทๆนๅผ -->
<div class="shortcut">
<span id="place">ๅไบฌ</span>
<ul class="ul_place">
<li>ๅไบฌ</li>
<li>ไธๆตท</li>
<li>ๅคฉๆดฅ</li>
<li>้้ๅบ</li>
<li>ๆฒณๅ</li>
<li>ๅฑฑ่ฅฟ</li>
<li>ๆฒณๅ</li>
<li>่พฝๅฎ</li>
<li>ๅๆ</li>
<li>้ป้พๆฑ</li>
<li>ๅ
่ๅค</li>
<li>ๆฑ่</li>
<li>ๅฑฑไธ</li>
<li>ๅฎๅพฝ</li>
<li>ๆตๆฑ</li>
<li>็ฆๅปบ</li>
<li>ๆนๅ</li>
<li>ๆนๅ</li>
<li>ๅนฟไธ</li>
<li>ๅนฟ่ฅฟ</li>
<li>ๆฑ่ฅฟ</li>
<li>ๅๅท</li>
<li>ๆตทๅ</li>
<li>่ดตๅท</li>
<li>ไบๅ</li>
<li>่ฅฟ่</li>
<li>้่ฅฟ</li>
<li>็่</li>
<li>้ๆตท</li>
<li>ๅฎๅค</li>
<li>ๆฐ็</li>
<li>ๆธฏๆพณ</li>
<li>ๅฐๆนพ</li>
<li>้้ฑผๅฒ</li>
<li>ๆตทๅค</li>
</ul>
<ul class="ul_shortcut">
<li>
<a href="javascript:;">ๆจๅฅฝ,่ฏท็ปๅฝ</a>
<a href="javascript:;">ๅ
่ดนๆณจๅ</a>
</li>
<li>|</li>
<li>ๆ็่ฎขๅ</li>
<li>|</li>
<li class="ul_shortcut_my">ๆ็ไบฌไธ</li>
<li>|</li>
<li>ไบฌไธไผๅ</li>
<li>|</li>
<li>ไผไธ้่ดญ</li>
<li>|</li>
<li class="pho_jd">ๆๆบไบฌไธ</li>
<li>|</li>
<li class="weixin">ๅ
ณๆณจไบฌไธ</li>
<li>|</li>
<li class="ul_shortcut_ser">ๅฎขๆทๆๅก</li>
<li>|</li>
<li class="ul_shortcut_web">็ฝ็ซๅฏผ่ช</li>
</ul>
<!-- ๆ็ไบฌไธ็้่้จๅ -->
<div class="ul_shortcut_my_m">
<ul>
<li>ๅพ
ๅค็่ฎขๅ</li>
<li>ๆถๆฏ</li>
<li>่ฟไฟฎ้ๆข่ดง</li>
<li>ๆ็้ฎ็ญ</li>
<li>้ไปทๅๅ</li>
<li>ๆ็ๅ
ณๆณจ</li>
</ul>
<ul>
<li>ๆ็ไบฌ่ฑ</li>
<li>ๆ็ไผๆ ๅธ</li>
<li>ๆ็็ฝๆก</li>
<li>ๆ็็่ดข</li>
</ul>
</div>
<!-- ๅฎขๆทๆๅก็้่้จๅ -->
<div class="ul_shortcut_ser_details">
<span>ๅฎขๆท</span>
<ul class="ul_shortcut_ser_details_1">
<li>ๅธฎๅฉไธญๅฟ</li>
<li>ๅฎๅๆๅก</li>
<li>ๅจ็บฟๅฎขๆ</li>
<li>ๆ่งๅปบ่ฎฎ</li>
<li>็ต่ฏๅฎขๆ</li>
<li>ๅฎขๆ้ฎ็ฎฑ</li>
<li>้่ๅจ่ฏข</li>
<li>ๅฎๅ
จ็ๅฎขๆ</li>
</ul>
<span>ๅๆท</span>
<ul class="ul_shortcut_ser_details_2">
<li>ๅไฝๆๅ</li>
<li>ไบฌไธๅๅญฆ้ข</li>
<li>ๅๅฎถๅๅฐ</li>
<li>ไบฌ้บฆๅทฅไฝๅฐ</li>
<li>ๅๅฎถๅธฎๅฉ</li>
<li>่งๅๅนณๅฐ</li>
</ul>
</div>
<!-- ็ฝ็ซๅฏผ่ช้่็ๅ
ๅฎน -->
<div class="ul_shortcut_web_details">
<ul class="ul_shortcut_web_details_theme">
<span>็น่ฒไธป้ข</span>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
<li>ไบฌไธไผๅ</li>
</ul>
<ul class="ul_shortcut_web_details_industry">
<span>่กไธ้ข้</span>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
<li>ๆๆบ</li>
</ul>
<ul class="ul_shortcut_web_details_service">
<span>็ๆดปๆๅก</span>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
<li>ไบฌไธๅฐๅฎถ</li>
</ul>
<ul class="ul_shortcut_web_details_more">
<span>ๆดๅค็ฒพ้</span>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
<li>ๆธธๆ็คพๅบ</li>
</ul>
</div>
<div class="pho_jd_details">
<div class="pho_jd_details_top">
<img src="./image/jd1.png" alt="">
<a href="javascript:;">ๆๆบไบฌไธ</a>
<p>ๆฐไบบไธไบซๅคง็คผๅ
</p>
<p>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</p>
</div>
<div class="pho_jd_details_top">
<img src="./image/jd2.jpg" alt="">
<a href="javascript:;">ๆๆบไบฌไธ</a>
<p>ๆฐไบบไธไบซๅคง็คผๅ
</p>
<p>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
<a href="javascript:;"></a>
</p>
</div>
<div class="pho_jd_details_top">
<img src="./image/jd3.jpg" alt="">
<a href="javascript:;">ๆๆบไบฌไธ</a>
<p>ๆฐไบบไธไบซๅคง็คผๅ
</p>
<p>
<a href="javascript:;">1</a>
<a href="javascript:;">2</a>
<a href="javascript:;">3</a>
</p>
</div>
</div>
</div>
<!-- ๅคด้จ -->
<div class="header">
<!-- ไบฌไธlogo -->
<div id="logo"><a href="javascript:;"></a></div>
<div class="search">
<input type="text">
<b></b>
<i></i>
</div>
<div class="car">
<i></i>
<a href="javascript:;">ๆ็่ดญ็ฉ่ฝฆ</a>
<b id="top-right">0</b>
<div id="car_details">
<i></i><span>่ดญ็ฉ่ฝฆไธญ่ฟๆฒกๆๅๅ๏ผ่ตถ็ดง้่ดญๅง๏ผ</span>
</div>
</div>
<!-- ๆ็ดขๆกไธๆน็็ญ่ฏ -->
<div class="hotwords">
<a href="javascript:;">ไบฌไธไนๅฎถ</a>
<a href="javascript:;">ไบฌไธไนๅฎถ</a>
<a href="javascript:;">ไบฌไธไนๅฎถ</a>
<a href="javascript:;">ไบฌไธไนๅฎถ</a>
</div>
<div class="nav">
<ul>
<li>็งๆ</li>
<li>็งๆ</li>
<li>็งๆ</li>
<li>็งๆ</li>
<li>็งๆ</li>
<li>็งๆ</li>
<li>็งๆ</li>
<li>็งๆ</li>
<li>็งๆ</li>
<li>็งๆ</li>
</ul>
</div>
<div class="header_main">
ๅ
จ้จๅๅๅ็ฑป<i></i>
</div>
<div class="main_more">
<div class="Navigation1">
<div class="Navigation1_left">
<ul>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
<li>
<a href="javascript:;">็ต่</a>
/
<a href="javascript:;">ๆๆบ</a>
</li>
</ul>
<!-- ๆๆบๆ -->
<div class="pho_details">
<div class="pho_nav">
<ul>
<li>ๆๆบ้ข้ ></li>
<li>ๆๆบ้ข้ ></li>
<li>ๆๆบ้ข้ ></li>
<li>ๆๆบ้ข้ ></li>
<li>ๆๆบ้ข้ ></li>
<li>ๆๆบ้ข้ ></li>
</ul>
</div>
<div class="pho_nav_one cbox">
<span>ๆๆบ้่ฎฏ ></span>
<ul>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
</ul>
</div>
<div class="pho_nav_two cbox">
<span>ๆๆบ้่ฎฏ ></span>
<ul>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
</ul>
</div>
<div class="pho_nav_three cbox">
<span>ๆๆบ้่ฎฏ ></span>
<ul>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
</ul>
</div>
<div class="pho_nav_four cbox">
<span>ๆๆบ้่ฎฏ ></span>
<ul>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
</ul>
</div>
<div class="pho_nav_five cbox">
<span>ๆๆบ้่ฎฏ ></span>
<ul>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
</ul>
</div>
<div class="pho_nav_six cbox">
<span>ๆๆบ้่ฎฏ ></span>
<ul>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
</ul>
</div>
<div class="pho_nav_seven cbox">
<span>ๆๆบ้่ฎฏ ></span>
<ul>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
<li>ๆๆบ็ปดไฟฎ</li>
</ul>
</div>
<div class="pho_pic">
<img src="./image/ap.jpg" alt="">
<img src="./image/op.jpg" alt="">
<img src="./image/ho.jpg" alt="">
<img src="./image/mi.jpg" alt="">
<img src="./image/ca.jpg" alt="">
<img src="./image/ji.png" alt="">
<img src="./image/ph.jpg" alt="">
<img src="./image/te.jpg" alt="">
<img id="pho_new" src="./image/new.jpg" alt="">
<img id="pho_cool" src="./image/cool.jpg" alt="">
</div>
</div>
</div>
<div class="more">
<div class="one1"></div>
</div>
</div>
</div>
</div>
<!-- ๅๅ่ฏฆๆ
-->
<div class="details">
<!-- ๅๅๆ ้ข -->
<div class="details_til">
<!-- ๆ ้ข็ๅทฆ่พน -->
<ul>
<li>ๆๆบ</li>
<li>></li>
<li>ๆๆบ้่ฎฏ</li>
<li>></li>
<li>ๆๆบ</li>
<li>></li>
<li>ๅไธบ</li>
<li>></li>
<li>ๅไธบ่ฃ่9</li>
</ul>
<!-- ๆ ้ข็ๅณ่พน -->
<div class="til_rig">
<ul>
<li><i>JD</i><i>่ช่ฅ</i>่ฃ่ๅฎๆนๆ่ฐๅบ</li>
<li><i></i>่็ณปไพๅบๅ</li>
<li><i></i>JIMI</li>
<li><i></i>ๅ
ณๆณจๅบ้บ</li>
</ul>
</div>
</div>
<!-- ๆ ้ขๅ
ๅฎน -->
<div class="details_mai">
<!-- ๆพๅคง็ๅพ็ -->
<div class="big_pic">
<img src="./image/big1.jpg" alt="">
<img src="./image/big2.jpg" alt="">
<img src="./image/big3.jpg" alt="">
<img src="./image/big4.jpg" alt="">
<img src="./image/big5.jpg" alt="">
</div>
<!-- ๆญฃๅธธ็ๅพ็ -->
<div class="details_pic">
<img src="./image/fd1.jpg" alt="">
<img src="./image/fd2.jpg" alt="">
<img src="./image/fd3.jpg" alt="">
<img src="./image/fd4.jpg" alt="">
<img src="./image/fd5.jpg" alt="">
</div>
<div class="details_sml">
<div id="sml_left"></div>
<ul>
<li><img src="./image/small1.jpg" alt=""></li>
<li><img src="./image/small2.jpg" alt=""></li>
<li><img src="./image/small3.jpg" alt=""></li>
<li><img src="./image/small4.jpg" alt=""></li>
<li><img src="./image/small5.jpg" alt=""></li>
</ul>
<div id="sml_right"></div>
</div>
<div class="details_wrap">
<div class="sku-name">
่ฃ่ V9 ๅ
จ็ฝ้ ้ซ้
็ 6GB+64GB ๅนปๅค้ป ็งปๅจ่้็ตไฟก4Gๆๆบๅๅกๅๅพ
</div>
<div class="item_hide">
ไธๅ็ซๅ100๏ผ้ขๅธๅๅ200๏ผๆไบคไปท2699๏ผ็บค่ๆบ่บซ๏ผ2Kๅฑ๏ผๅ้ๅคด๏ผๅผบๅฒ่ฏ็๏ผไฝ ๆณ่ฆ็ๅฟซ
</div>
<div class="item_hide_i">
้ๆฉใ็งปๅจไผๆ ่ดญใไธๆขๅท๏ผ่ดญๆฐๆบ๏ผ่ฟๅฏ้่ณๅค285ๅ
่ฏ่ดน๏ผ
</div>
<!-- ๆๆบไปทๆ ผ -->
<div class="pho_pirce">
<div class="pho_pirce_top">
ไบฌไธไปท
<span>๏ฟฅ</span>
<span>2990.00</span>
<a href="javascript:;">้ไปท้็ฅ</a>
</div>
<div class="pho_pirce_bot">
<span id="pho_pirce_bot_one">ไฟ้</span>
<span id="pho_pirce_bot_two">่ต ๅ</span>
<span id="pho_pirce_bot_three">ๆข่ดญ</span>
<span id="pho_pirce_bot_four">ๆปกๅ</span>
<i></i>
<p>x1</p>
<b>(่ต ๅฎๅณๆญข)</b>
</div>
</div>
<div class="summary-support">
ๅขๅผไธๅก
<a href="javascript:;"><i></i><span>ไปฅๆงๆขๆฐ๏ผ้ฒ็ฝฎๅๆถ</span></a>
<a href="javascript:;"><i></i><span>้ฒ็ฝฎๅๆถ</span></a>
<a href="javascript:;"><i></i><span>ไปฅๆงๆขๆฐ</span></a>
</div>
<div class="summary-stock">
<p>้
้ ่ณ</p>
<span>ไธๆตท<i></i></span>
<b>ๆฏๆ</b>
</div>
<div class="choose-attr-1 choose_box">
<span>้ๆฉ้ข่ฒ</span>
<ul>
<li>
<img src="./image/blue.jpg" alt="">
<a href="javascript:;">ๆๅ
่</a>
</li>
<li>
<img src="./image/gold.jpg" alt="">
<a href="javascript:;">้ๅ
้</a>
</li>
<li>
<img src="./image/black.jpg" alt="">
<a href="javascript:;">ๅนปๅค้ป</a>
</li>
<li>
<img src="./image/res.jpg" alt="">
<a href="javascript:;">้ญ
็ฐ็บข</a>
</li>
</ul>
</div>
<div class="choose-attr-2 choose_box">
<span>้ๆฉ็ๆฌ</span>
<ul>
<li>ๅ
จ็ฝ้(6GB 64GB)</li>
<li>ๅ
จ็ฝ้(6GB 64GB)</li>
<li>ๅ
จ็ฝ้(6GB 64GB)</li>
</ul>
</div>
<div class="choose-type choose_box">
<span>่ดญไนฐๆนๅผ</span>
<ul>
<li>ๅฎๆนๆ ้
</li>
<li>ๅฎๆนๆ ้
</li>
<li>ๅฎๆนๆ ้
</li>
<li>ๅฎๆนๆ ้
</li>
</ul>
</div>
<!-- ้ๆฉไนฐๅคๅฐๅฐ -->
<div class="buy-num">
<input id="buy_how" type="text" value="1">
<a href="javascript:;">-</a>
<a href="javascript:;">+</a>
</div>
<div class="add">ๅ ๅ
ฅ่ดญ็ฉ่ฝฆ</div>
<div class="buy">็ซๅณ่ดญไนฐ</div>
<div class="summary-tips">
<p>ๆธฉ้ฆจๆ็คบ</p>
<span>ยทๆฏๆ7ๅคฉๆ ็็ฑ้่ดง</span>
</div>
</div>
<!-- ๅบๅฎถๅ
ณๆณจ -->
<div class="left-btns">
<ul>
<li><i></i><span>ๅ
ณๆณจ</span></li>
<li><i></i><span>ๅไบซ</span></li>
<li><i></i><span>ๅฏนๆฏ</span></li>
</ul>
<a href="javascript:;">ไธพๆฅ</a>
</div>
</div>
</div>
<!-- ๅๅฎถๅๅ็ๅ
ทไฝไป็ปๅๅฎขๆท่ฏ่ฎบ -->
<div class="shop_all">
<!-- ๅทฆ่พน -->
<div class="aside">
<!-- ๅบๅฎถ -->
<div class="store">
<div class="store_top">
่ฃ่ๅฎๆนๆ่ฐๅบ
<i></i>
</div>
<div class="store_bot">
<ul>
<li>
<i></i>
<span>่ฟๅบ้้</span>
</li>
<li>
<i></i>
<span>ๅ
ณๆณจๅบ้บ</span>
</li>
</ul>
</div>
</div>
<!-- ๅ
ณไบ -->
<div class="about">
<div class="about_top">
ๅ
ณไบๆๆบ๏ผไฝ ๅฏ่ฝๅจๆพ
</div>
<div class="about_main">
<ul>
<li>ๅฎๅ๏ผAndroid๏ผ</li>
<li>5.6่ฑๅฏธๅไปฅไธ</li>
<li>ๆ็บน่ฏๅซ</li>
<li>ๅฟซ้ๅ
็ต</li>
<li>ๅฟซ้ๅ
็ต</li>
<li>ๅฟซ้ๅ
็ต</li>
<li>ๅฟซ้ๅ
็ต</li>
<li>ๅฟซ้ๅ
็ต</li>
<li>ๅฟซ้ๅ
็ต</li>
<li>็งปๅจ4G/่้4G/็ตไฟก4G</li>
<li>ๅฟซ้ๅ
็ต</li>
<li>ๅฟซ้ๅ
็ต</li>
</ul>
</div>
</div>
<!-- ่พพไบบๆ้ -->
<div class="choose">
<div class="choose_top">่พพไบบ้่ดญ</div>
<div class="choose_main">
<ul>
<li>
<img src="./image/choose1.jpg" alt="">
<p>่ฃ่ V9 ๅ
จ็ฝ้ ้ซ้
็ 6GB+64GB ๆๅ
่ ็งปๅจ่้็ตไฟก4Gๆๆบ ๅๅกๅๅพ
</p>
<b>๏ฟฅ2998.00</b>
</li>
<li>
<img src="./image/choose1.jpg" alt="">
<p>่ฃ่ V9 ๅ
จ็ฝ้ ้ซ้
็ 6GB+64GB ๆๅ
่ ็งปๅจ่้็ตไฟก4Gๆๆบ ๅๅกๅๅพ
</p>
<b>๏ฟฅ2998.00</b>
</li>
<li>
<img src="./image/choose1.jpg" alt="">
<p>่ฃ่ V9 ๅ
จ็ฝ้ ้ซ้
็ 6GB+64GB ๆๅ
่ ็งปๅจ่้็ตไฟก4Gๆๆบ ๅๅกๅๅพ
</p>
<b>๏ฟฅ2998.00</b>
</li>
<li>
<img src="./image/choose1.jpg" alt="">
<p>่ฃ่ V9 ๅ
จ็ฝ้ ้ซ้
็ 6GB+64GB ๆๅ
่ ็งปๅจ่้็ตไฟก4Gๆๆบ ๅๅกๅๅพ
</p>
<b>๏ฟฅ2998.00</b>
</li>
<li>
<img src="./image/choose1.jpg" alt="">
<p>่ฃ่ V9 ๅ
จ็ฝ้ ้ซ้
็ 6GB+64GB ๆๅ
่ ็งปๅจ่้็ตไฟก4Gๆๆบ ๅๅกๅๅพ
</p>
<b>๏ฟฅ2998.00</b>
</li>
<li>
<img src="./image/choose1.jpg" alt="">
<p>่ฃ่ V9 ๅ
จ็ฝ้ ้ซ้
็ 6GB+64GB ๆๅ
่ ็งปๅจ่้็ตไฟก4Gๆๆบ ๅๅกๅๅพ
</p>
<b>๏ฟฅ2998.00</b>
</li>
</ul>
</div>
</div>
<!-- ็ญ้ๆฆ -->
<div class="hot">
<div class="hot_top">
ๆๆบ็ญ้ๆฆ
</div>
<div class="hot_mid">
<ul>
<li>ๅไปทไฝ</li>
<li>ๅๅ็</li>
<li>ๆปๆ่ก</li>
</ul>
</div>
<div class="hot_main">
<ul>
<li>
<img src="./image/hot1.jpg" alt="">
<span>ๅไธบ่ฃ่9</span>
<b>๏ฟฅ2999.00</b>
</li>
<li>
<img src="./image/hot1.jpg" alt="">
<span>ๅไธบ่ฃ่9</span>
<b>๏ฟฅ2999.00</b>
</li>
<li>
<img src="./image/hot1.jpg" alt="">
<span>ๅไธบ่ฃ่9</span>
<b>๏ฟฅ2999.00</b>
</li>
<li>
<img src="./image/hot1.jpg" alt="">
<span>ๅไธบ่ฃ่9</span>
<b>๏ฟฅ2999.00</b>
</li>
<li>
<img src="./image/hot1.jpg" alt="">
<span>ๅไธบ่ฃ่9</span>
<b>๏ฟฅ2999.00</b>
</li>
<li>
<img src="./image/hot1.jpg" alt="">
<span>ๅไธบ่ฃ่9</span>
<b>๏ฟฅ2999.00</b>
</li>
<li>
<img src="./image/hot1.jpg" alt="">
<span>ๅไธบ่ฃ่9</span>
<b>๏ฟฅ2999.00</b>
</li>
</ul>
</div>
</div>
</div>
<!-- ๅณ่พน -->
<!-- ๅฝๆปๅจๅฐไธๅฎไฝ็ฝฎๆถๅๅๆ ๅบๅฎไธๅจ -->
<div class="shop_detail_top" id="top_fix">
<ul>
<li>ๅๅไป็ป</li>
<li>่งๆ ผไธๅ
่ฃ
</li>
<li>ๅฎๅไฟ้</li>
<li>ๅๅ่ฏไปท(20ไธ+)</li>
<li>ๆๆบ็คพๅบ</li>
<a href="javascript:;">ๅ ๅ
ฅ่ดญ็ฉ่ฝฆ</a>
</ul>
</div>
<div class="shop_detail">
<!-- ๅๅไป็ป -->
<div class="shop_detail_top">
<ul>
<li>ๅๅไป็ป</li>
<li>่งๆ ผไธๅ
่ฃ
</li>
<li>ๅฎๅไฟ้</li>
<li>ๅๅ่ฏไปท(20ไธ+)</li>
<li>ๆๆบ็คพๅบ</li>
<a href="javascript:;">ๅ ๅ
ฅ่ดญ็ฉ่ฝฆ</a>
</ul>
</div>
<!-- ๅพๆไป็ป -->
<div class="shop_detail_main">
<ul class="main_w">
<li>
<img src="./image/param1.png" alt="">
<p id="ipi">ๅ่พจ็๏ผ2560ร1440๏ผQuad HD/2K
</p>
</li>
<li>
<img src="./image/param2.png" alt="">
<p>ๅ็ฝฎๆๅๅคด๏ผๅ1200ไธๅ็ด </p>
<p>ๅ็ฝฎๆๅๅคด๏ผ800ไธๅ็ด </p>
</li>
<li>
<img src="./image/param3.png" alt="">
<p>ๆ ธ ๆฐ๏ผๅ
ซๆ ธ + ๅพฎๆบๆ ธi6</p>
<p>้ข ็๏ผ4 x CortexA53 1.8GHz + 4 x CortexA73 2.4GHz</p>
</li>
</ul>
<span>ๅ็๏ผ <a href="javascript:;">ๅไธบ(HUAWEI)</a></span>
<div class="shop_detail_main_m">
<ul>
<li>ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9</li>
<li>ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9</li>
<li>ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9</li>
<li>ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9</li>
</ul>
<ul>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
</ul>
<ul>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
</ul>
<ul>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
<li>
ๅๅๅ็งฐ๏ผๅไธบ่ฃ่V9
</li>
</ul>
</div>
</div>
<!-- ๅพ็ -->
<div class="main_pic">
<img src="image/pic1.jpg" alt="">
<img src="image/pic2.jpg" alt="">
<img src="image/pic3.jpg" alt="">
<img src="image/pic4.jpg" alt="">
<img src="image/pic5.jpg" alt="">
<img src="image/pic6.jpg" alt="">
<img src="image/pic7.jpg" alt="">
<img src="image/pic8.jpg" alt="">
<img src="image/pic9.jpg" alt="">
<img src="image/pic10.jpg" alt="">
<img src="image/pic11.jpg" alt="">
<img src="image/pic12.jpg" alt="">
<img src="image/pic13.jpg" alt="">
<img src="image/pic14.jpg" alt="">
</div>
<!-- ๅๅ่ฏไปท -->
<div class="shop_detail_comment">
<div class="comment_top">
ๅๅ่ฏไปท
</div>
<div class="comment_mid">
<div class="comment_sc">
<b>ๅฅฝ่ฏๅบฆ</b>
<span>96%</span>
</div>
<ul>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
<li>ๅฐฑๆฏๅฟซ(2655)</li>
</ul>
</div>
<!-- ๅ
จ้จ่ฏไปท -->
<div class="all_com_top">
<ul>
<li>ๅ
จ้จ่ฏไปท(20ไธ)</li>
<li>ๆๅพ(10000)</li>
<li>ๆๅพ(10000)</li>
<li>ๆๅพ(10000)</li>
<li>ๆๅพ(10000)</li>
<li>ๆๅพ(10000)</li>
<li><input type="checkbox">ๅช็ๅฝๅๅๅ่ฏไปท</li>
</ul>
<div class="all_com_rig">
<span>ๆจ่ๆๅบ</span>
<i></i>
</div>
</div>
<!-- ็จๆท็่ฏไปท -->
<div class="all_com_main">
<div class="cor_name">
<span>
<i></i>
j***ไผ
</span>
<span>็ ็ณไผๅ</span>
</div>
<div class="cor_wri">
<div class="cor_love"></div>
<div class="cor_write">
่ถ
็บงๅๆฌข๏ผๅฅฝ้
ท็ๆๆบ๏ผๆๆๅพๅฅฝ๏ผๅฟซ้็ปๅ๏ผๅ
ถไปๅ่ฝ่ฟๅจ็ ็ฉถ๏ผๅซๅฟไบ้่ชๆๆๅฆ๏ผๅๅ
</div>
<ul class="cor_pic">
<li>
<img src="./image/corw1.jpg" alt="">
</li>
<li>
<img src="./image/corw2.jpg" alt="">
</li>
<li>
<img src="./image/corw3.jpg" alt="">
</li>
<li>
<img src="./image/corw4.jpg" alt="">
</li>
</ul>
<ul class="cor_buy">
<li>้ๅ
้</li>
<li>ๅ
จ็ฝ้๏ผ6GB 64GB๏ผ</li>
<li>ๅฎๆนๆ ้
</li>
<li>2017-02-28 17:12</li>
</ul>
<ul class="other">
<li>ไธพๆฅ</li>
<li><i></i>2263</li>
<li><i></i>1580</li>
</ul>
</div>
<!-- ๅๅค -->
<div class="reto">
<dl class="recomment">
<dt>ๅไธบ็ป็ซฏๆๅก_ๆฝๆฃฎ ๅๅค๏ผ</dt>
<dd>ๆจๅฅฝ๏ผๆ่ฐขๆจ้ๆฉๆไปฌๅบ้บ็ๅฎ่ดใๅจ็ฉๆตๆน้ข๏ผๆไปฌไธบ่ฑ็ฒไปฌ้ๆฉๆๅฟซๆไผ่ดจ็็ฉๆต๏ผ่ฎฉๆจ็ฌฌไธๆถ้ดๆฟๅฐๆฌฃๅ็็ฑๆบๅไนไธ็จ็ญๅพ
ใ่ฃ่V9็ฒพๅทง็ๅทฅ่บๆถๆๅธฆๆฅๆๆบ็็บค่๏ผ้ๅฑ็ๅ็ง้
่ฒๆดๆพๆถๅฐใๅผบๅฒ็้
็ฝฎๆฟ่ฝฝไบไบบๅทฅๆบ่ฝ็ฎๆณไผๅ็EMUI 5.0ๆไฝ็ณป็ป๏ผๆดๆบ่ฟ่กๆดๅฟซ้๏ผๆๆใ็่ง้ขใ็ฉๆธธๆ็ญ้ฝๆด็
ๅฟซใๅผๅพๆจๆฅๆ๏ผๅฆๅค๏ผ่ต ๅไผ้ๆจ็ๅๅไธ่ตท้
้็ปๆจ๏ผ่ฏทๆจไป็ปๆ ธๅฏนๆถๅฐ็ๅๅไธ่ดญ็ฉๆธ
ๅๆฏๅฆไธ่ด๏ผ่ฅไธไธ่ด๏ผ่ฏทๆจๅๆถ่็ณปไบฌไธๅฎขๆใๅ็ปญ่ฅ่ฟๆ็้ฎ๏ผ้ๆถๅๆฅๅจ่ฏขๆไปฌๅฆใ</dd>
</dl>
<div class="retim">
2017.03.04
</div>
</div>
</div>
<div class="all_com_main">
<div class="cor_name">
<span>
<i></i>
j***ไผ
</span>
<span>็ ็ณไผๅ</span>
</div>
<div class="cor_wri">
<div class="cor_love"></div>
<div class="cor_write">
่ถ
็บงๅๆฌข๏ผๅฅฝ้
ท็ๆๆบ๏ผๆๆๅพๅฅฝ๏ผๅฟซ้็ปๅ๏ผๅ
ถไปๅ่ฝ่ฟๅจ็ ็ฉถ๏ผๅซๅฟไบ้่ชๆๆๅฆ๏ผๅๅ
</div>
<ul class="cor_pic">
<li>
<img src="./image/corw1.jpg" alt="">
</li>
<li>
<img src="./image/corw2.jpg" alt="">
</li>
<li>
<img src="./image/corw3.jpg" alt="">
</li>
<li>
<img src="./image/corw4.jpg" alt="">
</li>
</ul>
<ul class="cor_buy">
<li>้ๅ
้</li>
<li>ๅ
จ็ฝ้๏ผ6GB 64GB๏ผ</li>
<li>ๅฎๆนๆ ้
</li>
<li>2017-02-28 17:12</li>
</ul>
<ul class="other">
<li>ไธพๆฅ</li>
<li><i></i>2263</li>
<li><i></i>1580</li>
</ul>
</div>
<!-- ๅๅค -->
<div class="reto">
<dl class="recomment">
<dt>ๅไธบ็ป็ซฏๆๅก_ๆฝๆฃฎ ๅๅค๏ผ</dt>
<dd>ๆจๅฅฝ๏ผๆ่ฐขๆจ้ๆฉๆไปฌๅบ้บ็ๅฎ่ดใๅจ็ฉๆตๆน้ข๏ผๆไปฌไธบ่ฑ็ฒไปฌ้ๆฉๆๅฟซๆไผ่ดจ็็ฉๆต๏ผ่ฎฉๆจ็ฌฌไธๆถ้ดๆฟๅฐๆฌฃๅ็็ฑๆบๅไนไธ็จ็ญๅพ
ใ่ฃ่V9็ฒพๅทง็ๅทฅ่บๆถๆๅธฆๆฅๆๆบ็็บค่๏ผ้ๅฑ็ๅ็ง้
่ฒๆดๆพๆถๅฐใๅผบๅฒ็้
็ฝฎๆฟ่ฝฝไบไบบๅทฅๆบ่ฝ็ฎๆณไผๅ็EMUI 5.0ๆไฝ็ณป็ป๏ผๆดๆบ่ฟ่กๆดๅฟซ้๏ผๆๆใ็่ง้ขใ็ฉๆธธๆ็ญ้ฝๆด็
ๅฟซใๅผๅพๆจๆฅๆ๏ผๅฆๅค๏ผ่ต ๅไผ้ๆจ็ๅๅไธ่ตท้
้็ปๆจ๏ผ่ฏทๆจไป็ปๆ ธๅฏนๆถๅฐ็ๅๅไธ่ดญ็ฉๆธ
ๅๆฏๅฆไธ่ด๏ผ่ฅไธไธ่ด๏ผ่ฏทๆจๅๆถ่็ณปไบฌไธๅฎขๆใๅ็ปญ่ฅ่ฟๆ็้ฎ๏ผ้ๆถๅๆฅๅจ่ฏขๆไปฌๅฆใ</dd>
</dl>
<div class="retim">
2017.03.04
</div>
</div>
</div>
<div class="all_com_main">
<div class="cor_name">
<span>
<i></i>
j***ไผ
</span>
<span>็ ็ณไผๅ</span>
</div>
<div class="cor_wri">
<div class="cor_love"></div>
<div class="cor_write">
่ถ
็บงๅๆฌข๏ผๅฅฝ้
ท็ๆๆบ๏ผๆๆๅพๅฅฝ๏ผๅฟซ้็ปๅ๏ผๅ
ถไปๅ่ฝ่ฟๅจ็ ็ฉถ๏ผๅซๅฟไบ้่ชๆๆๅฆ๏ผๅๅ
</div>
<ul class="cor_pic">
<li>
<img src="./image/corw1.jpg" alt="">
</li>
<li>
<img src="./image/corw2.jpg" alt="">
</li>
<li>
<img src="./image/corw3.jpg" alt="">
</li>
<li>
<img src="./image/corw4.jpg" alt="">
</li>
</ul>
<ul class="cor_buy">
<li>้ๅ
้</li>
<li>ๅ
จ็ฝ้๏ผ6GB 64GB๏ผ</li>
<li>ๅฎๆนๆ ้
</li>
<li>2017-02-28 17:12</li>
</ul>
<ul class="other">
<li>ไธพๆฅ</li>
<li><i></i>2263</li>
<li><i></i>1580</li>
</ul>
</div>
<!-- ๅๅค -->
<div class="reto">
<dl class="recomment">
<dt>ๅไธบ็ป็ซฏๆๅก_ๆฝๆฃฎ ๅๅค๏ผ</dt>
<dd>ๆจๅฅฝ๏ผๆ่ฐขๆจ้ๆฉๆไปฌๅบ้บ็ๅฎ่ดใๅจ็ฉๆตๆน้ข๏ผๆไปฌไธบ่ฑ็ฒไปฌ้ๆฉๆๅฟซๆไผ่ดจ็็ฉๆต๏ผ่ฎฉๆจ็ฌฌไธๆถ้ดๆฟๅฐๆฌฃๅ็็ฑๆบๅไนไธ็จ็ญๅพ
ใ่ฃ่V9็ฒพๅทง็ๅทฅ่บๆถๆๅธฆๆฅๆๆบ็็บค่๏ผ้ๅฑ็ๅ็ง้
่ฒๆดๆพๆถๅฐใๅผบๅฒ็้
็ฝฎๆฟ่ฝฝไบไบบๅทฅๆบ่ฝ็ฎๆณไผๅ็EMUI 5.0ๆไฝ็ณป็ป๏ผๆดๆบ่ฟ่กๆดๅฟซ้๏ผๆๆใ็่ง้ขใ็ฉๆธธๆ็ญ้ฝๆด็
ๅฟซใๅผๅพๆจๆฅๆ๏ผๅฆๅค๏ผ่ต ๅไผ้ๆจ็ๅๅไธ่ตท้
้็ปๆจ๏ผ่ฏทๆจไป็ปๆ ธๅฏนๆถๅฐ็ๅๅไธ่ดญ็ฉๆธ
ๅๆฏๅฆไธ่ด๏ผ่ฅไธไธ่ด๏ผ่ฏทๆจๅๆถ่็ณปไบฌไธๅฎขๆใๅ็ปญ่ฅ่ฟๆ็้ฎ๏ผ้ๆถๅๆฅๅจ่ฏขๆไปฌๅฆใ</dd>
</dl>
<div class="retim">
2017.03.04
</div>
</div>
</div>
<div class="all_com_main">
<div class="cor_name">
<span>
<i></i>
j***ไผ
</span>
<span>็ ็ณไผๅ</span>
</div>
<div class="cor_wri">
<div class="cor_love"></div>
<div class="cor_write">
่ถ
็บงๅๆฌข๏ผๅฅฝ้
ท็ๆๆบ๏ผๆๆๅพๅฅฝ๏ผๅฟซ้็ปๅ๏ผๅ
ถไปๅ่ฝ่ฟๅจ็ ็ฉถ๏ผๅซๅฟไบ้่ชๆๆๅฆ๏ผๅๅ
</div>
<ul class="cor_pic">
<li>
<img src="./image/corw1.jpg" alt="">
</li>
<li>
<img src="./image/corw2.jpg" alt="">
</li>
<li>
<img src="./image/corw3.jpg" alt="">
</li>
<li>
<img src="./image/corw4.jpg" alt="">
</li>
</ul>
<ul class="cor_buy">
<li>้ๅ
้</li>
<li>ๅ
จ็ฝ้๏ผ6GB 64GB๏ผ</li>
<li>ๅฎๆนๆ ้
</li>
<li>2017-02-28 17:12</li>
</ul>
<ul class="other">
<li>ไธพๆฅ</li>
<li><i></i>2263</li>
<li><i></i>1580</li>
</ul>
</div>
<!-- ๅๅค -->
<div class="reto">
<dl class="recomment">
<dt>ๅไธบ็ป็ซฏๆๅก_ๆฝๆฃฎ ๅๅค๏ผ</dt>
<dd>ๆจๅฅฝ๏ผๆ่ฐขๆจ้ๆฉๆไปฌๅบ้บ็ๅฎ่ดใๅจ็ฉๆตๆน้ข๏ผๆไปฌไธบ่ฑ็ฒไปฌ้ๆฉๆๅฟซๆไผ่ดจ็็ฉๆต๏ผ่ฎฉๆจ็ฌฌไธๆถ้ดๆฟๅฐๆฌฃๅ็็ฑๆบๅไนไธ็จ็ญๅพ
ใ่ฃ่V9็ฒพๅทง็ๅทฅ่บๆถๆๅธฆๆฅๆๆบ็็บค่๏ผ้ๅฑ็ๅ็ง้
่ฒๆดๆพๆถๅฐใๅผบๅฒ็้
็ฝฎๆฟ่ฝฝไบไบบๅทฅๆบ่ฝ็ฎๆณไผๅ็EMUI 5.0ๆไฝ็ณป็ป๏ผๆดๆบ่ฟ่กๆดๅฟซ้๏ผๆๆใ็่ง้ขใ็ฉๆธธๆ็ญ้ฝๆด็
ๅฟซใๅผๅพๆจๆฅๆ๏ผๅฆๅค๏ผ่ต ๅไผ้ๆจ็ๅๅไธ่ตท้
้็ปๆจ๏ผ่ฏทๆจไป็ปๆ ธๅฏนๆถๅฐ็ๅๅไธ่ดญ็ฉๆธ
ๅๆฏๅฆไธ่ด๏ผ่ฅไธไธ่ด๏ผ่ฏทๆจๅๆถ่็ณปไบฌไธๅฎขๆใๅ็ปญ่ฅ่ฟๆ็้ฎ๏ผ้ๆถๅๆฅๅจ่ฏขๆไปฌๅฆใ</dd>
</dl>
<div class="retim">
2017.03.04
</div>
</div>
</div>
</div>
</div>
</div>
<!-- ้กต่ -->
<div class="footer">
<div class="footer_top">
<ul>
<li><i></i><p>ๅ็ฑป้ฝๅ
จ๏ผ่ฝปๆพ่ดญ็ฉ</p></li>
<li><i></i><p>ๅ็ฑป้ฝๅ
จ๏ผ่ฝปๆพ่ดญ็ฉ</p></li>
<li><i></i><p>ๅ็ฑป้ฝๅ
จ๏ผ่ฝปๆพ่ดญ็ฉ</p></li>
<li><i></i><p>ๅ็ฑป้ฝๅ
จ๏ผ่ฝปๆพ่ดญ็ฉ</p></li>
</ul>
</div>
<div class="footer_main">
<div class="shop footer_box">
<h5>่ดญ็ฉๆๅ</h5>
<ul>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
</ul>
</div>
<div class="send footer_box">
<h5>่ดญ็ฉๆๅ</h5>
<ul>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
</ul>
</div>
<div class="pay footer_box">
<h5>่ดญ็ฉๆๅ</h5>
<ul>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
</ul>
</div>
<div class="service footer_box">
<h5>่ดญ็ฉๆๅ</h5>
<ul>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
</ul>
</div>
<div class="advantage footer_box">
<h5>่ดญ็ฉๆๅ</h5>
<ul>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
<li>่ดญ็ฉๆต็จ</li>
</ul></div>
<div class="Range">
<h5>ไบฌไธ่ช่ฅ่ฆ็ๅบๅฟ</h5>
<p>ไบฌไธๅทฒๅๅ
จๅฝ2661ไธชๅบๅฟๆไพ่ช่ฅ้
้ๆๅก๏ผๆฏๆ่ดงๅฐไปๆฌพใPOSๆบๅทๅกๅๅฎๅไธ้จๆๅกใ</p>
<p><a href="javascript:;">ๆฅ็่ฏฆๆ
</a></p>
</div>
</div>
<div class="footer_bot">
<p>
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>|
<a href="javascript:;">่็ณปๆไปฌ</a>
</p>
<p>
<a href="javascript:;">ไบฌๅ
ฌ็ฝๅฎๅค 11000002000088ๅท</a>|
<a href="javascript:;">ไบฌICP่ฏ070359ๅท</a>|
<a href="javascript:;">ไบ่็ฝ่ฏๅไฟกๆฏๆๅก่ตๆ ผ่ฏ็ผๅท(ไบฌ)-็ป่ฅๆง-2014-0008</a>|
<a href="javascript:;">ๆฐๅบๅไบฌ้ถ ๅญ็ฌฌๅคง120007ๅท</a>
</p>
<p>
<a href="javascript:;">ไบ่็ฝๅบ็่ฎธๅฏ่ฏ็ผๅทๆฐๅบ็ฝ่ฏ(ไบฌ)ๅญ150ๅท</a>|
<a href="javascript:;">ๅบ็็ฉ็ป่ฅ่ฎธๅฏ่ฏ</a>|
<a href="javascript:;">็ฝ็ปๆๅ็ป่ฅ่ฎธๅฏ่ฏไบฌ็ฝๆ[2014]2148-348ๅท</a>|
<a href="javascript:;">่ฟๆณๅไธ่ฏไฟกๆฏไธพๆฅ็ต่ฏ๏ผ4006561155</a>
</p>
<p>
<a href="javascript:;">Copyright ยฉ 2004 - 2017 ไบฌไธJD.com ็ๆๆๆ</a>|
<a href="javascript:;">ๆถ่ดน่
็ปดๆ็ญ็บฟ๏ผ4006067733็ป่ฅ่ฏ็
ง</a>
</p>
<p>
<a href="javascript:;">ไบฌไธๆไธ็ฝ็ซ๏ผไบฌไธๆฏไป</a>|
<a href="javascript:;">ไบฌไธไบ</a>
</p>
</div>
<div class="footer_bot_pic">
<ul>
<li>
<img src="./image/25.png" alt="">
<a href="javascript:;">ๆทฑๅณ็ฝ็ป่ญฆๅฏๆฅ่ญฆๅนณๅฐ</a>
</li>
<li>
<img src="./image/26.png" alt="">
<a href="javascript:;">ๅ
ฌๅ
ฑไฟกๆฏๅฎๅ
จ็ฝ็ป็ๅฏ</a>
</li>
<li>
<img src="./image/27.png" alt="">
<a href="javascript:;">ไธ่ฏไฟกๆฏไธพๆฅไธญๅฟ</a>
</li>
<li>
<img src="" alt="">
<a href="javascript:;">ไธ่ฏไฟกๆฏไธพๆฅไธญๅฟ</a>
</li>
<li>
<img src="./image/28.png" alt="">
<a href="javascript:;">ไธ่ฏไฟกๆฏไธพๆฅไธญๅฟ</a>
</li>
<li>
<img src="./image/29.png" alt="">
<a href="javascript:;">ไธ่ฏไฟกๆฏไธพๆฅไธญๅฟ</a>
</li>
</ul>
</div>
</div>
</body>
<script src="./js/detailspage.js"></script>
</html><file_sep> // $('#sign_one').css('display','none')
// ่ฆๆน.register_sign็้ซๅบฆ
/*ๅฏ็ ็ป้็ๆ
ๅตไธๆฏ330px*/
/*height:330px;*/
/*ๆซ็ ็ป้็ๆ
ๅตไธๆฏ361px*/
// ๅฏ็ ็ป้ไธบ.sign_pwd
// ไบ็ปด็ ็ป้ไธบ.sign_QR
$('.sign_left').click(function(){
$('.sign_QR').css('display','block');
$('.sign_pwd').css('display','none');
$('.register_sign').css('height','361px');
$('.sign_left').css('color','red')
$('.sign_right').css('color','black')
});
$('.sign_right').click(function(){
$('.sign_QR').css('display','none');
$('.sign_pwd').css('display','block');
$('.register_sign').css('height','330px');
$('.sign_left').css('color','black')
$('.sign_right').css('color','red')
});
$('#QR >img').eq(0).mouseover(function(){
$(this).animate({
'left': 45,
}, 200);
$('#QR >img').eq(1).fadeIn(200);
}).mouseout(function(){
$(this).animate({
'left': 95,
}, 200);
$('#QR >img').eq(1).fadeOut(200);
})
<file_sep> // ๅไบฌ
$(function(){
// console.log($('#place').html());
for(var i=0;i<35;i++){
if($('#place').html() == $('.ul_place >li').eq(i).html()){
$('.ul_place >li').eq(i).css('background','#f00')
}else{
$('.ul_place >li').eq(i).css('background','#fff')
}
}
$('.ul_place >li').click(function(){
console.log($(this).index());
var hei = $('.ul_place >li').eq($(this).index()).html()
$('#place').html(hei);
for(var i=0;i<35;i++){
if($('#place').html() == $('.ul_place >li').eq(i).html()){
$('.ul_place >li').eq(i).css('background','#f00')
}else{
$('.ul_place >li').eq(i).css('background','#fff')
}
}
})
})
// jq1ไธบๅพ็ jq2ไธบๆ้ฎ cli1ไธบๅๅทฆๆ้ฎ๏ผcli2ไธบๅๅณ ,col1ไธบๆ้ฎๅๆฅ็้ข่ฒ,col2ไธบๆ้ฎๅๆข็้ข่ฒ๏ผtime ไธบๅฎๆถๅจ็ๆถ้ด
// ไธ็ฅ้ไปไนๅๅ ๆ ๆณๆพๅฐ$(function(){})้้ข
lunbo($('.live_pic >img'),$('#liveli >ul >li'),$('#livele'),$('#liveri'),'#FFFFFF','#FD3131',2000);
function lunbo(jq1,jq2,cli1,cli2,col1,col2,time){
jq1.timer =null;
var showIndex = 0;
jq1.ele = 0;
jq1.eq(showIndex).css('display', 'block');
jq2.eq(showIndex).css('background',col2);
// console.log(jq2.eq(showIndex));
// console.log(jq2.index());
// ้ผ ๆ ็งปๅ
ฅๆ้ฎๅฎๆถๅจๅๆญข ็งปๅบๆถๅๆฌกๅฏๅจ
jq2.mouseover(function(){
clearInterval(jq1.timer);
jq1.ele = $(this).index();
jq1.eq(jq1.ele).fadeIn(200);
jq2.eq(jq1.ele).css('background',col2);
jq2.eq(jq1.ele).siblings().css('background',col1);
jq1.eq(jq1.ele).siblings().fadeOut(200);
}).mouseout(function(){
play();
});
// ็นๅปๅๅทฆๅๅณๆ้ฎไฝฟๅพๅพ็ๅๆข๏ผๅฆๆไธ็นๅปๅฐฑ่ชๅจๅๆข๏ผ็นๅปไธไธๅๅฆๆ
// ไธๅจ็นๅปไบไนไธๆ ท๏ผ่ชๅจ่ฝฎๆญใ
// ๅฏน่ฟไธคไธชๆ้ฎ่ฟ่กไบ็ดๆฅ็ๅฐ่ฃ
function cli(obj,num1,num2,num3){
obj.click(function(){
clearInterval(jq1.timer);
jq2.eq(jq1.ele).css('background',col1);
jq1.eq(jq1.ele).fadeOut(200);
if(num1>0){
jq1.ele = jq1.ele + (num1);
if(jq1.ele > num2){
jq1.ele = num3;
}
}else{
jq1.ele = jq1.ele + (num1);
if(jq1.ele < num2){
jq1.ele = num3;
}
}
jq1.eq(jq1.ele).fadeIn(200);
jq2.eq(jq1.ele).css('background',col2);
// ็นๅปๅ็ซๅณๅฏๅจๅฎๆถๅจ
setTimeout(function(){
play();
},0);
});
}
cli(cli1,-1,0,jq2.index());
cli(cli2,1,jq2.index(),0);
// ็จๅฝๆฐๆๅฎๆถๅจๅฐ่ฃ
ไธไธ
function play(){
jq1.timer = setInterval(function(){
jq1.eq(jq1.ele).fadeOut(200);
jq2.eq(jq1.ele).css('background',col1);
// ไธไธๅผ
jq1.ele++;
// ไธไธๅผ ๆพ็คบๅพ๏ผไธๆ ไธบ 1
jq1.ele > jq2.index() && (jq1.ele = 0);
// ๆทกๅ
ฅ
jq1.eq(jq1.ele).fadeIn(200);
jq2.eq(jq1.ele).css('background',col2);
// console.log(ele);
},time);
}
play();
}
// ๅฉ็จjsๅฐ่ฃ
ไบไธไธช้ผ ๆ ็งปๅ
ฅ็งปๅบไบไปถๅฝๆฐ๏ผๅๆถๅ ไธ็น็น็ๆๆ
// co1,co2 ๅฐฑๆฏไฝ ่ชๅทฑๅๆฅ็้ข่ฒ๏ผ็จไบ็งปๅบๅๆขๅค๏ผๆ้ป่ฎค้ข่ฒ๏ผ
// cg1,cg2,ๅฐฑๆฏไฝ ่ฆๆนๅ็้ข่ฒใ๏ผๆ้ป่ฎค้ข่ฒ๏ผ
function hov(obj1,obj2,co1='#E3E4E5',co2='#E3E4E5',cg1='#fff',cg2='#ccc'){
obj1.mouseover(function(){
obj2.css('display','block');
obj1.css({'background':cg1,'border':'1px solid '+cg2,'border-bottom':'0'});
});
obj2.mouseout(function(){
obj2.css('display','none');
obj1.css({'background':co1,'border':'1px solid '+co2});
}).mousemove(function(){
obj2.css('display','block');
obj1.css({'background':cg1,'border':'1px solid '+cg2});
});
obj1.mouseout(function(){
obj2.css('display','none');
obj1.css({'background':co1,'border':'1px solid '+co2});
});
}
hov($('#place'),$('.ul_place'));
// ๆ ้ข็ๆ็ไบฌไธ
hov($('.ul_shortcut_my'),$('.ul_shortcut_my_m'));
// ๆ ้ข็ๅฎขๆทๆๅก
hov($('.ul_shortcut_ser'),$('.ul_shortcut_ser_details'));
// ๆ ้ข็็ฝ็ซๅฏผ่ช
hov($('.ul_shortcut_web'),$('.ul_shortcut_web_details'));
// ๆ ้ข็ๆๆบไบฌไธ
hov($('.pho_jd'),$('.pho_jd_details'));
// ๆ็่ดญ็ฉ่ฝฆ
hov($('.car'),$('#car_details'),'#fff');
// ไพง่พนๅฏผ่ชๆ ๆทกๅ
ฅๆทกๅบ
$('.Navigation_left >ul >li').mouseover(function(){
$('.pho_details').show();
}).mouseover(function(){
$('.pho_details').show();
});
$('.pho_details').mouseout(function(){
$('.pho_details').css('display','none');
}).mousemove(function(){
$('.pho_details').css('display','block');
});
$('.Navigation_left >ul >li').mouseout(function(){
$('.pho_details').hide();
});
// ่ฝฎๆญๅพ
lunbo($('#Navigation_mid_au_pic >li'),$('.img_index >li'),$('#turn_left'),$('#turn_right'),'#fff','red',4000);
// ็งๆ็ๆถ้
$(function(){
// ๆฃๆตๆถ้ด็ๅ็งๆฏๅฆๅฐไบ10
function checkNum(num){
if(num<10){
num = '0'+num;
}
return num;
}
setInterval(function(){
var newda = new Date(2018,10,1,00,00,00);
var oldda = new Date();
var diff = parseInt((newda.getTime() - oldda.getTime())/1000);
var h = parseInt((diff/3600)%24);
h = checkNum(h);
var m = parseInt((diff/60)%60);
m = checkNum(m);
var s = parseInt(diff%60);
s = checkNum(s);
$('#timer_hou').html(h);
$('#timer_min').html(m);
$('#timer_sec').html(s);
// console.log(h,m,s);
},1000)
});
// ็บข็บฟ็งปๅจ
$('.Sale_more >a').eq(1).mouseover(function(){
$('#lines').animate({
'left':50
},100);
$('#Sale_details2').animate({
'left':0
},100);
$('#Sale_details1').animate({
'left':-180
},100)
});
$('.Sale_more >a').eq(0).mouseover(function(){
$('#lines').animate({
'left':10
},100);
$('#Sale_details2').animate({
'left':180
},100);
$('#Sale_details1').animate({
'left':0
},100);
});
// ๅๅทฆๅๅณ็ๆๆ
// obj1ไธบๅๅทฆๆ้ฎ๏ผobj2ไธบๅๅณๆ้ฎ๏ผobj3ไธบ่ฆ็งปๅจ็ๅฏน่ฑก๏ผdisไธบๆฏๆฌก็งปๅจ็่ท็ฆป
goto($('.to_le'),$('.to_ri'),$('.clothes >ul'),1000)
function goto(obj1,obj2,obj3,dis){
obj1.click(function(){
// var lo = parseInt($('.clothes >ul').eq(i).css('left'));
for(var j =0;j<3;j++){
if(parseInt(obj3.eq(j).css('left')) < -dis){
obj3.eq(j).css('left',dis);
}
}
for(var i= 0;i<3;i++){
obj3.eq(i).animate({
'left':parseInt(obj3.eq(i).css('left'))-dis
})
}
})
obj2.click(function(){
for(var j =0;j<3;j++){
if(parseInt(obj3.eq(j).css('left')) > dis){
obj3.eq(j).css('left',-dis);
}
}
for(var i= 0;i<3;i++){
obj3.eq(i).animate({
'left':parseInt(obj3.eq(i).css('left'))+dis
})
}
})
}
goto($('#com_bo_le'),$('#com_bo_ri'),$('.com_bottom >ul'),1170)
// ็ฉ3c
goto($('#mai_le'),$('#mar_ri'),$('.play_left >.play_main >ul').not('.play_main_ul'),590);
goto($('#ri_le'),$('#ri_ri'),$('.play_right >.play_main >ul').not('.play_main_ul'),590)
// $(function(){
// $('.to_le').click(function(){
// // var lo = parseInt($('.clothes >ul').eq(i).css('left'));
// for(var j =0;j<3;j++){
// if(parseInt($('.clothes >ul').eq(j).css('left')) < -1000){
// $('.clothes >ul').eq(j).css('left',1000);
// }
// }
// for(var i= 0;i<3;i++){
// $('.clothes >ul').eq(i).animate({
// 'left':parseInt($('.clothes >ul').eq(i).css('left'))-1000
// })
// }
// })
// $('.to_ri').click(function(){
// for(var j =0;j<3;j++){
// if(parseInt($('.clothes >ul').eq(j).css('left')) > 1000){
// $('.clothes >ul').eq(j).css('left',-1000);
// }
// }
// for(var i= 0;i<3;i++){
// $('.clothes >ul').eq(i).animate({
// 'left':parseInt($('.clothes >ul').eq(i).css('left'))+1000
// })
// }
// })
// })
// ็งๆๆ ็่ชๅจ่ฝฎๆญๅพ
$(function(){
var mar =1;
var timer1 =null;
var lele =0;
$('.au_clothes >ul >li').eq(0).css('background','#f00');
plau();
function plau(){
timer1=setInterval(function(){
if(mar >0){
$('#au_left').css('display','block');
$('#au_right').css('display','none');
$('.au_clothes >ul >li').eq(0).css('background','#f00');
$('.au_clothes >ul >li').eq(1).css('background','#342A2D');
}else{
$('#au_left').css('display','none');
$('#au_right').css('display','block');
$('.au_clothes >ul >li').eq(1).css('background','#f00');
$('.au_clothes >ul >li').eq(0).css('background','#342A2D');
}
mar = -mar;
},1000)
}
// ๅๆญขๅฎๆถๅจ
$('.au_clothes').mouseover(function(){
clearInterval(timer1);
}).mouseout(function(){
plau();
});
$('.au_clothes >ul >li').mouseover(function(){
lele = $(this).index();
// console.log(lele);
$('.au_clothes >ul >li').eq(lele).css('background','#f00');
$('.au_clothes >div').eq(lele).css('display','block');
$('.au_clothes >ul >li').eq(lele).siblings().css('background','#342A2D');
$('.au_clothes >div').eq(lele).siblings().css('display','none');
$('.au_clothes >ul').css('display','block');
})
})
// ็งปๅจๆๆ(ไธ็ฅ้ไปไนๅๅ ๏ผๅฏน#com_bot_leๆฒกๆ็จ๏ผๅ็ฌๅๅฏไปฅไฝฟ็จ)
function mov(obj1, obj2,num){
var la= 0;
var ol = parseInt(obj2.css('left'));
obj1.mouseover(function(){
la = $(this).index();
obj2.eq(la).animate({
'left':ol+num
},100)
}).mouseout(function(){
obj2.eq(la).animate({
'left':ol
},100)
})
};
mov($('.find_list >ul >li'),$('.find_list >ul >li >img'),-4);
mov($('.prize_details >ul >li'),$('.prize_details >ul >li >img'),4);
mov($('.enjoy_main >ul >li'),$('.enjoy_main >ul >li >img'),-10);
mov($('.enjoy_main_rig >ul >li'),$('.enjoy_main_rig >ul >li >img'),-4);
mov($('.com_left >.com_ul >li'),$('.com_left >.com_ul >li >img'),-4);
mov($('.com_right >.com_ul >li'),$('.com_right >.com_ul >li >img'),-4);
mov($('.com_left >.com_pic_left'),$('.com_left >.com_pic_left >img'),-4);
mov($('.com_right >.com_pic_left'),$('.com_right >.com_pic_left >img'),-4);
mov($('#play_le'),$('#play_le img'),-4);
mov($('#play_ri'),$('#play_ri img'),-4);
mov($('.play_main >.play_main_ul >li'),$('.play_main >.play_main_ul >li >img'),-4);
mov($('.play_right >.play_main > ul >li'),$('.play_right >.play_main > ul >li >img'),-4);
function mov2(obj1,obj2,num){
var ol = parseInt(obj2.css('left'));
obj1.mouseover(function(){
obj2.animate({
'left':ol +num
},100)
}).mouseout(function(){
obj2.animate({
'left':ol
},100)
})
}
mov2($('#com_bot_le'),$('#com_bot_le >img'),-4);
// ๆ่กๆฆ็็บข็บฟ
$('.rank_box_head > ul >li').mouseover(function(){
// console.log($(this).index());
var to = $(this).index();
$('#rank_line').animate({
'left':to*78
},100);
// $('.rank_box_main >ul').eq(to).css('display','block');
$('.rank_box_main >ul').eq(to).fadeIn(100);
// $('.rank_box_main >ul').eq(to).siblings().css('display','none');
$('.rank_box_main >ul').eq(to).siblings().fadeOut(100);
})
// ไผไนฐไธ่พ็่ฝฎๆญๅพ
lunbo($('.buy_list >div'),$('#buy_le >li'),$('#list_left'),$('#list_right'),'#C8C8C8','#E01222',4000);
//่ง
me็่ฝฎๆญๅพ
lunbo($('.live_box >a'),$('#live_ul >li'),$('#live_le'),$('#live_ri'),'#C7C7C7','#E31F2F',2000);
// ๅทฆไพงๆปๅจๆ
$(function(){
var floor_list = [];
for(var xx =4;xx<9;xx++ ){
floor_list[floor_list.length] = $('.main >div').eq(xx).offset().top;
}
var flag = true;
var timer3 = null;
// ๆปๅจๆถ้ข่ฒๅ็ๅๅ
$(window).scroll(function(){
var tl = ($(this).scrollTop());
for(var fl=0;fl<5;fl++){
if(tl >= floor_list[fl]){
for(var ii =0;ii<5;ii++){
$('.le_slide >ul >li').eq(ii).css('background','#918888');
}
$('.le_slide >ul >li').eq(fl).css('background','#D70B1C')
}
}
if(!flag){
clearInterval(timer3);
}
flag =false;
});
// ็นๅปๆถๅ็ๆปๅจ
for(var fl =0;fl<5;fl++){
$('.le_slide >ul >li').click(function(){
clearInterval(timer3);
console.log('1');
var tol = $('.main >div').eq($(this).index()+4).offset().top;
var th = $(window).scrollTop();
var speed = 0;
timer3 = setInterval(function(){
flag = true;
speed = (tol - th)/8;
console.log(speed);
speed = speed >0?Math.ceil(speed):Math.floor(speed);
document.documentElement.scrollTop = th + speed ;
th = $(window).scrollTop();
// console.log(th);
// console.log(tol);
},30)
})
}
// ๅฝๆปๅจๅฐๆไธไธชไฝ็ฝฎๆถๅทฆไพงๆ ๆถๅคฑๆๆพ็คบ
$(window).scroll(function(){
if($(this).scrollTop() >$('.timer_go').offset().top){
$('.le_slide').fadeIn(100);
$('.mid_slide').slideDown();
$('.mid_slide').css('display','block');
}else{
$('.le_slide').fadeOut(100);
$('.mid_slide').slideUp(1);
}
})
})
// ๅๅฐ้กถๅฑ
$(function(){
var timer4 =null;
$('#di').click(function(){
clearInterval(timer4);
var tol =$(window).scrollTop();
timer4 = setInterval(function(){
var speed = (0-tol)/8;
speed = speed >0?Math.ceil(speed):Math.floor(speed);
document.documentElement.scrollTop = tol + speed;
tol = $(window).scrollTop();
if(tol == 0){
clearInterval(timer4);
}
},30)
})
})
// ๅณไพงๆปๅจๆ ๆปๅจ
$(function(){
var ji;
$('.ri_slide >ul >li').mouseover(function(){
ji =$(this).index();
move($('.ri_slide >ul >li >div').eq(ji),1254,ji);
// $('.ri_slide >ul >li ').eq(ji).css('background','#C81623');
$(this).children().eq(0).css('background','#C81623');
}).mouseout(function(){
move($('.ri_slide >ul >li >div').eq(ji),1324,ji);
// $('.ri_slide >ul >li ').eq(ji).css('background','#7A6E6E');
$(this).children().eq(0).css('background','#7A6E6E');
})
var time=[0,1,2,3,4,5,6,7];
function move(obj,dis,ji){
// console.log(obj);
clearInterval(time[ji]);
time[ji] = setInterval(function(){
var kl = obj.offset().left;
var speed = (dis-kl)/8;
if(speed>0){
speed = Math.ceil(speed);
}else{
speed = Math.floor(speed);
}
if(kl+speed == dis){
clearInterval(time[ji]);
}else{
obj.offset({left:kl+speed});
}
},30)
}
})
// ๅณไพงๅบ้จๆปๅจๆ
$(function(){
var ji;
$('.rto_slide >ul >li').mouseover(function(){
ji =$(this).index();
move($('.rto_slide >ul >li >div').eq(ji),1254,ji);
// $('.ri_slide >ul >li ').eq(ji).css('background','#C81623');
$(this).children().eq(0).css('background','#C81623');
}).mouseout(function(){
move($('.rto_slide >ul >li >div').eq(ji),1324,ji);
// $('.ri_slide >ul >li ').eq(ji).css('background','#7A6E6E');
$(this).children().eq(0).css('background','#7A6E6E');
})
var time=[8,9];
function move(obj,dis,ji){
// console.log(obj);
clearInterval(time[ji]);
time[ji] = setInterval(function(){
var kl = obj.offset().left;
var speed = (dis-kl)/8;
if(speed>0){
speed = Math.ceil(speed);
}else{
speed = Math.floor(speed);
}
if(kl+speed == dis){
clearInterval(time[ji]);
}else{
obj.offset({left:kl+speed});
}
},30)
}
})
|
ab8e4cb9068a0b57addb871d751939008742cde2
|
[
"JavaScript",
"HTML"
] | 4 |
JavaScript
|
hj13235415/hwjxm.github.io
|
6ea7d76d4d2e3307db1999a5dce3989336323530
|
9349f2fa2d6e2f501cdb387de80431729ea12de1
|
refs/heads/master
|
<repo_name>EllaVankirk/typescript-lc101-projects<file_sep>/studio/Rocket.ts
import { Astronaut } from "./Astronaut";
export class Rocket {
name: string;
totalCapacityKg: number;
cargoItems: string[];
astronauts: string[];
constructor(name: string, totalCapacityKg: number);
this.name = name;
this.totalCapacityKg = totalCapacityKg;
sumMass(items: Payload[]): number{ // payload is making sure these are numbers
// for each item in payload[]
// add them together
}
currentMassKg(): number {
// return the combined mass of astronauts and cargo items
let totalMass:number = 0 ;
}
canAdd(item: Payload): boolean {
}
addCargo(cargo: Cargo): boolean {
if (this.canAdd === true) {
return true;
} else if (this.canAdd === false) {
return false;
}
}
addAstronaut(astronaut: Astronaut): boolean {
if (this.canAdd === true) {
return true;
} else if (this.canAdd === false) {
return false;
}
}
}
// let astronauts: Astronaut[] = [
// new Astronaut(75, 'Mae'), massKg and name
// new Astronaut(81, 'Sally'),massKg and name
// new Astronaut(99, 'Charles')massKg and name
// ];
// let cargo: Cargo[] = [
// new Cargo(3107.39, "Satellite"), massKg and material
// new Cargo(1000.39, "Space Probe"), massKg and material
// new Cargo(753, "Water"), massKg and material
// new Cargo(541, "Food"), massKg and material
// new Cargo(2107.39, "Tesla Roadster"),massKg and material
// ];
|
55c0083e5f62b232fa8199393a3aa245c211c201
|
[
"TypeScript"
] | 1 |
TypeScript
|
EllaVankirk/typescript-lc101-projects
|
1fb61fb7e74e28eb76285275d5454338382fe07d
|
20c2e655a9bf18bcc5acbe10c10a5a219ee7ee0e
|
refs/heads/master
|
<repo_name>igrik12/Tests<file_sep>/headlessFirefoxDriver.js
'use strict';
const firefox = require('selenium-webdriver/firefox');
var selenium = require('selenium-webdriver');
const screen = {
width: 640,
height: 480
};
/**
* Creates a Selenium WebDriver using Headless Firefox as the browser
* @returns {ThenableWebDriver} selenium web driver
*/
module.exports = function () {
var driver = new selenium.Builder()
.setFirefoxOptions(new firefox.Options().headless().windowSize(screen))
.withCapabilities(selenium.Capabilities.firefox())
.build();
return driver;
};
|
580ebddece1e867789edbb3b99e8ffbaf29f6fcf
|
[
"JavaScript"
] | 1 |
JavaScript
|
igrik12/Tests
|
35a8be2410def04137b4ce6ddb1e9fc2d6888196
|
533954e94680eb55e9d693ede32fc74f29352d71
|
refs/heads/master
|
<file_sep>if (window.performance && window.performance.navigation.type === window.performance.navigation.TYPE_BACK_FORWARD) {
alert('Please refresh the page and continue');
window.location.reload();
}
var textWrapper = document.querySelector('.ml2');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");
anime.timeline({ loop: true })
.add({
targets: '.ml2 .letter',
scale: [4, 1],
opacity: [0, 1],
translateZ: 0,
easing: "easeOutExpo",
duration: 950,
delay: (el, i) => 70 * i
}).add({
targets: '.ml2',
opacity: 0,
duration: 1000,
easing: "easeOutExpo",
delay: 1000
});
// ---------------Landing Page Animation------------------------------------
var TxtRotate = function (el, toRotate, period) {
this.toRotate = toRotate;
this.el = el;
this.loopNum = 0;
this.period = parseInt(period, 10) || 2000;
this.txt = "";
this.tick();
this.isDeleting = false;
};
TxtRotate.prototype.tick = function () {
var i = this.loopNum % this.toRotate.length;
var fullTxt = this.toRotate[i];
if (this.isDeleting) {
this.txt = fullTxt.substring(0, this.txt.length - 1);
} else {
this.txt = fullTxt.substring(0, this.txt.length + 1);
}
this.el.innerHTML = '<span class="wrap">' + this.txt + "</span>";
var that = this;
var delta = 300 - Math.random() * 100;
if (this.isDeleting) {
delta /= 2;
}
if (!this.isDeleting && this.txt === fullTxt) {
delta = this.period;
this.isDeleting = true;
} else if (this.isDeleting && this.txt === "") {
this.isDeleting = false;
this.loopNum++;
delta = 500;
}
setTimeout(function () {
that.tick();
}, delta);
};
window.onload = function () {
var elements = document.getElementsByClassName("txt-rotate");
for (var i = 0; i < elements.length; i++) {
var toRotate = elements[i].getAttribute("data-rotate");
var period = elements[i].getAttribute("data-period");
if (toRotate) {
new TxtRotate(elements[i], JSON.parse(toRotate), period);
}
}
// INJECT CSS
var css = document.createElement("style");
css.type = "text/css";
css.innerHTML = ".txt-rotate > .wrap { border-right: 0.08em solid #666 }";
document.body.appendChild(css);
};
// ------------------------------- Drag Drop------------------------------------------------------------
$(document).ready(() => {
$("#convert_one").click(() => {
$("#font").show("slide", { direction: "left" }, 1000);
});
$("#finalbtn").click(() => {
$("#download").show();
$("#font").hide();
$("#success_container").hide();
});
});
var file_name = document.getElementById("file_name");
var myfile = document.getElementById("myfile");
let file = ''
document.querySelectorAll(".drop-zone__input").forEach((inputElement) => {
const dropZoneElement = inputElement.closest(".drop-zone");
dropZoneElement.addEventListener("click", (e) => {
inputElement.click();
});
inputElement.addEventListener("change", (e) => {
if (inputElement.files.length) {
updateThumbnail(dropZoneElement, inputElement.files[0]);
// file to be loaded
file = inputElement.files[0]
console.log(inputElement.files[0]);
console.log(inputElement.files[0].size);
console.log(inputElement.files[0].name);
let size_of_file = inputElement.files[0].size;
var check = inputElement.files[0].name;
file_name.innerHTML = inputElement.files[0].name.trim().replace(/\s/g, "");
// var regxtwo = /^([A-Za-z0-9_./()]{2,500}).doc$/;
var regxthree = /^([A-Za-z0-9_./\-()]{2,500}).docx$/;
var regxfour = /^([A-Za-z0-9_./\-()]{2,500}).txt$/;
if (regxthree.test(check) || regxfour.test(check)) {
if (size_of_file > 25000) {
document.getElementById("upload").style.display = "none";
document.getElementById("error_container").style.display = "block";
alert("file size should be less than 25KB. Please refresh and upload again");
} else {
document.getElementById("upload").style.display = "none";
document.getElementById("success_container").style.display = "block";
}
}
else {
document.getElementById("upload").style.display = "none";
document.getElementById("error_container").style.display = "block";
alert("File type should be .docx or .txt. Please refresh and upload again");
}
}
});
dropZoneElement.addEventListener("dragover", (e) => {
e.preventDefault();
dropZoneElement.classList.add("drop-zone--over");
});
["dragleave", "dragend"].forEach((type) => {
dropZoneElement.addEventListener(type, (e) => {
dropZoneElement.classList.remove("drop-zone--over");
});
});
dropZoneElement.addEventListener("drop", (e) => {
e.preventDefault();
if (e.dataTransfer.files.length) {
inputElement.files = e.dataTransfer.files;
// file to be loaded
file = e.dataTransfer.files[0]
console.log(e.dataTransfer.files[0]);
console.log(e.dataTransfer.files[0].size);
console.log(e.dataTransfer.files[0].name);
var check = e.dataTransfer.files[0].name.trim().replace(/\s/g, "");
file_name.innerHTML = e.dataTransfer.files[0].name;
// var regx = /.+\.pdf$/;
// var regxtwo = /^([A-Za-z0-9_./()]{2,500}).doc$/;
var regxthree = /^([A-Za-z0-9_./\-()]{2,500}).docx$/;
var regxfour = /^([A-Za-z0-9_./\-()]{2,500}).txt$/;
if (regxthree.test(check) || regxfour.test(check)) {
if (inputElement.files[0].size > 25000) {
document.getElementById("upload").style.display = "none";
document.getElementById("error_container").style.display = "block";
alert("file size should be less than 25KB. Please refresh and upload again");
} else {
document.getElementById("upload").style.display = "none";
document.getElementById("success_container").style.display = "block";
}
}
else {
document.getElementById("upload").style.display = "none";
document.getElementById("error_container").style.display = "block";
alert("File type should be .docx or .txt. Please refresh and upload again");
}
updateThumbnail(dropZoneElement, e.dataTransfer.files[0]);
}
dropZoneElement.classList.remove("drop-zone--over");
});
});
/**
* Updates the thumbnail on a drop zone element.
*
* @param {HTMLElement} dropZoneElement
* @param {File} file
*/
function updateThumbnail(dropZoneElement, file) {
let thumbnailElement = dropZoneElement.querySelector(".drop-zone__thumb");
// First time - remove the prompt
if (dropZoneElement.querySelector(".drop-zone__prompt")) {
dropZoneElement.querySelector(".drop-zone__prompt").remove();
}
// First time - there is no thumbnail element, so lets create it
if (!thumbnailElement) {
thumbnailElement = document.createElement("div");
thumbnailElement.classList.add("drop-zone__thumb");
dropZoneElement.appendChild(thumbnailElement);
}
thumbnailElement.dataset.label = file.name;
}
//font selected by the user
var font_select = document.getElementById("finalbtn");
font_select.addEventListener("click", async () => {
let selected = document.querySelector('input[type="radio"]:checked');
// console.log(selected.value);
const formData = new FormData();
formData.append("file", file);
formData.append("font", selected.value);
let url = 'https://stc-handwriter.azurewebsites.net/';
// let url = 'http://localhost:3000/'
fetch(url + 'handwriter/convert', {
method: 'POST',
body: formData
})
.then((response) => response.json())
.then((result) => {
if (result.pdfFilename) {
window.location.href = (url + result.pdfFilename)
$("#download").hide();
$("#downloaded").show();
}
else {
alert(result.err)
}
})
.catch(error => {
console.error(error)
alert("There was some error connecting to server. Please try again !");
})
});<file_sep>var fs = require('fs');
var formidable = require('formidable');
const axios = require('axios')
const PDFDocument = require('pdfkit');
const Jimp = require('jimp');
const mammoth = require('mammoth')
/**
* convertToHandwritten return the path for pdf file generated
* by accepting file to be parsed along with font type
* from a multipart form request
*/
const convertToHandwritten = async (req, res) => {
var form = new formidable.IncomingForm();
// parsing the form object
form.parse(req, async (err, fields, files) => {
// console.log(files['file'])
// Checking if file is uploaded and file size doesn't exceeds 25KB
if (files['file'] && files['file'].type && files['file'].size <= 25000) {
let fileContent = "";
let error = ""
// reading the file to be parsed
fs.readFile(files['file'].path, async (err, data) => {
let filePath = files['file'].path;
let filebuffer = data;
let filename = files['file'].name;
if (filename.length == 0)
return "";
var dot = filename.lastIndexOf(".");
if (dot == -1)
return "";
var fileextension = filename.substr(dot, filename.length);
// console.log(filePath)
// console.log(filebuffer)
// console.log(filename)
// console.log(fileextension)
// Checking if file format is either .doc or .docx or .txt
if (fileextension == '.docx') {
// reading .docx or .doc file using mammoth
try {
const docTxt = await mammoth.extractRawText({ path: filePath })
var textLines = docTxt.value.split("\n");
// deleting extra '\n' from text
for (var i = 0; i < textLines.length; i += 2) {
fileContent += textLines[i] + '\n'
}
} catch (e) {
error = e
}
}
else if (fileextension == '.txt') {
try {
fileContent = data.toString()
}
catch (e) {
error = e
}
}
else {
return res.status(415).send({ err: 'Invalid file format' })
}
if (error) {
return res.status(400).send(error)
}
//-------------here I have to check character limit
console.log('file content : ' + fileContent)
console.log('font selected : ' + fields.font)
// sending request to python script for generating handwritten images
axios.post('https://convert-to-handwriting.herokuapp.com/', {
"text": fileContent,
"font": parseInt(fields.font)
})
.then(async (response) => {
const pages = ['1', '2', '3', '4']
imgArray = ['', '', '', '']
let imgCount = 0
// creating a pdf doc object
var pdfDoc = new PDFDocument();
const createPdf = async () => {
// parsing the response and generating the imgCodes array with base64 codes
pages.forEach(element => {
if (data[element].length != 0) {
for (let i = 0; i < response.data[element].length; i++) {
if (i != 0 && i != 1 && i != (response.data[element].length - 1)) {
imgArray[parseInt(element) - 1] += response.data[element][i]
}
}
}
})
// counting the number of images generated
for (let i = 0; i < imgArray.length; i++) {
if (imgArray[i] != '') {
imgCount += 1
}
}
// creating public directory in the root folder if doesn't exists
if (!fs.existsSync('./public')) {
fs.mkdirSync('./public');
console.log('directory created')
}
const timeStamp = Date.now()
// creating empty pdf file
const fileStream = fs.createWriteStream('./public/handwritten' + timeStamp + '.pdf')
pdfDoc.pipe(fileStream);
for (let i = 0; i < imgCount; i++) {
// generating png files from base64 codes
console.log('creating image')
fs.writeFileSync('./public/image' + timeStamp + (i + 1) + '.png', imgArray[i], { encoding: 'base64' });
if (i > 0) {
pdfDoc.addPage()
}
console.log('adding image to pdf')
// adding generated images to pdf doc object
let image = await Jimp.read('./public/image' + timeStamp + (i + 1) + '.png');
image.getBuffer(Jimp.MIME_PNG, (err, result) => {
// Scaling pdf proprotionally to the specified width
pdfDoc.image(result, 34, 10, { width: 550 })
});
// deleted the images which are no longer in use
fs.unlink('./public/image' + timeStamp + (i + 1) + '.png', (err) => {
if (err) {
console.log('problem deleting image')
return
}
else {
console.log('image deleted')
}
})
}
console.log('loading PDF')
pdfDoc.end();
// waiting for pdf to process and returning the pdf path
fileStream.on("close", () => {
console.log(`Generated PDF file `);
return res.send({ pdfFilename: 'handwritten' + timeStamp + '.pdf' })
})
}
await createPdf()
})
.catch(() => {
return res.status(500).send({ err: 'Script not working or request to script is invalid' })
})
});
}
else {
return res.status(400).send({ err: "No file uploaded or file size larger than 25Kb" })
}
})
}
module.exports = convertToHandwritten
<file_sep># STC_Handwriting_Generator
<h1>https://rishabhbudhia.github.io/STC_Handwriting_Generator/</h1>
<file_sep>๏ปฟastroid==2.4.2
click==7.1.2
colorama==0.4.4
cycler==0.10.0
Flask==1.1.2
gunicorn==20.0.4
isort==5.7.0
itsdangerous==1.1.0
Jinja2==2.11.3
kiwisolver==1.3.1
lazy-object-proxy==1.4.3
MarkupSafe==1.1.1
matplotlib==3.3.4
mccabe==0.6.1
numpy==1.19.5
Pillow==8.1.0
pybase64==1.1.4
pylint==2.6.0
pyparsing==2.4.7
python-dateutil==2.8.1
six==1.15.0
toml==0.10.2
Werkzeug==1.0.1
wrapt==1.12.1
Flask-Cors==3.0.10<file_sep>from PIL import Image, ImageFont, ImageDraw
import matplotlib.pyplot as plt
import matplotlib.image as mpimg
import base64
import numpy as np
from io import BytesIO
from flask import Flask, jsonify, request
from flask_cors import CORS, cross_origin
app = Flask(__name__)
cors = CORS(app)
app.config['CORS_HEADERS'] = 'Content-Type'
def text_wrap(text, font, max_width):
lines = []
# If the text width is smaller than the image width, then no need to split
# just add it to the line list and return
if font.getsize(text)[0] <= max_width:
lines.append(text)
else:
#split the line by spaces to get words
words = text.split(' ')
i = 0
# append every word to a line while its width is shorter than the image width
while i < len(words):
line = ''
while i < len(words) and font.getsize(line + words[i])[0] <= max_width:
line = line + words[i]+ " "
i += 1
if not line:
line = words[i]
i += 1
lines.append(line)
return lines
def get_image12(page,fontname,pagetype,word_space,line_height,line_spacing,letter_width, symbols):
pag1 = Image.open('static/template'+pagetype+'.jpg')
height = 15
width = 15
if (len(page) != 0):
for lines in page:
for words in lines.split():
for letters in words:
if(letters.isalpha()):
if (letters.islower()):
overlay=Image.open('static/'+fontname+'/s'+letters+'.png').convert('RGBA')
else:
overlay=Image.open('static/'+fontname+'/'+letters+'.png').convert('RGBA')
elif (letters.isdigit()):
overlay=Image.open('static/'+fontname+'/'+letters+'.png').convert('RGBA')
else:
if letters in symbols:
letters = symbols[letters]
else:
letters = 'question'
overlay=Image.open('static/'+fontname+'/'+letters+'.png').convert('RGBA')
x,y=overlay.size
pag1.paste(overlay, (width,height,x+width,y+height), overlay)
width+=(x-letter_width)
width+=word_space
height+=line_height
height+=line_spacing
width=15
return pag1
def get_image3(page,pagetype,line_spacing):
pag1 = Image.open('static/template'+pagetype+'.jpg')
height = 20
width = 20
draw = ImageDraw.Draw(pag1)
font = ImageFont.truetype('static/Bestfont10-Regular.ttf', 167)
for line in page:
draw.text((width,height),line,font=font,fill=0)
height+=line_spacing
return pag1
@app.route("/", methods=["POST"])
@cross_origin()
def home():
data = request.json
text = data['text']
font = data['font']
letter_width=0 #individual letter width
word_space=0 #space between words
xsize=0 #font width
ysize=0 #font height
line_height=0 #height for line placement
line_spacing=0 #height for line change
fontname='' #fonttype
noflines = 0 #noflines in a single page
pagetype = '' #template used
limit = 0
if font==1:
limit=2393
letter_width=25
word_space=70
xsize=70
ysize=100
line_height=40
line_spacing=51
fontname='my font2'
noflines = 38
pagetype = '1'
elif font==2:
limit=2300
letter_width= 40
word_space=45
xsize=100
ysize=200
line_height=99
line_spacing=59
fontname='myfont4'
noflines = 22
pagetype = '2'
elif font==3:
line_height = 104
line_spacing = 104
noflines = 33
pagetype = '3'
page1 = []
page2 = []
page3 = []
page4 = []
if (font == 1 or font == 2):
height = 15
width = 15
page = 1
lines = text.strip().split('\n')
temp = []
l = ''
for line in lines:
for word in line.split():
if ((width+len(word)*(xsize-letter_width) + word_space)<=limit):
width = width + len(word)*(xsize-letter_width)
width = width + word_space
l = l + word + ' '
else:
width = 15
if (page == 1):
page1.append(l)
elif (page == 2):
page2.append(l)
elif (page == 3):
page3.append(l)
else:
page4.append(l)
l = word + ' '
width = width + len(word)*(xsize-letter_width)
width = width + word_space
height+=line_height
height+=line_spacing
if (height>3450):
page+=1
height = 15
width = 15
if (page == 1):
page1.append(l)
elif (page == 2):
page2.append(l)
elif (page == 3):
page3.append(l)
else:
page4.append(l)
l= ''
height+=line_height
height+=line_spacing
if (height>3450):
page+=1
if (page == 5):
break
height = 15
if (font == 3):
fonts = ImageFont.truetype('static/Bestfont10-Regular.ttf', 167)
lines = text.strip().split('\n')
x = 20
y = 20
final_stemmed = []
for line in lines:
lines2 = text_wrap(line, fonts, 2450)
for prlines in lines2:
final_stemmed.append(prlines)
page1 = final_stemmed[0:33]
page2 = final_stemmed[33:66]
page3 = final_stemmed[66:99]
page4 = final_stemmed[99:132]
symbols = {
'.' : 'fullstop',
',' : 'comma',
'?' : 'question',
'!' : 'exclamation',
'{' : 'openingcurly',
'[' : 'openingsquare',
'(' : 'openingbracket',
')' : 'closingbracket',
'}' : 'closingcurly',
']' : 'closingsquare',
'\'': 'inverted',
'โ' : 'doubleinverted',
'โ' : 'doubleinverted',
'โ' : 'inverted',
'โ' : 'inverted',
'/' : 'slash',
':' : 'colon',
';' : 'semicolon',
'=' : 'equals',
'+' : 'plus',
'*' : 'multiply',
'\\': 'backslash',
'#' : 'hash',
'$' : 'dollar',
'@' : 'atsign',
'~' : 'tilde',
'`' : 'inverted',
'^' : 'exponent',
'-' : 'hyphen',
'%' : 'percent',
'<' : 'lessthan',
'>' : 'greaterthan',
'_' : 'underscore',
'|' : 'or',
'&' : 'ampersand',
'\"': 'doubleinverted'
}
img_str1 = ''
img_str2 = ''
img_str3 = ''
img_str4 = ''
if (font == 1 or font == 2):
if (len(page1)!=0):
image1=get_image12(page1,fontname,pagetype,word_space,line_height,line_spacing,letter_width,symbols)
buffered = BytesIO()
image1.save(buffered, format="JPEG")
img_str1 = base64.b64encode(buffered.getvalue())
if (len(page2)!=0):
image1=get_image12(page2,fontname,pagetype,word_space,line_height,line_spacing,letter_width,symbols)
buffered = BytesIO()
image1.save(buffered, format="JPEG")
img_str2 = base64.b64encode(buffered.getvalue())
if (len(page3)!=0):
image1=get_image12(page3,fontname,pagetype,word_space,line_height,line_spacing,letter_width,symbols)
buffered = BytesIO()
image1.save(buffered, format="JPEG")
img_str3 = base64.b64encode(buffered.getvalue())
if (len(page4)!=0):
image1=get_image12(page4,fontname,pagetype,word_space,line_height,line_spacing,letter_width,symbols)
buffered = BytesIO()
image1.save(buffered, format="JPEG")
img_str4 = base64.b64encode(buffered.getvalue())
if (font == 3):
if (len(page1)!=0):
image1 = get_image3(page1,pagetype,line_spacing)
buffered = BytesIO()
image1.save(buffered, format="JPEG")
img_str1 = base64.b64encode(buffered.getvalue())
if (len(page2)!=0):
image1 = get_image3(page2,pagetype,line_spacing)
buffered = BytesIO()
image1.save(buffered, format="JPEG")
img_str2 = base64.b64encode(buffered.getvalue())
if (len(page3)!=0):
image1 = get_image3(page3,pagetype,line_spacing)
buffered = BytesIO()
image1.save(buffered, format="JPEG")
img_str3 = base64.b64encode(buffered.getvalue())
if (len(page4)!=0):
image1 = get_image3(page4,pagetype,line_spacing)
buffered = BytesIO()
image1.save(buffered, format="JPEG")
img_str4 = base64.b64encode(buffered.getvalue())
final_prod = { '1': str(img_str1), '2':str(img_str2),'3':str(img_str3),'4':str(img_str4) }
return final_prod
if(__name__=='__main__'):
app.run()
<file_sep># Bit To Ink
> <Subtitle>
> BitToInk is a website which converts digital text to handwritten PDF
<!--
[](https://bittoink.stcvit.in/) -->
<br>
## Getting Started
1. Open the website.
2. Upload a .txt or a .docx file with some text (max - 3.5 pages)
3. Select a font
4. Click on convert
## Contributors
* <a href="https://github.com/singhalyash8080"> <NAME> </a>
* <a href="https://github.com/samarthya-jha"> <NAME> </a>
* <a href="https://github.com/Anay241"> <NAME> </a>
* <a href="https://github.com/RishabhBudhia"> <NAME> </a>
|
81a06190dd42659491f5c387c36b548d62a3140d
|
[
"JavaScript",
"Python",
"Text",
"Markdown"
] | 6 |
JavaScript
|
singhalyash8080/Bit-To-Ink
|
993f0182ac0b43df1db9f6c5e42fb3b44addd037
|
e5d89f664012d3242c2e4f804bda40d2cafb67c8
|
refs/heads/master
|
<repo_name>bravesoftdz/LockFile<file_sep>/Readme.md
# LockFile
[](https://ci.appveyor.com/project/Tyrrrz/LockFile/branch/master)
[](https://ci.appveyor.com/project/Tyrrrz/LockFile/branch/master/tests)
[](https://codecov.io/gh/Tyrrrz/LockFile)
[](https://nuget.org/packages/LockFile)
[](https://nuget.org/packages/LockFile)
[](https://patreon.com/tyrrrz)
[](https://buymeacoffee.com/tyrrrz)
LockFile is the simplest lock file implementation for .NET.
## Download
- [NuGet](https://nuget.org/packages/LockFile): `dotnet add package LockFile`
- [Continuous integration](https://ci.appveyor.com/project/Tyrrrz/LockFile)
## Features
- Dead simple
- Targets .NET Framework 4.5+ and .NET Standard 2.0+
## Usage
Lock files are acquired by opening a file with `FileShare.None`, which guarantees exclusive access to file. Lock files are released when they are disposed.
### Try to acquire a lock file once
```c#
using (var lockFile = LockFile.TryAcquire("some.lock"))
{
if (lockFile != null)
{
// Lock file acquired
}
}
```
### Wait until lock file is released and acquire it
```c#
using (var lockFile = LockFile.WaitAcquire("some.lock"))
{
// Lock file is eventually acquired
}
```
Or you can set a timeout via `CancellationToken`:
```c#
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(2)))
using (var lockFile = LockFile.WaitAcquire("some.lock", cts.Token))
{
// If lock file is not acquired within 2 seconds, an exception is thrown
}
```
## Libraries used
- [NUnit](https://github.com/nunit/nunit)
- [Coverlet](https://github.com/tonerdo/coverlet)
## Donate
If you really like my projects and want to support me, consider donating to me on [Patreon](https://patreon.com/tyrrrz) or [BuyMeACoffee](https://buymeacoffee.com/tyrrrz). All donations are optional and are greatly appreciated. ๐<file_sep>/LockFile.Tests/LockFileTests.cs
๏ปฟusing System;
using System.IO;
using System.Threading;
using System.Threading.Tasks;
using NUnit.Framework;
namespace LockFile.Tests
{
[TestFixture]
public class LockFileTests
{
public string TestDirPath => TestContext.CurrentContext.TestDirectory;
public string TempDirPath => Path.Combine(TestDirPath, "Temp");
[SetUp]
public void SetUp()
{
Directory.CreateDirectory(TempDirPath);
}
[TearDown]
public void TearDown()
{
if (Directory.Exists(TempDirPath))
Directory.Delete(TempDirPath, true);
}
[Test]
public void LockFileInfo_TryAcquire_Test()
{
var lockFilePath = Path.Combine(TempDirPath, Guid.NewGuid().ToString());
using (var lockFile = LockFile.TryAcquire(lockFilePath))
{
Assert.That(lockFile, Is.Not.Null);
}
}
[Test]
public void LockFileInfo_TryAcquire_AlreadyAcquired_Test()
{
var lockFilePath = Path.Combine(TempDirPath, Guid.NewGuid().ToString());
using (LockFile.TryAcquire(lockFilePath))
{
var lockFile = LockFile.TryAcquire(lockFilePath);
Assert.That(lockFile, Is.Null);
}
}
[Test]
public void LockFileInfo_WaitAcquire_Test()
{
var lockFilePath = Path.Combine(TempDirPath, Guid.NewGuid().ToString());
using (var originalLockFile = LockFile.TryAcquire(lockFilePath))
{
Task.Delay(TimeSpan.FromSeconds(0.5)).ContinueWith(_ => originalLockFile.Dispose());
using (var newLockFile = LockFile.WaitAcquire(lockFilePath))
{
Assert.That(newLockFile, Is.Not.Null);
}
}
}
[Test]
public void LockFileInfo_WaitAcquire_Cancellation_Test()
{
var lockFilePath = Path.Combine(TempDirPath, Guid.NewGuid().ToString());
using (var cts = new CancellationTokenSource(TimeSpan.FromSeconds(0.5)))
using (LockFile.TryAcquire(lockFilePath))
{
Assert.Throws<OperationCanceledException>(() =>
LockFile.WaitAcquire(lockFilePath, cts.Token));
}
}
}
}<file_sep>/LockFile/LockFile.cs
๏ปฟusing System;
using System.IO;
using System.Threading;
using LockFile.Internal;
namespace LockFile
{
/// <summary>
/// Represents an exclusive resource backed by a file.
/// </summary>
public partial class LockFile : IDisposable
{
/// <summary>
/// File stream that represents this lock file.
/// </summary>
public FileStream FileStream { get; }
/// <summary>
/// Initializes an instance of <see cref="LockFile"/>.
/// </summary>
public LockFile(FileStream fileStream)
{
FileStream = fileStream.GuardNotNull(nameof(fileStream));
}
/// <inheritdoc />
public void Dispose() => FileStream.Dispose();
}
public partial class LockFile
{
/// <summary>
/// Tries to acquire a lock file with given file path.
/// Returns null if the file is already in use.
/// </summary>
public static LockFile TryAcquire(string filePath)
{
filePath.GuardNotNull(nameof(filePath));
try
{
var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
return new LockFile(fileStream);
}
// When access to file is denied, an IOException (not derived) is thrown
catch (IOException ex) when (ex.GetType() == typeof(IOException))
{
return null;
}
}
/// <summary>
/// Repeatedly tries to acquire a lock file, until the operation succeeds or is canceled.
/// </summary>
public static LockFile WaitAcquire(string filePath,
CancellationToken cancellationToken = default(CancellationToken))
{
filePath.GuardNotNull(nameof(filePath));
while (true)
{
// Throw if canceled
cancellationToken.ThrowIfCancellationRequested();
// Try to acquire lock file
var lockFile = TryAcquire(filePath);
if (lockFile != null)
return lockFile;
}
}
}
}
|
8ddc0c38229dce7c4a2299677d4dd31929fe0ccf
|
[
"Markdown",
"C#"
] | 3 |
Markdown
|
bravesoftdz/LockFile
|
e067887ab62008f8178b366265a2215896abf092
|
44cce95753ec224e68e1b5e566fb98a62d5fc7e7
|
refs/heads/master
|
<repo_name>gb-6k-house/node-yourshares<file_sep>/demo/src/myRequest.ts
/******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import * as http from 'http'
export class MyRequest {
host: string
port: number
constructor(host: string, port: number = 8080) {
this.host = host
this.port = port
}
private request(method: string, path: string, data: any, cb: any, headers: any = {
"Content-Type": 'charset=UTF-8',
}) {
if (typeof data === 'function') {
headers = cb;
cb = data;
}
// headers = Object.assign({ }, headers)
console.info(path + " ๅคด้จไฟกๆฏ: " + JSON.stringify(headers));
var opt = {
host: this.host,
port: this.port,
method: method,
path: path,
headers: headers
};
var body = "";
var req = http.request(opt, function (res) {
console.log("post response: " + res.statusCode);
res.setEncoding('utf8');
res.on('data', function (d) {
body += d;
}).on('end', function () {
console.log(res.headers);
console.log('่ฏทๆฑ่ฟๅๆฐๆฎไฝ:' + body);
typeof cb === 'function' && cb(body)
});
}).on('error', function (e) {
console.log("error: " + e.message);
})
if (typeof data !== 'function') {
req.write(JSON.stringify(data));
}
req.end();
}
post(path: string, data: any, cb: (data) => void, header?: any) {
this.request('POST', path, data, cb, header)
}
get(path: string, cb: (data) => void, header?: any) {
this.request('GET', path, cb, header)
}
delete(path: string, cb: (data) => void, header?: any) {
this.request('DELETE', path, cb, header)
}
}<file_sep>/lib/types/index.d.ts
/******************************************************************************
** ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
******************************************************************************/
import String from './String+Extension';
import { RPCStartup, RpcService } from "./YSRpcService";
import { YSHttpHandle } from "./YSHttpHandle";
import { YSErrorType, YSErrorTabel, YSPurifyMessage } from "./YSError";
import { RpcConfig } from "./YSRpcConfig";
import { RPCClient } from "./YSRpcClient";
import { YSDBManager, YSTable } from "./YSTable";
import * as Sequelize from 'sequelize';
import * as express from "express";
export { express, Sequelize, String, RPCStartup, RPCClient, RpcService, RpcConfig, YSHttpHandle, YSErrorType, YSErrorTabel, YSPurifyMessage, YSDBManager, YSTable };
<file_sep>/lib/types/YSRpcClient.d.ts
/******************************************************************************
** auth: liukai
** date: 2017/9
** ver : 1.0
** desc: ่ฏดๆ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import { RpcConfig } from "./YSRpcConfig";
/**
* RPCๅฎขๆท็ซฏ
*
* @export
* @class RPCClient
*/
export declare class RPCClient {
private packageName;
private protoPath;
private addressConfig;
private grpcClient;
private serviceName;
/**
*
* @param address
* @param serviceName
= * @param protoPath .proto file ่ทฏๅพ
* @param packageName proto่ฏดๆๆไปถไธญpackageๅ็งฐ
*/
constructor(address: RpcConfig, serviceName: string, protoPath: string, packageName: string);
private init;
/**
* protocol buffersๅฏไปฅๅฎไนๅ็ง็ฑปๅ็ๆๅก: https://grpc.io/docs/tutorials/basic/node.html
* ๏ผ1๏ผไธไธช ็ฎๅ RPC ๏ผ ๅฎขๆท็ซฏไฝฟ็จๅญๆ นๅ้่ฏทๆฑๅฐๆๅกๅจๅนถ็ญๅพ
ๅๅบ่ฟๅ๏ผๅฐฑๅๅนณๅธธ็ๅฝๆฐ่ฐ็จไธๆ ทใ
* // Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {}
* ๏ผ2๏ผไธไธช ๆๅกๅจ็ซฏๆตๅผ RPC ๏ผ ๅฎขๆท็ซฏๅ้่ฏทๆฑๅฐๆๅกๅจ๏ผๆฟๅฐไธไธชๆตๅป่ฏปๅ่ฟๅ็ๆถๆฏๅบๅใ
* ๅฎขๆท็ซฏ่ฏปๅ่ฟๅ็ๆต๏ผ็ดๅฐ้้ขๆฒกๆไปปไฝๆถๆฏใไปไพๅญไธญๅฏไปฅ็ๅบ๏ผ้่ฟๅจ ๅๅบ ็ฑปๅๅๆๅ
ฅ stream ๅ
ณ้ฎๅญ๏ผๅฏไปฅๆๅฎไธไธชๆๅกๅจ็ซฏ็ๆตๆนๆณใ
* // Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
// huge number of features.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
* ๏ผ3๏ผไธไธช ๅฎขๆท็ซฏๆตๅผ RPC ๏ผ ๅฎขๆท็ซฏๅๅ
ฅไธไธชๆถๆฏๅบๅๅนถๅฐๅ
ถๅ้ๅฐๆๅกๅจ๏ผ
ๅๆ ทไนๆฏไฝฟ็จๆตใไธๆฆๅฎขๆท็ซฏๅฎๆๅๅ
ฅๆถๆฏ๏ผๅฎ็ญๅพ
ๆๅกๅจๅฎๆ่ฏปๅ่ฟๅๅฎ็ๅๅบใ้่ฟๅจ ่ฏทๆฑ ็ฑปๅๅๆๅฎ stream ๅ
ณ้ฎๅญๆฅๆๅฎไธไธชๅฎขๆท็ซฏ็ๆตๆนๆณใ
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
* ๏ผ4๏ผ ไธไธช ๅๅๆตๅผ RPC ๆฏๅๆนไฝฟ็จ่ฏปๅๆตๅปๅ้ไธไธชๆถๆฏๅบๅใไธคไธชๆต็ฌ็ซๆไฝ๏ผ
ๅ ๆญคๅฎขๆท็ซฏๅๆๅกๅจๅฏไปฅไปฅไปปๆๅๆฌข็้กบๅบ่ฏปๅ๏ผๆฏๅฆ๏ผ ๆๅกๅจๅฏไปฅๅจๅๅ
ฅๅๅบๅ็ญๅพ
ๆฅๆถๆๆ็ๅฎขๆท็ซฏๆถๆฏ๏ผๆ่
ๅฏไปฅไบคๆฟ็่ฏปๅๅๅๅ
ฅๆถๆฏ๏ผๆ่
ๅ
ถไป่ฏปๅ็็ปๅใ
ๆฏไธชๆตไธญ็ๆถๆฏ้กบๅบ่ขซ้ข็ใไฝ ๅฏไปฅ้่ฟๅจ่ฏทๆฑๅๅๅบๅๅ stream ๅ
ณ้ฎๅญๅปๅถๅฎๆนๆณ็็ฑปๅใ
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
*/
private mapgRpcServiceToSelf;
}
<file_sep>/src/YSRpcClient.ts
/******************************************************************************
** auth: liukai
** date: 2017/9
** ver : 1.0
** desc: ่ฏดๆ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
/// <reference types="grpc" />
import { RpcConfig } from "./YSRpcConfig";
import * as Promise from "bluebird";
import * as grpc from "grpc"
let LOG_PRE = 'RPC Service Log-->>>'
/**
* RPCๅฎขๆท็ซฏ
*
* @export
* @class RPCClient
*/
export class RPCClient {
private packageName: string;
private protoPath: string;
private addressConfig: RpcConfig;
private grpcClient: any;
private serviceName: string;
/**
*
* @param address
* @param serviceName
= * @param protoPath .proto file ่ทฏๅพ
* @param packageName proto่ฏดๆๆไปถไธญpackageๅ็งฐ
*/
constructor(
address: RpcConfig,
serviceName: string,
protoPath: string,
packageName: string
) {
this.protoPath = protoPath;
this.packageName = packageName;
this.addressConfig = address;
this.serviceName = serviceName;
this.init()
}
private init() {
let ipHost = this.addressConfig;
var proto = grpc.load(this.protoPath)[this.packageName];
let Service = proto[this.serviceName]
if (Service === undefined) {
console.error(`${LOG_PRE} service [${this.serviceName}] not define in .proto file`)
return
}
this.grpcClient = new Service(
ipHost.ip + ":" + ipHost.port,
grpc.credentials.createInsecure()
);
this.mapgRpcServiceToSelf();
}
/**
* protocol buffersๅฏไปฅๅฎไนๅ็ง็ฑปๅ็ๆๅก: https://grpc.io/docs/tutorials/basic/node.html
* ๏ผ1๏ผไธไธช ็ฎๅ RPC ๏ผ ๅฎขๆท็ซฏไฝฟ็จๅญๆ นๅ้่ฏทๆฑๅฐๆๅกๅจๅนถ็ญๅพ
ๅๅบ่ฟๅ๏ผๅฐฑๅๅนณๅธธ็ๅฝๆฐ่ฐ็จไธๆ ทใ
* // Obtains the feature at a given position.
rpc GetFeature(Point) returns (Feature) {}
* ๏ผ2๏ผไธไธช ๆๅกๅจ็ซฏๆตๅผ RPC ๏ผ ๅฎขๆท็ซฏๅ้่ฏทๆฑๅฐๆๅกๅจ๏ผๆฟๅฐไธไธชๆตๅป่ฏปๅ่ฟๅ็ๆถๆฏๅบๅใ
* ๅฎขๆท็ซฏ่ฏปๅ่ฟๅ็ๆต๏ผ็ดๅฐ้้ขๆฒกๆไปปไฝๆถๆฏใไปไพๅญไธญๅฏไปฅ็ๅบ๏ผ้่ฟๅจ ๅๅบ ็ฑปๅๅๆๅ
ฅ stream ๅ
ณ้ฎๅญ๏ผๅฏไปฅๆๅฎไธไธชๆๅกๅจ็ซฏ็ๆตๆนๆณใ
* // Obtains the Features available within the given Rectangle. Results are
// streamed rather than returned at once (e.g. in a response message with a
// repeated field), as the rectangle may cover a large area and contain a
// huge number of features.
rpc ListFeatures(Rectangle) returns (stream Feature) {}
* ๏ผ3๏ผไธไธช ๅฎขๆท็ซฏๆตๅผ RPC ๏ผ ๅฎขๆท็ซฏๅๅ
ฅไธไธชๆถๆฏๅบๅๅนถๅฐๅ
ถๅ้ๅฐๆๅกๅจ๏ผ
ๅๆ ทไนๆฏไฝฟ็จๆตใไธๆฆๅฎขๆท็ซฏๅฎๆๅๅ
ฅๆถๆฏ๏ผๅฎ็ญๅพ
ๆๅกๅจๅฎๆ่ฏปๅ่ฟๅๅฎ็ๅๅบใ้่ฟๅจ ่ฏทๆฑ ็ฑปๅๅๆๅฎ stream ๅ
ณ้ฎๅญๆฅๆๅฎไธไธชๅฎขๆท็ซฏ็ๆตๆนๆณใ
// Accepts a stream of Points on a route being traversed, returning a
// RouteSummary when traversal is completed.
rpc RecordRoute(stream Point) returns (RouteSummary) {}
* ๏ผ4๏ผ ไธไธช ๅๅๆตๅผ RPC ๆฏๅๆนไฝฟ็จ่ฏปๅๆตๅปๅ้ไธไธชๆถๆฏๅบๅใไธคไธชๆต็ฌ็ซๆไฝ๏ผ
ๅ ๆญคๅฎขๆท็ซฏๅๆๅกๅจๅฏไปฅไปฅไปปๆๅๆฌข็้กบๅบ่ฏปๅ๏ผๆฏๅฆ๏ผ ๆๅกๅจๅฏไปฅๅจๅๅ
ฅๅๅบๅ็ญๅพ
ๆฅๆถๆๆ็ๅฎขๆท็ซฏๆถๆฏ๏ผๆ่
ๅฏไปฅไบคๆฟ็่ฏปๅๅๅๅ
ฅๆถๆฏ๏ผๆ่
ๅ
ถไป่ฏปๅ็็ปๅใ
ๆฏไธชๆตไธญ็ๆถๆฏ้กบๅบ่ขซ้ข็ใไฝ ๅฏไปฅ้่ฟๅจ่ฏทๆฑๅๅๅบๅๅ stream ๅ
ณ้ฎๅญๅปๅถๅฎๆนๆณ็็ฑปๅใ
// Accepts a stream of RouteNotes sent while a route is being traversed,
// while receiving other RouteNotes (e.g. from other users).
rpc RouteChat(stream RouteNote) returns (stream RouteNote) {}
*/
private mapgRpcServiceToSelf() {
let self = this;
Object.keys(Object.getPrototypeOf(self.grpcClient)).forEach(function(
functionName
) {
const originalFunction = self.grpcClient[functionName];
//ๅฆๆๆฏๆๅกๅจๆฅๅฃๅฝๆฐ๏ผๆ ๅฐๅฐๅฝๅๅฏน่ฑก
if (
originalFunction.requestStream !== undefined &&
originalFunction.responseStream !== undefined
) {
//ๅคๆญๅฝๅๆๅกๆฅๅฃ็็ฑปๅ
const genericFunctionSelector =
(originalFunction.requestStream ? 2 : 0) |
(originalFunction.responseStream ? 1 : 0);
let genericFunctionName;
switch (genericFunctionSelector) {
case 0:
//็ฎๅ RPC
genericFunctionName = "makeUnaryRequest"
self[functionName] = UnaryRequest.makeUnaryRequestunction(self.grpcClient, originalFunction)
break
case 1:
// ไธไธช ๆๅกๅจ็ซฏๆตๅผ RPC
self[functionName] = originalFunction
break
case 2:
//ไธไธช ๅฎขๆท็ซฏๆตๅผ RPC
self[functionName] = originalFunction
break
case 3:
//ไธไธช ๅๅๆตๅผ RPC
self[functionName] = originalFunction
break
}
console.log(`${LOG_PRE} find service ${functionName} `)
}
});
}
}
//็ฌฌไธ็ง ็ฎๅ RPC ๏ผๅฎขๆท็ซฏ้ๅฎ็ฐPromiseๆนๅผ่ฐ็จ
class UnaryRequest {
private client: any;
private originalFunction: Function;
constructor(client, original_function) {
this.client = client;
this.originalFunction = original_function;
}
//ๅ้ๆฐๆฎๅฐๆๅกๅจ็ซฏ
sendMessage(content = {}) {
return new Promise((resolve, reject) => {
this.originalFunction.call(this.client, content, function(
error,
response
) {
if (error) {
reject(error);
} else {
resolve(response);
}
});
});
}
static makeUnaryRequestunction(client, originalFunction): Function {
return function () {
return new UnaryRequest(client, originalFunction);
}
}
}
<file_sep>/lib/types/YSRpcService.d.ts
/****************************************************************************
** ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: RPCๅๅธ
***************************************************************************/
import { RpcConfig } from "./YSRpcConfig";
export interface RpcService {
serviceName: string;
object: any;
}
/**
* RPCๆๅกๅจๅฏๅจ็จๅบ
*
* @export
* @abstract
* @class RPCStartup
*/
export declare class RPCStartup {
private server;
private rpclist;
private packageName;
private protoPath;
private addressConfig;
/**
*
* @param adrees
= * @param protoPath .proto file ่ทฏๅพ
* @param packageName proto่ฏดๆๆไปถไธญpackageๅ็งฐ
*/
constructor(address: RpcConfig, protoPath: string, packageName: string);
private findService;
/**
* ๅๅธๆๅก
*/
publish(): void;
/**
* ๆทปๅ ๅๅธๅฏน่ฑก
*/
addService(server: RpcService): void;
}
<file_sep>/src/YSRpcConfig.ts
/******************************************************************************
** auth: liukai
** date: 2017/9
** ver : 1.0
** desc: ่ฏดๆ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
export interface RpcConfig {
ip: String,
port: String,
name?: String, //ๆๅกๅจๅ็งฐ
}<file_sep>/demo/src/httpServer.ts
/******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import {YSHttpHandle } from "../../src"
import * as express from "express"
let config1 = {host:"tcp://127.0.0.1:9001", name: 'Test'}
let app = express()
class TestHttpHandle extends YSHttpHandle {
public post_teacher(req, res, next) {
console.log(`post_teacher body: ${req.body}`)
console.log(`post_teacher query:`, req.query)
// console.log('req.paramer==>>', req.params.id)
}
public get_hello_world(req, res) {
console.log(req.query)
console.log('get_hello req.paramer==>>', req.query.id)
res.send('hello world')
}
public delete_hello(req, res) {
console.log(`delete_hello:===>`)
console.log(req.query)
res.send('hello world')
}
}
let http = new TestHttpHandle('/api/v1')
app.set('port', (process.env.PORT || 8080))
http.attach(app)
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get('port'));
});<file_sep>/demo/src/rpcClient.ts
/******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import {RPCClient} from "../../src"
var PROTO_PATH = __dirname + '/protos/helloworld.proto';
var client: any = new RPCClient({ip: '0.0.0.0', port: '50051'},'Greeter', PROTO_PATH, 'helloworld')
client.sayHello().sendMessage({name: 'world'}).then((message) =>{
console.log('Greeting:', message);
})
<file_sep>/lib/types/YSHttpHandle.d.ts
/******************************************************************************
** ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ๅบไบexpressๆกๆถ๏ผๅๅธhttpๆฅๅฃ
******************************************************************************/
import { YSErrorType } from "./YSError";
export declare abstract class YSHttpHandle {
prefix: string;
constructor(prefix: string);
/** app = express()
* httpๅๅธ๏ผ ๅๅธๅฝๆฐๅๆ ผๅผ {Method}_{FunctionName}็ๆนๆณ
* ๅ
ถไธญ: Methodๆฏ http่ฏทๆฑ็ๆนๆณ
* FunctionNameๆฏๆนๆณ็่ทฏๅพ๏ผๆ็ป่ทฏๅพ= prefix/FunctionName, FunctionNameๅฏไปฅๅ
ๅซ'_'็ฌฆๅ๏ผไพๅฆpost_teahcer_add
* 1ใไพๅฆๅฝๆฐpost_teacher() ๅๆ็ปๅๅธ็httpๆฅๅฃๆฏ post /prefix/teacher๏ผ ๅฆๆๅฝๆฐๅไธบpost_teacher_add๏ผๅๆ็ปๅๅธๆฅๅฃๆฏ/prefix/teacher/add
* 2ใๅฝๆฐๅไธ่ฝๅชๆฏ http่ฏทๆฑ็ๆนๆณๅใไพๅฆ
* ๅฝๆฐๅget()๏ผ่ฏฅๅฝๆฐไธไผๅๅธ
*
* @param app
*/
attach(app: any): void;
/**
* ่ฟๅJSONๆ ผๅผๆฐๆฎๅฐๅฎขๆท็ซฏ
* {
* code : 0,
* msg : 'ๆไฝๆๅ',
* data : any
* }
* @param {any} response
* @param {any} errcode
* @param {any} msg
* @param {any} data
* @memberof YSHttpHandle
*/
static sendJSONData(response: any, error: YSErrorType, data?: any): void;
}
<file_sep>/lib/types/YSTable.d.ts
/******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ๅบไบsequelize ORM็็ฎๅๅฐ่ฃ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import * as Sequelize from 'sequelize';
/**
* ่กจๆจกๅ็็ฎก็็ฑป๏ผ่ด่ดฃ่กจๆจกๅไธๆฐๆฎๅบๅๆญฅ
*
* @export
* @class YSDBManager
*/
export declare class YSDBManager {
static readonly Instance: YSDBManager;
tables: YSTable[];
addTable(table: YSTable): number;
/**
* ๅๆญฅๆจกๅๅฐๆฐๆฎๅบ
*
*
* @memberof DBManager
*/
sync(before: () => void): void;
}
/**
* ๆฐๆฎๅบ่กจๆจกๅๅฎไนๅบ็ก็ๅบ็ฑป
*
*/
export declare abstract class YSTable {
model: Sequelize.Model<any, any>;
protected constructor();
/**
* ๅๅปบ Sequelize.Modelๆจกๅ ไพๅฆ
*
protected newModel(): Sequelize.Model<any, any> {
return Mysql.Instance.define('tUser', {
userName: {
type: Sequelize.STRING(20), //ๆฐๆฎ็ฑปๅ
}
})
}
*
* @protected
* @abstract
* @memberof YSTable
*/
protected abstract newModel(): Sequelize.Model<any, any>;
/**
* ่ฟๆฅๆฐๆฎๅบไนๅๆง่ก็ๆไฝ
*
*
* @memberof Table
*/
afterAync(): void;
/**
*
*ๅๆญฅๆฐๆฎไนๅ๏ผๅค็ๆไฝ
*
*
* @memberof Table
*/
beforeAync(): void;
static createModel(): Sequelize.Model<any, any>;
}
<file_sep>/README.md
# node-yourshares
<!-- TOC -->
- [node-yourshares](#node-yourshares)
- [้กน็ฎไป็ป](#้กน็ฎไป็ป)
- [ๅฎ่ฃ
ๆนๅผ](#ๅฎ่ฃ
ๆนๅผ)
- [ไฝฟ็จ่ฏดๆ](#ไฝฟ็จ่ฏดๆ)
- [ๅฟซ้ๅฎไนHttpๆฅๅฃๆๅก](#ๅฟซ้ๅฎไนhttpๆฅๅฃๆๅก)
- [ๅฟซ้ๅฎไนRPCๆๅก็ซฏ](#ๅฟซ้ๅฎไนrpcๆๅก็ซฏ)
<!-- /TOC -->
#### ้กน็ฎไป็ป
ๆ็
งใ ็บฆๅฎไผไบ้
็ฝฎใ็ๅผๅๅๅ๏ผๅฟซ้ๆญๅปบHTTPๆๅก๏ผRPCๆๅก็ๆกๆถไธป่ฆๅ
ๆฌไธๅคงๅๅ่ฝ
1. [ๅฟซ้ๅฎไนHttpๆฅๅฃๆๅก](#ๅฟซ้ๅฎไนHttpๆฅๅฃๆๅก)
2. [ๅฟซ้ๅฎไนRPCๆๅก](#ๅฟซ้ๅฎไนRPCๆๅก)
3. [ๅบไบORM๏ผๅฟซ้ๅฎไน่ช่บซ็ๆฐๆฎๆจกๅ](#ๅบไบORM๏ผๅฟซ้ๅฎไน่ช่บซ็ๆฐๆฎๆจกๅ)
#### ๅฎ่ฃ
ๆนๅผ
```
npm i node-yourshares
```
#### ไฝฟ็จ่ฏดๆ
##### ๅฟซ้ๅฎไนHttpๆฅๅฃๆๅก
ๅฎไนhttpๆๅก๏ผๅช้่ฆ็ปงๆฟYSHttpHandle็ฑปใๆฏๅฆๅๅธ่ทฏๅพไธบ/helloword ็get่ฏทๆฑ, typscriptไปฃ็ ๅฆไธ:
```javascript
import {YSHttpHandle} from "node-yourshares"
import * as express from "express"
let config1 = {host:"tcp://127.0.0.1:9001", name: 'Test'}
let app = express()
class TestHttpHandle extends YSHttpHandle {
public get_helloworld(req, res) {
console.log(req.query)
console.log('get_hello req.paramer==>>', req.query.id)
res.send('hello world')
}
}
let http = new TestHttpHandle()
app.set('port', (process.env.PORT || 8080))
http.attach(app)
app.listen(app.get('port'), () => {
console.log('Node app is running on port', app.get('port'));
})
```
ๅ ็น่ฏดๆ
1. ้่ฆๅๅธ็httpๆฅๅฃๅฝๆฐๅๅฝขๅผๅฟ
้กปๅฝขๅฆ: get_xxx_xxxๆpost_xxx_xxx็ญ;
2. ๆกๆถ่ชๅจ่ฏๅซๅฏน่ฑกไธญไปฅ['post', 'get', 'delete', 'all']ๅผๅคด็ๆนๆณ่ฟ่กๅๅธใ
3. API่ฏทๆฑ็ๆนๅผ๏ผไปฅๅฝๆฐๅๅผๅคด็['post', 'get', 'delete', 'all']ไธบๆ ่ฏใๆฏๅฆ้่ฆๅๅธpost่ฏทๆฑ็ๆนๆณใๅๅฏไปฅๅ็งฐไธบpost_xx็ๆนๆณใ
4. api็่ทฏๅพๆ นๆฎๆนๆณๅๆฅๅฎไนใๆฏๅฆๆนๆณ post_hello_world๏ผๅฎๅฎ้
่กจ็คบ็ๆๆๆฏใๅๅธpostๆฅๅฃ๏ผ่ทฏๅพไธบ/hello/world
##### ๅฟซ้ๅฎไนRPCๆๅก็ซฏ
node-yourshares็RPCๆๅกๆฏ้่ฟ[gRPC][1]ๅฎ็ฐ็ใๆฅไธๆฅ้่ฟ็ฎๅไพๅญๆฅ่ฏดๆๅฆไฝ่ฟ่กRPCๆๅก็ซฏๅๆถ่ดน็ซฏไปฃ็ ็ผๅใ
>**ๅฎไนRPCๆๅกๅจ**
้ฆๅ
๏ผๅฎไนRPCๆๅกๅจ้ฆๅ
้่ฆ็ผๅ[protobuf][2]ๆไปถ
```
syntax = "proto3";
option java_multiple_files = true;
option java_package = "io.grpc.examples.helloworld";
option java_outer_classname = "HelloWorldProto";
option objc_class_prefix = "HLW";
package helloworld;
// The greeting service definition.
service Greeter {
// Sends a greeting
rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// The request message containing the user's name.
message HelloRequest {
string name = 1;
}
// The response message containing the greetings
message HelloReply {
string message = 1;
}
```
>**ๆๅก็ซฏไปฃ็ **
```
import {RPCStartup} from "../../src"
var PROTO_PATH = __dirname + '/protos/helloworld.proto';
/**/
class HelloRpc {
/**
* Implements the SayHello RPC method.
*/
sayHello(call, callback) {
callback(null, {message: 'Hello ' + call.request.name});
}
}
var rpc = new RPCStartup({ip: '0.0.0.0', port: '50051'}, PROTO_PATH, 'helloworld')
rpc.addService({serviceName: 'Greeter', object: new HelloRpc()})
rpc.publish()
```
ๅ
ณไบRPCStartup็ฎๅ่ฏดๆ
- ้่ฟRPCStartup#addServiceๅๅธ.protoๆ่ฟฐ็ๆฅๅฃ๏ผไธๅจๆ่ฟฐๆไปถไธญ็ๆฅๅฃๅ"_"ๅผๅคด็ๆฅๅฃไธไผ่ฟ่กๅๅธใ
- .protoๅฏไปฅๅฎไนๅ็งๆๅกๆฅๅฃ๏ผ1ใ็ฎๅ RPC๏ผ2ใ ๆๅกๅจ็ซฏๆตๅผ RPC๏ผ3ใๅฎขๆท็ซฏๆตๅผ RPC๏ผ4ใๅๅๆตๅผ RPCใๅ็งๆๅกๅ
ทไฝๅฆไฝๅฎ็ฐRPCๆฅๅฃ่ฏทๅ็
ง[gRPC-Node][3]
>**ๆถ่ดน็ซฏไปฃ็ **
```
import {RPCClient} from "../../src"
var PROTO_PATH = __dirname + '/protos/helloworld.proto';
var client: any = new RPCClient({ip: '0.0.0.0', port: '50051'},'Greeter', PROTO_PATH, 'helloworld')
client.sayHello().sendMessage({name: 'world'}).then((message) =>{
console.log('Greeting:', message);
})
```
- ๆถ่ดน็ซฏ็ดๆฅ้่ฟๅๅปบRPCClientๅฎไพๅฐฑๅฏไปฅๆถ่ดนๆๅก็ซฏ็ๆนๆณใ
- ๅฆๆๆฅๅฃๆฏ็ฎๅRPC๏ผๅ้่ฟPromise่ฐ็จๆฅๅฃใ
- ๅ
ณไบๆดๅคๅ็ง็ฑปๅ็ๆฅๅฃ๏ผๆถ่ดน็ซฏไปฃ็ ็ผๅ๏ผๅ็
ง[gRPC-Node-Detail][4]
[1]:https://grpc.io
[2]:https://developers.google.com/protocol-buffers/
[3]:https://grpc.io/docs/quickstart/node.html
[4]:https://grpc.io/docs/tutorials/basic/node.html
<file_sep>/src/index.ts
/******************************************************************************
** ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
******************************************************************************/
import String from'./String+Extension'
import { RPCStartup ,RpcService } from "./YSRpcService"
import { YSHttpHandle } from "./YSHttpHandle"
import { YSErrorType, YSErrorTabel, YSPurifyMessage } from "./YSError"
import { RpcConfig} from "./YSRpcConfig"
import { RPCClient} from "./YSRpcClient"
import { YSDBManager, YSTable} from "./YSTable"
import * as Sequelize from 'sequelize';
import * as express from "express"
export {
express,
Sequelize,
String,
RPCStartup,
RPCClient,
RpcService,
RpcConfig,
YSHttpHandle,
YSErrorType,
YSErrorTabel,
YSPurifyMessage,
YSDBManager,
YSTable
};<file_sep>/lib/types/String+Extension.d.ts
declare const _default: {};
/******************************************************************************
** ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
******************************************************************************/
export default _default;
declare global {
interface String {
hasPrefix(str: String): boolean;
hasSuffix(suffix: String): boolean;
}
}
<file_sep>/src/YSTable.ts
/******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ๅบไบsequelize ORM็็ฎๅๅฐ่ฃ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import * as Sequelize from 'sequelize';
/**
* ่กจๆจกๅ็็ฎก็็ฑป๏ผ่ด่ดฃ่กจๆจกๅไธๆฐๆฎๅบๅๆญฅ
*
* @export
* @class YSDBManager
*/
export class YSDBManager {
public static readonly Instance: YSDBManager = new YSDBManager();
tables: YSTable[] = []
public addTable(table: YSTable): number {
let index = this.tables.indexOf(table)
if (index >= 0) {
return index
} else {
return this.tables.push(table) - 1
}
}
/**
* ๅๆญฅๆจกๅๅฐๆฐๆฎๅบ
*
*
* @memberof DBManager
*/
public sync(before:()=>void) {
typeof before === 'function' && before();
this.tables.forEach(element => {
element.beforeAync()
element.model.sync({ force: false }).then(function () {
element.afterAync()
});
});
}
}
/**
* ๆฐๆฎๅบ่กจๆจกๅๅฎไนๅบ็ก็ๅบ็ฑป
*
*/
export abstract class YSTable {
public model: Sequelize.Model<any, any>;
protected constructor() {
}
/**
* ๅๅปบ Sequelize.Modelๆจกๅ ไพๅฆ
*
protected newModel(): Sequelize.Model<any, any> {
return Mysql.Instance.define('tUser', {
userName: {
type: Sequelize.STRING(20), //ๆฐๆฎ็ฑปๅ
}
})
}
*
* @protected
* @abstract
* @memberof YSTable
*/
protected abstract newModel(): Sequelize.Model<any, any>
/**
* ่ฟๆฅๆฐๆฎๅบไนๅๆง่ก็ๆไฝ
*
*
* @memberof Table
*/
public afterAync() {
console.info("Table", "afterAync")
};
/**
*
*ๅๆญฅๆฐๆฎไนๅ๏ผๅค็ๆไฝ
*
*
* @memberof Table
*/
public beforeAync() {
console.info("Table ", "beforeAync")
}
public static createModel(): Sequelize.Model<any, any> {
let table = Object.create(this.prototype);
table.model = table.newModel()
YSDBManager.Instance.addTable(table);
return table.model
}
}<file_sep>/gulpfile.js
/**
* Created by niupark on 2017/5/5.
*/
var gulp = require('gulp');
// var ts = require('gulp-typescript');
// var sourcemaps = require('gulp-sourcemaps');
var shell = require('gulp-shell');
var clean = require('gulp-clean');
// var tsProject = ts.createProject('tsconfig.json');
gulp.task("clean", function(){
return gulp.src('./lib/')
.pipe(clean());
})
gulp.task('copy', ['clean'], function() {
return gulp.src('configes/*.json')
.pipe(gulp.dest('dist/configes/'));
});
/*************************************
*ๅๆ ท็้
็ฝฎ๏ผ้่ฟ gulp-sourcemaps ็ๆ็mapๆไปถ๏ผๅจvscodeไธญ ๆ ๆณdebug๏ผๅๅ ไธๆ
*็ฐๅจไฝฟ็จtscๅฝไปค็ดๆฅ็ผ่ฏtsๆไปถ
*/
// gulp.task('compile' ,['copy'], function () {
// return tsProject.src()
// .pipe(sourcemaps.init())
// .pipe(tsProject())
// .pipe(sourcemaps.write())
// .pipe(gulp.dest('dist'));
// });
gulp.task('compile' ,['copy'], shell.task([
'tsc'
]));
var JSCOVERAGE = './node_modules/.bin/istanbul cover _mocha ./dist/src/tests/**/*.js';
var MOCHA = './node_modules/.bin/mocha -R spec -t 10000 ./dist/src/tests/**/*.js';
gulp.task('test', shell.task([
MOCHA
]));
gulp.task('test-cov', shell.task([
JSCOVERAGE,
MOCHA
]));<file_sep>/src/YSError.ts
/******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
export interface YSErrorType {
messages: {
'zh-CN': string,
'en-US'?: string
}|String,
code: number,
locale?: string,
}
/**
* ้่ฏฏๅฎไน ไพๅฆ
*
* class MyError1 extends YSErrorTabel{
sucesse = {
messages : {
'zh-CN': 'ๆๅ',
'en-US': 'ๅคฑ่ดฅ'
},
code : 0,
locale : 'zh-CN'
}
} ๆ่
class MyError2 extends YSErrorTabel{
sucesse = {
messages : 'ๆๅ',
code : 0,
}
}
*
* @export
* @class YSErrorTabel
*/
export class YSErrorTabel{
[field: string]:YSErrorType
}
export function YSPurifyMessage(error:YSErrorType, i18n?:string):string {
if (typeof error.messages === 'string'){
return error.messages
}else{
return error.messages[i18n || error.locale] || error.messages[error.locale];
}
}
<file_sep>/src/YSHttpHandle.ts
/******************************************************************************
** ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ๅบไบexpressๆกๆถ๏ผๅๅธhttpๆฅๅฃ
******************************************************************************/
import { YSErrorType, YSErrorTabel, YSPurifyMessage } from "./YSError"
let httpMethod = ['post', 'get', 'delete', 'all']
/**
* httpๅๅธ๏ผ ๅๅธๅฝๆฐๅๆ ผๅผ {Method}_{FunctionName}็ๆนๆณ
* ๅ
ถไธญ: Methodๆฏ http่ฏทๆฑ็ๆนๆณ
* FunctionNameๆฏๆนๆณ็่ทฏๅพ๏ผๆ็ป่ทฏๅพ= prefix/FunctionName, FunctionNameไธ่ฝๅ
ๅซ'_'็ฌฆๅ๏ผไพๅฆpost_teahcer_addๆฏ้ๆณๅฝๅ๏ผไธไผๆ็ปๅทฒhttpๆฅๅฃๅๅธ
* 1ใไพๅฆๅฝๆฐpost_teacher() ๅๆ็ปๅๅธ็httpๆฅๅฃๆฏ post /prefix/teacher
* 2ใๅฝๆฐๅไนๅฏไปฅๅชๆฏ http่ฏทๆฑ็ๆนๆณๅใไพๅฆ
* ๅฝๆฐๅget()๏ผๅๆ็ปๅๅธ็httpๆฅๅฃๆฏ get /prefix
*
* @export
* @abstract
* @class YSHttpHandle
*/
//่ฏทๆฑ็ๅบๆฌไฟกๆฏ
function reject(func: Function): Function {
return function(req, res, next) {
// let message = `ๆถๅฐ่ฏทๆฑ-> ${req.originalUrl}`
// if(req.body != null) {
// message += (typeof req.body === 'object')? `ๆฐๆฎไฝ: \n ${JSON.stringify(req.body)}`:`ๆฐๆฎไฝ: \n ${req.body}`
// }
// console.log(message)
func(req, res, next)
}
}
export abstract class YSHttpHandle {
prefix = ""
constructor(prefix: string) {
if (!prefix.hasPrefix('/')) {
throw new Error(`${prefix} ๏ผpath is invalid.`);
}
//็กฎไฟprefix '/'็ปๅฐพ
if (prefix.hasSuffix('/')) {
this.prefix = prefix
} else {
this.prefix = prefix + '/'
}
}
/** app = express()
* httpๅๅธ๏ผ ๅๅธๅฝๆฐๅๆ ผๅผ {Method}_{FunctionName}็ๆนๆณ
* ๅ
ถไธญ: Methodๆฏ http่ฏทๆฑ็ๆนๆณ
* FunctionNameๆฏๆนๆณ็่ทฏๅพ๏ผๆ็ป่ทฏๅพ= prefix/FunctionName, FunctionNameๅฏไปฅๅ
ๅซ'_'็ฌฆๅ๏ผไพๅฆpost_teahcer_add
* 1ใไพๅฆๅฝๆฐpost_teacher() ๅๆ็ปๅๅธ็httpๆฅๅฃๆฏ post /prefix/teacher๏ผ ๅฆๆๅฝๆฐๅไธบpost_teacher_add๏ผๅๆ็ปๅๅธๆฅๅฃๆฏ/prefix/teacher/add
* 2ใๅฝๆฐๅไธ่ฝๅชๆฏ http่ฏทๆฑ็ๆนๆณๅใไพๅฆ
* ๅฝๆฐๅget()๏ผ่ฏฅๅฝๆฐไธไผๅๅธ
*
* @param app
*/
public attach(app: any) {
console.log(`==============>ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)<================`)
let self = this
let prototype = Object.getPrototypeOf(this)
if (prototype != null) {
Object.getOwnPropertyNames(prototype).forEach(httpFuncName => {
let nameArray = httpFuncName.split('_')
if (nameArray.length >= 2 && httpMethod.indexOf(nameArray[0].toLowerCase()) >= 0) {
let path = self.prefix + nameArray[1]
for (var index = 2; index < nameArray.length; index++) {
var element = nameArray[index];
path += '/' + element
}
app[nameArray[0].toLowerCase()](path, prototype[httpFuncName])
console.log(`httpๆฅๅฃๅๅธ: ${nameArray[0]} -> ${path}`)
}
})
}
}
/**
* ่ฟๅJSONๆ ผๅผๆฐๆฎๅฐๅฎขๆท็ซฏ
* {
* code : 0,
* msg : 'ๆไฝๆๅ',
* data : any
* }
* @param {any} response
* @param {any} errcode
* @param {any} msg
* @param {any} data
* @memberof YSHttpHandle
*/
public static sendJSONData (response, error: YSErrorType, data?: any) {
let obj:any = {};
obj.code = error.code;
obj.msg = YSPurifyMessage(error);
if (data != null) {
obj.data = data;
}
console.info(response.req.originalUrl + ' ่ฟๅๆฐๆฎๅ
:' + JSON.stringify(obj));
response.set('Content-Type', 'application/json')
response.send(obj);
}
}
<file_sep>/demo/src/rpcServer.ts
/******************************************************************************
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
** Copyright ยฉ 2017ๅนด ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn). All rights reserved
******************************************************************************/
import {RPCStartup} from "../../src"
var PROTO_PATH = __dirname + '/protos/helloworld.proto';
/**/
class HelloRpc {
/**
* Implements the SayHello RPC method.
*/
sayHello(call, callback) {
callback(null, {message: 'Hello ' + call.request.name});
}
sayHello2(call, callback) {
callback(null, {message: 'Hello ' + call.request.name});
}
static AAAA() {
console.log('')
}
}
var a = new HelloRpc()
a['xxx'] = function () {
}
a['bbb'] = 1
console.log(Object.getOwnPropertyNames(Object.getPrototypeOf(a)))
console.log(Object.getOwnPropertyNames(a))
console.log(Object.keys(a))
console.log(Object.keys((Object.getPrototypeOf(a))))
console.log(Object.getOwnPropertyNames(HelloRpc))
var rpc = new RPCStartup({ip: '0.0.0.0', port: '50051'}, PROTO_PATH, 'helloworld')
rpc.addService({serviceName: 'Greeter', object: new HelloRpc()})
rpc.publish()
<file_sep>/src/YSRpcService.ts
/****************************************************************************
** ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: RPCๅๅธ
***************************************************************************/
// import hprose = require('hprose');
import { RpcConfig} from "./YSRpcConfig"
import * as grpc from "grpc"
//logๆฅๅฟๅ็ผ
let LOG_PRE = 'RPC Service Log-->>>'
export interface RpcService {
serviceName: string, //ๅฏนๅบprotoๆไปถไธญservice ๅ็งฐ
object: any //ๅ
ณ่็็ฑปๅฏน่ฑก
}
/**
* RPCๆๅกๅจๅฏๅจ็จๅบ
*
* @export
* @abstract
* @class RPCStartup
*/
export class RPCStartup {
private server: any
private rpclist = []
private packageName: string
private protoPath: string
private addressConfig: RpcConfig
/**
*
* @param adrees
= * @param protoPath .proto file ่ทฏๅพ
* @param packageName proto่ฏดๆๆไปถไธญpackageๅ็งฐ
*/
constructor(address: RpcConfig, protoPath: string, packageName: string) {
this.protoPath = protoPath
this.packageName = packageName
this.addressConfig = address
}
//่ทๅๆๅกๅๅ
ณ่็ๅฏน่ฑก
private findService(name: string): RpcService {
for(var i=0; i<this.rpclist.length; i++) {
if (this.rpclist[i].serviceName === name) {
return this.rpclist[i]
}
}
}
/**
* ๅๅธๆๅก
*/
public publish() {
//่ทๅIPไฟกๆฏ
let ipHost = this.addressConfig
this.server = new grpc.Server()
var proto = grpc.load(this.protoPath)[this.packageName]
//protoๅฏน่ฑกmapไบ.protoๆไปถไฟกๆฏ
//่ทๅprotoๅฏน่ฑกไธญ็ฑปๅไธบServiceClientๅฏน่ฑกๅญๅจserviceๅฑๆงใ่ฟ็งๅฏน่ฑกๅฎ้
ไธๅฏนๅบ.protoไธญ็service่็น
//้ๅproto่ทๅservice
console.log(`==============>ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)<================\n>>>${ipHost.ip}:${ipHost.port}<<< publish api`)
let self = this
Object.getOwnPropertyNames(proto).forEach(propertyName => {
// if (typeof proto[property]. === 'function' && proto[property].name === 'ServiceClient'){ //้่ฟๅคๆญๆนๆณๅๆฅ่ทๅserviceๅฏน่ฑก
//้่ฟๅคๆญๆฏๅฆๅญๅจserviceๅฑๆงๆฅ่ทๅserviceๅฏน่ฑก
if (proto[propertyName].service !== undefined){
let serviceObject = self.findService(propertyName)
console.log(`${LOG_PRE} service ${propertyName} publish api [Begin]`)
if (serviceObject !== undefined && serviceObject.object !== undefined) {
let apiObject = serviceObject.object
var routerObject = {}
//Object.keys(Object.getPrototypeOf(apiObject))
//่ทๅ่ชๅทฑๆฌ่บซ็ๅฑๆง
Object.getOwnPropertyNames(apiObject).forEach(rpcFuncName => {
//ๅๅธapiObject ๆนๆณ
//ๆๆๆชๅจ.protoไธญๅฎไนๅ_ๅผๅคด็ๆนๆณไธไผๅๅธ
// console.log(`${LOG_PRE} find object ${serviceObject.serviceName} function: ${rpcFuncName}`)
if (proto[propertyName].service[rpcFuncName] !== undefined
&& typeof apiObject[rpcFuncName] === 'function'
&& !rpcFuncName.hasPrefix('_')){
console.log(`${LOG_PRE} ${serviceObject.serviceName} ๅๅธๆฅๅฃ ${rpcFuncName}`)
routerObject[rpcFuncName] = apiObject[rpcFuncName]
}
})
//่ทๅๅๅ่ฟไธ็ๆนๆณ
Object.getOwnPropertyNames(Object.getPrototypeOf(apiObject)).forEach(rpcFuncName => {
//ๅๅธapiObject ๆนๆณ
//ๆๆๆชๅจ.protoไธญๅฎไนๅ_ๅผๅคด็ๆนๆณไธไผๅๅธ
// console.log(`${LOG_PRE} find object ${serviceObject.serviceName} function: ${rpcFuncName}`)
if (rpcFuncName !== 'constructor' && proto[propertyName].service[rpcFuncName] !== undefined
&& typeof apiObject[rpcFuncName] === 'function'
&& !rpcFuncName.hasPrefix('_')){
console.log(`${LOG_PRE} ${serviceObject.serviceName} ๅๅธๆฅๅฃ ${rpcFuncName}`)
routerObject[rpcFuncName] = apiObject[rpcFuncName]
}
})
//grpcๅๅธๆๅก
self.server.addService(proto[propertyName].service, routerObject)
}else{
//ๆๅกๆฒกๆๆพๅฐๅ
ณ่็ๅฏน่ฑก
console.error(`${LOG_PRE} ${propertyName} have no map Object!!!!`)
}
console.log(`${LOG_PRE} service ${propertyName} publish api [End]`)
}
})
this.server.bind(ipHost.ip+ ':'+ ipHost.port, grpc.ServerCredentials.createInsecure());
this.server.start();
}
//
/**
* ๆทปๅ ๅๅธๅฏน่ฑก
*/
public addService(server: RpcService) {
this.rpclist.push(server)
}
}
<file_sep>/src/String+Extension.ts
/******************************************************************************
** ๅฐงๅฐไฟกๆฏ็งๆ(wwww.yourshares.cn)
** auth: liukai
** date: 2017/7
** ver : 1.0
** desc: ่ฏดๆ
******************************************************************************/
//ๆฉๅฑString ้่ฆๅ
ๅฃฐๆStringไธบๅ
้จๆจกๅ๏ผไธ็ถๆ ๆณ็ผ่ฏ๏ผ ๅ็
งhttps://basarat.gitbooks.io/typescript/content/docs/types/lib.d.ts.html
// Ensure this is treated as a module
export default {}
declare global {
interface String {
hasPrefix(str: String): boolean
hasSuffix(suffix: String): boolean
}
}
String.prototype.hasSuffix = function (suffix: string): boolean {
var str: string = this;
return str && str.indexOf(suffix, str.length - suffix.length) !== -1;
}
String.prototype.hasPrefix = function (prefix: string) {
var str: string = this;
return str.slice(0, prefix.length) == prefix;
}
|
45dd63fe8c2dc8f5b6860acceb2c33f9194f15ff
|
[
"Markdown",
"TypeScript",
"JavaScript"
] | 20 |
TypeScript
|
gb-6k-house/node-yourshares
|
5ce7f504722f89d0a1dddad4e213abb56cc3d018
|
0a984adb8727c2f3112af3ac75929f45c089a427
|
refs/heads/master
|
<repo_name>Kevinvillalpando1998/dado<file_sep>/Dado/Dado/Dado.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dado
{
class Dado
{
private int[] vec;
public Dado()
{
vec = new int[6];
}
Random rmd = new Random();
Random rnm = new Random();
public void lanzardado()
{
int dado;
dado = rmd.Next(1, 7);
}
public void lanzar1()
{
}
public void lanzar()
{
int p;
p = rmd.Next(1, 7);
if (p == 1)
{
vec[0] += 1;
}
else if (p == 2)
{
vec[1] += 1;
}
else if (p == 3)
{
vec[2] += 1;
}
else if (p == 4)
{
vec[3] += 1;
}
else if (p == 5)
{
vec[4] += 1;
}
else if (p== 6)
{
vec[5] += 1;
}
}
public override string ToString()
{
string lil = "";
for (int c = 0; c < 6; c++)
{
lil += "cara " + (c + 1) + " cayo " + vec[c] + " veces"+ Environment.NewLine;
}
return lil;
}
}
}
<file_sep>/Dado/Dado/Sumas.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Dado
{
class Sumas
{
private int[] dado;
public Sumas()
{
dado = new int[11];
}
Random rdm = new Random();
public void lanzar()
{
int n1, n2,r;
n1 = rdm.Next(1, 7);
n2 = rdm.Next(1, 7);
r = n1 + n2;
switch (r)
{
case 2:
dado[0] += 1;
break;
case 3:
dado[1]+= 1;
break;
case 4:
dado[2] += 1;
break;
case 5:
dado[3] += 1;
break;
case 6:
dado[4] += 1;
break;
case 7:
dado[5] += 1;
break;
case 8:
dado[6] += 1;
break;
case 9:
dado[7] += 1;
break;
case 10:
dado[8] += 1;
break;
case 11:
dado[9] += 1;
break;
case 12:
dado[10] += 1;
break;
}
}
public override string ToString()
{
string lil = "";
for (int c=0; c<11; c++)
{
lil += "el resultado " + (c + 2) + "salio " + dado[c] + " veces" + Environment.NewLine;
}
return lil;
//return "2 se repite " + resultado1 + "veces" +Environment.NewLine + "3 se repite " + resultado2 + "veces" + Environment.NewLine + "4 se repite " + resultado3 + "veces" + Environment.NewLine + "5 se repite " + resultado4 + "veces" + Environment.NewLine + "6 se repite " + resultado5 + "veces" + Environment.NewLine + "7 se repite " + resultado6 + "veces" + Environment.NewLine + "8 se repite " + resultado7 + "veces" + Environment.NewLine + "9 se repite " + resultado8 + "veces" + Environment.NewLine + "10 se repite " + resultado9 + "veces" + Environment.NewLine + "11 se repite " + resultado10 + "veces" + Environment.NewLine + "12 se repite " + resultado11 + "veces" + Environment.NewLine;
}
}
}
<file_sep>/Dado/Dado/3er boton.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
namespace Dado
{
class _3er_boton
{
private int[] dado;
private int valor,n1,n2;
public _3er_boton()
{
dado = new int[11];
Thread.Sleep(1);
}
Random rdm = new Random(DateTime.Now.Millisecond);
Random rnd = new Random(DateTime.Now.Millisecond);
public void lanzardado1()
{
n1= rdm.Next(1, 7);
n2= rnd.Next( 1,7);
valor = n1 + n2;
}
public void comparar()
{
switch (valor)
{
case 2:
dado[0] += 1;
break;
case 3:
dado[1] += 1;
break;
case 4:
dado[2] += 1;
break;
case 5:
dado[3] += 1;
break;
case 6:
dado[4] += 1;
break;
case 7:
dado[5] += 1;
break;
case 8:
dado[6] += 1;
break;
case 9:
dado[7] += 1;
break;
case 10:
dado[8] += 1;
break;
case 11:
dado[9] += 1;
break;
case 12:
dado[10] += 1;
break;
}
}
public override string ToString()
{
string cadena = "";
for (int c= 0; c<11; c++)
{
cadena += "el resultado " + (c + 2) + "cayo " + dado[c]+ Environment.NewLine;
}
return cadena;
}
}
}
<file_sep>/Dado/Dado/Form1.cs
๏ปฟusing System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Dado
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
Dado dado1,dado2,dado3;
_3er_boton dosdados;
private void button1_Click(object sender, EventArgs e)
{
dado1 = new Dado();
for (int c=0; c<100; c++)
{
dado1.lanzar();
}
txtmontrar.Text = dado1.ToString();
}
Sumas dado;
private void button2_Click(object sender, EventArgs e)
{
dado = new Sumas();
for ( int c=0; c<100; c++)
{
dado.lanzar();
}
txtmontrar.Text = dado.ToString();
}
private void button3_Click(object sender, EventArgs e)
{
txtmontrar.Clear();
dosdados = new _3er_boton();
for ( int c=0; c<100; c++)
{
dosdados.lanzardado1();
dosdados.comparar();
}
txtmontrar.Text += dosdados.ToString();
}
}
}
|
d38173a91306589f720054a7946005f37ff5d313
|
[
"C#"
] | 4 |
C#
|
Kevinvillalpando1998/dado
|
1e8ff7cedb42d1b4b2e73c669f1d01e0086b12d5
|
568f01267415fd560b735c232f9ae73fc00b41a3
|
refs/heads/master
|
<file_sep>import galois from '@guildofweavers/galois'
export default class Attribute {
number: number
name: string
field: galois.FiniteField
getHash: ({ name, number } : {name: string, number: number}) => bigint
constructor (name: string, number: number, field: galois.FiniteField, getHash: ({ name, number } : {name: string, number: number}) => bigint) {
this.name = name
this.number = number
this.field = field
this.getHash = getHash
}
/**
* Returns a hashed value based on name and number
* This value is used in the database as the primary key, and will be used as the attribute used for comparison.
* Hash function and field is injected into this layer from the controller layer
*/
public getHashedValue = () => {
return this.field.prng(this.getHash({ name: this.name, number: this.number }))
}
}
<file_sep>import IdataRepo from './IDataRepo'
import { query } from '../../../common/dataAccess/dbAccess'
import BlindedAttributes from '../entities/blindedAttributes'
// Accesses data from local database or cloud service
export default class DataRepo implements IdataRepo {
public async getBlindedAttributes (clientID: string) : Promise<BlindedAttributes> {
console.log(clientID)
const queryString = 'select blinded_vectors from cloud.clients where clientid = $1'
const result = await query(queryString, [clientID])
if (result.rows) {
const blindedAttributes = result.rows[0].blinded_vectors
return new BlindedAttributes(blindedAttributes)
} else {
throw new Error('No such client found')
}
}
}
<file_sep>// export const cloudOrigin = 'http://eopsicloud-env-1.eba-bairbewe.ap-southeast-1.elasticbeanstalk.com'
export const cloudOrigin = 'https://silly-panda-38.loca.lt'
<file_sep>import IattributesRepo from './IAttributesRepo'
import CloudConfig from '../entities/cloudConfig'
import CLOUD_CONFIG from '../../CLOUD_CONFIG' // Cloud config
import { query } from '../../../common/dataAccess/dbAccess'
// Accesses data from local database or cloud service
export default class AttributesRepo implements IattributesRepo {
public saveAttributesLocal = async (clientID: string, url: string, attributes: string) => {
const queryString = `insert into cloud.clients (clientid, blinded_vectors, url) values ($1, $2, $3)
on conflict (clientid) do update
set blinded_vectors = excluded.blinded_vectors
,url = excluded.url`
query(queryString, [clientID, attributes, url])
}
private checkIfUrlPresent = async ({ url }: { url: string }) => {
const queryString = 'select * from cloud.clients where url = $1'
const result = await query(queryString, [url])
return !!result.rows.length
}
public async getCloudConfig () : Promise<CloudConfig> {
const { NUMBER_OF_BINS, MAXIMUM_LOAD, finiteFieldNum, smallFiniteFieldNum } = CLOUD_CONFIG
const vectorX = []
for (let i = 1; i <= 2 * MAXIMUM_LOAD + 1; i++) {
vectorX.push(BigInt(i))
}
return new CloudConfig(NUMBER_OF_BINS, MAXIMUM_LOAD, finiteFieldNum, smallFiniteFieldNum, vectorX)
}
}
<file_sep>import IconfigRepo from './IconfigRepo'
import { query } from '../../../common/dataAccess/dbAccess'
import { DatabaseError } from '../../../common/Error'
// Accesses data from local database or cloud service
export default class ConfigRepo implements IconfigRepo {
public async getMasterKey () : Promise<string> {
try {
const queryString = 'select value from client.config where key = \'masterkey\''
const result = await query(queryString)
return result.rows[0].value
} catch (e) {
throw new DatabaseError(e.message)
}
}
public async saveMasterKey (mk: string) : Promise<void> {
try {
const queryString = 'insert into client.config (key, value) values ($1, $2) on conflict do nothing' // This assumes that the master key will not be updated. Do an upsert if we want it to be updated
await query(queryString, ['masterkey', mk])
} catch (e) {
throw new DatabaseError(e.message)
}
}
public async saveClientID (clientID: string) : Promise<void> {
try {
const queryString = 'insert into client.config (key, value) values ($1, $2) on conflict do nothing' // This assumes that the master key will not be updated. Do an upsert if we want it to be updated
await query(queryString, ['clientID', clientID])
} catch (e) {
throw new DatabaseError(e.message)
}
}
public async getClientID () : Promise<string> {
try {
const queryString = 'select value from client.config where key = \'clientID\''
const result = await query(queryString)
return result.rows[0].value
} catch (e) {
throw new DatabaseError(e.message)
}
}
}
<file_sep>
import IConfigRepo from './IConfigRepo'
import { query } from '../../../common/dataAccess/dbAccess'
// Accesses data from local database or cloud service
export default class ConfigRepo implements IConfigRepo {
public async getClientID () : Promise<string> {
try {
const queryString = 'select * from client.config'
const result = await query(queryString)
let name = ''
result.rows.forEach(({ key, value }: {key: string, value: string}) => {
if (key === 'clientID') {
name = value
}
})
if (!name) {
throw new Error('client ID does not exit in Database')
}
return name
} catch (e) {
throw new Error('error retreiving client id ')
}
}
public async getClientPassword () : Promise<string> {
const queryString = 'select * from client.config'
const result = await query(queryString)
let password = ''
result.rows.forEach(({ key, value }: {key: string, value: string}) => {
if (key === 'name') {
password = value
}
})
return password
}
}
<file_sep>
// Bin sizes to handle a load of 1024 attributes
export default {
NUMBER_OF_BINS: 20,
MAXIMUM_LOAD: 100,
finiteFieldNum: 2n ** 256n - 351n * 2n ** 32n + 1n,
smallFiniteFieldNum: 1931n
// smallFiniteFieldNum: 1979n
// smallFiniteFieldNum: 351n * 2n ** 32n + 1n
}
<file_sep>import express from 'express'
import { Container } from 'typedi'
import InitPSIService from '../service'
import ConfigDA from '../../configDA/dataAccess/configRepo'
const router = express.Router()
// Called by the frontend
router.post('/initPSI', async (req, res) => {
const requesteeID = req.body.requesteeID
const requesteeIP = req.body.requesteeIP
if (!requesteeIP) {
res.status(433).json({ error: 'Please input requesteeIP' })
}
if (!requesteeID) {
res.status(433).json({ error: 'Please input requesteeID' })
}
const initPSIServiceInstance = Container.get(InitPSIService)
const configRepoInstance = new ConfigDA()
// TODO: A global variable should be set here to indicate that the PSI is computing
initPSIServiceInstance.initPSI({ requesteeID, requesteeIP }, configRepoInstance).then((intersectionResult?: String[]) => {
res.status(200).json({ status: 200, response: { success: true, intersectionResult } })
}).catch(err => {
res.status(500).json({ error: { type: 'general', message: err.message }, status: 500 })
})
})
export default router
<file_sep>
/**
* Interface for the data access layer to communicate with the service layer
*/
export default interface IConfigRepo {
getClientID : () => Promise<string>;
getClientPassword : () => Promise<string>;
}
<file_sep>import IattributesRepo from './IAttributesRepo'
import Attribute from '../../initClient/entities/attribute'
import CloudConfig from '../../initClient/entities/cloudConfig'
import galois from '@guildofweavers/galois'
import { initClientFetch, getCloudConfigFetch } from '../../../common/dataAccess/cloudAccess'
import { query } from '../../../common/dataAccess/dbAccess'
import { DatabaseError } from '../../../common/Error'
// Accesses data from local database or cloud service
export default class AttributesRepo implements IattributesRepo {
// eslint-disable-next-line camelcase
public getLocalAttributes = async () : Promise<{hashed_value: string, name: string, phone: number}[]> => {
const queryString = 'select * from client.attributes'
const results = await query(queryString)
return results.rows
}
public saveAttributesLocal = async (attributes: Attribute[]) => {
try {
const queryDelete = 'delete from client.attributes'
const queryString = `insert into client.attributes (hashed_value, name, phone) values ${attributes.map((attr) => `(${attr.getHashedValue()}, '${attr.name}', ${attr.number})`).join(',')} on conflict do nothing`
await query(queryDelete)
await query(queryString)
} catch (e) {
throw new DatabaseError(e.message)
}
}
// gets the configurations from the cloud
public async getCloudConfig () : Promise<CloudConfig> {
const res = await getCloudConfigFetch()
const { cloudConfig: cloudConfigString } = await res.json()
const cloudConfig = JSON.parse(cloudConfigString)
const numBins = cloudConfig.numBins
const numElementsPerBin = cloudConfig.numElementsPerBin
const finiteFieldNum = BigInt(cloudConfig.finiteFieldNum)
const smallFiniteFieldNum = BigInt(cloudConfig.smallFiniteFieldNum)
const vectorX = cloudConfig.vectorX.map((x: string) => BigInt(x))
return new CloudConfig(numBins, numElementsPerBin, finiteFieldNum, smallFiniteFieldNum, vectorX)
}
public async saveAttributesCloud (blindedVectors: galois.Matrix, url: string, clientID: string) : Promise<string> {
const stringified = JSON.stringify(blindedVectors, (key, value) =>
typeof value === 'bigint'
? value.toString()
: value // return everything else unchanged
)
await initClientFetch(stringified, url, clientID)
return ''
}
}
<file_sep>import { Service, Container } from 'typedi'
import IConfigRepo from '../../configDA/dataAccess/IConfigRepo'
import AppState from '../../../AppState'
// import { networkInterfaces } from 'os'
const fetch = require('node-fetch')
const acceptPSIRequestEndpoint = '/api/acceptPSIRequest/acceptPSIRequest'
interface initPSIRequest {
requesteeID: string;
requesteeIP: string;
}
@Service()
export default class InitPSIService {
public async initPSI ({ requesteeID, requesteeIP }: initPSIRequest, configRepo: IConfigRepo): Promise<String[] | undefined> {
const appStateInstance = Container.get(AppState)
appStateInstance.setPendingRequest(true)
console.log(`PSI initiated with client: ${requesteeID} at ${requesteeIP}`)
// Retrieve clientID from local DB
const clientID = await configRepo.getClientID()
await fetch(requesteeIP + acceptPSIRequestEndpoint, { method: 'POST', body: JSON.stringify({ requesterID: clientID, requesteeID }), headers: { 'Content-Type': 'application/json' } })
while (appStateInstance.isPendingRequest); // Wait until the results are retreived to return the results to the user
const intersectionResult = appStateInstance.intersectionResult
return intersectionResult
}
}
<file_sep>import { Service } from 'typedi'
import IAttributesRepo from '../dataAccess/IAttributesRepo'
interface initClientRequest {
url: string;
blindedVectors: string;
clientID: string;
}
interface cloudConfigResponse {
numBins: number;
numElementsPerBin: number;
finiteFieldNum: bigint;
smallFiniteFieldNum: bigint;
vectorX: bigint[]
}
@Service()
export default class InitClientService {
// clientID might not be unique
public async initClient ({ blindedVectors, url, clientID } : initClientRequest, dataAccess: IAttributesRepo) : Promise<string> {
// 1) Save attributes into cloud DB
await dataAccess.saveAttributesLocal(clientID, url, blindedVectors)
console.log('Saved Cloud Attributes')
return clientID
}
// Get cloud config
public async getCloudConfig (dataAccess: IAttributesRepo) : Promise<cloudConfigResponse> {
const { numBins, numElementsPerBin, finiteFieldNum, smallFiniteFieldNum, vectorX } = await dataAccess.getCloudConfig()
return { numBins, numElementsPerBin, finiteFieldNum, smallFiniteFieldNum, vectorX }
}
}
<file_sep>import IattributesRepo from './IAttributesRepo'
import CloudConfig from '../entities/cloudConfig'
import galois from '@guildofweavers/galois'
import { getCloudConfigFetch, resultsComputationFetch } from '../../../common/dataAccess/cloudAccess'
// Accesses data from local database or cloud service
export default class AttributesRepo implements IattributesRepo {
// gets the configurations from the cloud
public async getCloudConfig (): Promise<CloudConfig> {
const res = await getCloudConfigFetch()
const { cloudConfig: cloudConfigString } = await res.json()
const cloudConfig = JSON.parse(cloudConfigString)
const numBins = cloudConfig.numBins
const numElementsPerBin = cloudConfig.numElementsPerBin
const finiteFieldNum = BigInt(cloudConfig.finiteFieldNum)
const smallFiniteFieldNum = BigInt(cloudConfig.smallFiniteFieldNum)
const vectorX = cloudConfig.vectorX.map((x: string) => BigInt(x))
return new CloudConfig(numBins, numElementsPerBin, finiteFieldNum, smallFiniteFieldNum, vectorX)
}
public async resultsComputation (qMatrix: galois.Matrix, requesterID: string, requesteeID: string): Promise<void> {
const stringified = JSON.stringify(qMatrix, (key, value) =>
typeof value === 'bigint'
? value.toString()
: value // return everything else unchanged
)
console.log('Client B sends qMatrix to the cloud')
await resultsComputationFetch(stringified, requesterID, requesteeID)
}
}
<file_sep>import express from 'express'
import { Container } from 'typedi'
import InitClientService from '../service'
import AttributesRepo from '../dataAccess/attributesRepo'
const router = express.Router()
// Called by the client:
// returns a clientID
// Ideally, we should be using a jwt token here for authentication
router.post('/initClient', async (req, res) => {
const initClientServiceInstance = Container.get(InitClientService)
const attributeRepoInstance = new AttributesRepo()
const blindedVectors = req.body.blindedVectors
const url = req.body.url
const clientID = req.body.clientID
// Call initClient
initClientServiceInstance.initClient({ blindedVectors, url, clientID }, attributeRepoInstance).then((clientID) => {
res.status(200).json({ status: 200, clientID, response: { success: true } })
}).catch(err => {
res.status(500).json({ error: { type: 'general', message: err.message }, status: 500 })
})
})
// To get the cloud config
router.get('/getCloudConfig', async (req, res) => {
const initClientServiceInstance = Container.get(InitClientService)
const attributeRepoInstance = new AttributesRepo()
initClientServiceInstance.getCloudConfig(attributeRepoInstance).then(cloudConfig => {
const stringified = JSON.stringify(cloudConfig, (key, value) =>
typeof value === 'bigint'
? value.toString()
: value // return everything else unchanged
)
res.status(200).json({ status: 200, cloudConfig: stringified })
}).catch(err => {
res.status(500).json({ error: { type: 'general', message: err.message }, status: 500 })
})
})
export default router
<file_sep>export default class CloudConfig {
numBins: number
numElementsPerBin: number
finiteFieldNum: bigint
smallFiniteFieldNum: bigint
vectorX: bigint[]
constructor (numBins: number, numElementsPerBin: number, finiteFieldNum: bigint, smallFiniteFieldNum: bigint, vectorX: bigint[]) {
this.numBins = numBins
this.numElementsPerBin = numElementsPerBin
this.finiteFieldNum = finiteFieldNum
this.smallFiniteFieldNum = smallFiniteFieldNum
this.vectorX = vectorX
}
}
<file_sep>/* eslint-disable camelcase */
import Attribute from '../../initClient/entities/attribute'
import CloudConfig from '../../initClient/entities/cloudConfig'
import galois from '@guildofweavers/galois'
/**
* Interface for the data access layer to communicate with the service layer
*/
export default interface IattributesRepo {
saveAttributesLocal : (attributes: Attribute[]) => void;
getCloudConfig : () => Promise<CloudConfig>
saveAttributesCloud : (attributes: galois.Matrix, url: string, clientID: string) => Promise<string>
getLocalAttributes: () => Promise<{hashed_value: string, name: string, phone: number}[]>
}
<file_sep>/**
* Interface for the data access layer to communicate with the service layer
*/
export default interface IattributesRepo {
getMasterKey : () => Promise<string>;
saveMasterKey: (mk: string) => Promise<void>;
saveClientID: (clientID: string) => Promise<void>;
getClientID () : Promise<string>
}
<file_sep># Improved-EOPSI
## Starting up server:
Starts up a new server and db instance. Make sure docker is downloaded.
### Client app:
- cd into client-app directory
- docker-compose up
### Cloud app:
- cd into client-app directory
- docker-compose up
## Connecting to databae:
- download pg admin from https://www.pgadmin.org/download/ and open a new pgAdmin window
- create a new server and put localhost, 5432 (client) and localhost, 5433 (cloud) as the Url/ port
- Password is in the file: .env/db.env
## Testing the service:
- donwload postman
- After starting the 2 services, test a connection by doing a get request to localhost:5000. or localhost:5001
<file_sep>import galois from '@guildofweavers/galois'
export default class Attribute {
number: number
name: string
hashedValue?: bigint
field?: galois.FiniteField
getHash?: ({ name, number } : {name: string, number: number}) => bigint
constructor (name: string, number: number, { hashedValue, field, getHash } : {hashedValue?: string, field?: galois.FiniteField, getHash?: ({ name, number } : {name: string, number: number}) => bigint}) {
this.name = name
this.number = number
this.field = field
this.getHash = getHash
this.hashedValue = BigInt(hashedValue)
}
/**
* Returns a hashed value based on name and number
* This value is used in the database as the primary key, and will be used as the attribute used for comparison.
* Hash function and field is injected into this layer from the controller layer
*/
public getHashedValue = () => {
if (!this.hashedValue && this.field && this.getHash) {
return this.field.prng(this.getHash({ name: this.name, number: this.number }))
} else if (this.hashedValue) {
return this.hashedValue
} else {
throw new Error('Problem with getting hashed value, check attributes entity')
}
}
}
<file_sep>import { Service } from 'typedi'
import IDataRepo from '../dataAccess/IDataRepo'
import Igalois from '@guildofweavers/galois'
import CloudConfig from '../../initClient/entities/cloudConfig'
import BlindedAttributes from '../entities/blindedAttributes'
import { marshallGaloisMatrix } from '../../../common/util'
const fetch = require('node-fetch')
const RESULTS_RETRIEVAL_ENDPOINT = '/api/resultsRetrieval/resultsRetrieval'
interface resultsComputationRequest {
qMatrix: bigint[][];
requesterID: string;
requesteeID: string;
requesterBlindedMatrix: bigint[][];
requesteeBlindedMatrix: bigint[][];
cloudConfig: CloudConfig;
field: Igalois.FiniteField;
}
interface resultsComputationResponse {
requesterID: string;
requesteeID: string;
qPrime: Igalois.Matrix;
qPrimePrime: Igalois.Matrix;
}
interface retrieveAttributesRequest {
clientID: string;
}
interface retrieveAttributesResponse {
blindedAttributes: BlindedAttributes;
}
@Service()
export default class ResultsComputationService {
public async resultsComputation ({ qMatrix, requesterID, requesteeID, requesterBlindedMatrix, requesteeBlindedMatrix, cloudConfig, field }: resultsComputationRequest, dataAccess: IDataRepo): Promise<resultsComputationResponse> {
console.log('Cloud config num bins:', cloudConfig.numBins)
const tkB = 987n
const randomPolynomialB: bigint[][] = []
const randomPolynomialPointValueB: bigint[][] = []
for (let i = 0; i < cloudConfig.numBins; i++) {
randomPolynomialB[i] = []
}
ResultsComputationService.createRandomPolynomialB(tkB, cloudConfig.numBins, cloudConfig.numElementsPerBin, field, randomPolynomialB)
ResultsComputationService.convertToPointValueB(cloudConfig.vectorX, field, randomPolynomialB, randomPolynomialPointValueB)
// Converting from string to galolis matrix
const _qMatrix = field.newMatrixFrom(qMatrix)
const _requesteeBlindedMatrix = field.newMatrixFrom(requesteeBlindedMatrix)
const _requesterBlindedMatrix = field.newMatrixFrom(requesterBlindedMatrix)
const qPrime: Igalois.Matrix = field.mulMatrixElements(_qMatrix, _requesteeBlindedMatrix)
const randomPolynomialBMatrix = field.newMatrixFrom(randomPolynomialPointValueB)
const qPrimePrime: Igalois.Matrix = field.mulMatrixElements(randomPolynomialBMatrix, _requesterBlindedMatrix)
return { requesterID, requesteeID, qPrime, qPrimePrime }
// q' + q''(z) = wA T(A) + wB T(B) = g
}
public async retrieveBlindedAttributes ({ clientID }: retrieveAttributesRequest, dataAccess: IDataRepo): Promise<retrieveAttributesResponse> {
const blindedAttributes = await dataAccess.getBlindedAttributes(clientID)
return { blindedAttributes }
}
public async sendComputedResults ({ requesterID, requesteeID, qPrime, qPrimePrime }: resultsComputationResponse, requesterIP: string): Promise<void> {
const marshalledResults = { requesterID, requesteeID, qPrime: marshallGaloisMatrix(qPrime), qPrimePrime: marshallGaloisMatrix(qPrimePrime) }
console.log(`sending computed results to ${requesterIP + RESULTS_RETRIEVAL_ENDPOINT}`)
await fetch(requesterIP + RESULTS_RETRIEVAL_ENDPOINT, { method: 'POST', body: JSON.stringify(marshalledResults), headers: { 'Content-Type': 'application/json' } })
}
private static createRandomPolynomialB (tkB: bigint, numBins: number, maxLoad: number, field: Igalois.FiniteField, randomPolynomialB: bigint[][]): void {
// Creating Random Polynomial B
for (let i = 0; i < numBins; i++) {
const hashValue = field.prng(BigInt(String(tkB) + String(i * 20)))
// Creating degree d random polynomial - note: degree d polynomial has d+1 coefficients
for (let j = 0; j < maxLoad + 1; j++) {
const coefficient = field.prng(BigInt(String(hashValue) + String(j * 20)))
randomPolynomialB[i].push(coefficient)
}
}
}
private static convertToPointValueB (vectorX: bigint[], field: Igalois.FiniteField, randomPolynomialB: bigint[][], randomPolynomialPointValueB: bigint[][]): void {
// Converting to Point Value Representation
randomPolynomialB.forEach(randomPolynomialInBin => {
const polyArray: bigint[] = []
vectorX.forEach(x => {
polyArray.push(field.evalPolyAt(field.newVectorFrom(randomPolynomialInBin), x))
})
randomPolynomialPointValueB.push(polyArray)
})
}
}
<file_sep>const galois = require("@guildofweavers/galois");
const {concatenateAttribute, checkHashValue} = require("./util");
const randomNameGenerator = num => {
let res = '';
for(let i = 0; i < num; i++){
const random = Math.floor(Math.random() * 27);
res += String.fromCharCode(97 + random);
};
return res;
};
const generateTestData = (testSize) => {
const intersectionSet = [
{ name: 'alice', number: '91053280' },
{ name: 'bob', number: '98775251' },
{ name: 'charlie', number: '91524110' },
]
const testData = [...intersectionSet]
for(let i=0; i< testSize ; i++){
const name = randomNameGenerator(8)
const number = '9' + Math.floor(Math.random() * 10000000).toString()
testData.push({name, number})
}
return testData;
}
console.log(generateTestData(1))
// Constants
const LARGE_PRIME_NUMBER = 2n ** 256n - 351n * 2n ** 32n + 1n
// const SMALL_PRIME_NUMBER = 1931n
const SMALL_PRIME_NUMBER = 1979n
// const SMALL_PRIME_NUMBER = 351n * 2n ** 32n + 1n
const SMALLER_PRIME_NUMBER = 97n
// const LARGE_PRIME_NUMBER = 99999989n
// const SMALL_PRIME_NUMBER = 1931n
console.time('Full Protocol Time')
const field = galois.createPrimeField(LARGE_PRIME_NUMBER);
const smallField = galois.createPrimeField(SMALL_PRIME_NUMBER);
const smallerField = galois.createPrimeField(SMALLER_PRIME_NUMBER);
const NUMBER_OF_BINS = 6;
const MAXIMUM_LOAD = 5;
const MASTER_KEY_CLIENTA = 1234n; //master key set to simulate the implemented protocol
const MASTER_KEY_CLIENTB = 1234n; // master key set to simulate the implemented protocol
const ATTRIBUTE_COUNT = 1011
const clientAAttributes = [145n,1428n]
const clientBAttributes = [110n,1428n]
const vectorX = []
// Commented out to simulate the implemented protocol
// for (let i = 0; i < ATTRIBUTE_COUNT; i++){
// // const attributeA = smallerField.rand()
// // const attributeB = smallerField.rand()
// clientAAttributes.push(BigInt(i))
// clientBAttributes.push(BigInt(i+1000))
// // clientAAttributes.push(attributeA)
// // clientBAttributes.push(attributeB)
// }
for (let i = 1; i<= 2* MAXIMUM_LOAD + 1; i++){
vectorX.push(BigInt(i))
}
// console.log('Client A Attributes: ' + clientAAttributes)
// console.log('Client B Attributes: ' + clientBAttributes)
// console.log('Vector X: ' + vectorX)
// const clientAAttributes = [31n, 49n, 23n, 72n, 28n, 92n, 12n, 2n]
// const clientBAttributes = [23n, 49n, 25n, 31n, 72n, 22n, 50n, 2n]
// const vectorX = [1n, 2n, 3n, 4n, 5n, 6n, 7n, 8n, 9n, 10n, 11n, 12n, 13n, 14n, 15n]
const hashTableClientA = []
const hashTableClientB = []
const hashTablePointValueA = []
const hashTablePointValueB = []
const blindingFactorsA = []
const blindingFactorsB = []
const blindedValuesA = []
const blindedValuesB = []
const randomPolynomialA = []
const randomPolynomialB = []
for (let i = 0; i < NUMBER_OF_BINS; i++) {
hashTableClientA[i] = []
hashTableClientB[i] = []
hashTablePointValueA[i] = []
hashTablePointValueB[i] = []
blindingFactorsA[i] = []
blindingFactorsB[i] = []
blindedValuesA[i] = []
blindedValuesB[i] = []
randomPolynomialA[i] = []
randomPolynomialB[i] = []
}
// Concatenating the Attribute values with its hash -> attribute||00||hash(attribute)
const clientAConcateAttributes = clientAAttributes.map(attribute => {
return concatenateAttribute(attribute,smallField,SMALL_PRIME_NUMBER)
})
const clientBConcateAttributes = clientBAttributes.map(attribute => {
return concatenateAttribute(attribute,smallField,SMALL_PRIME_NUMBER)
})
// Hashing the attributes into bins
clientAConcateAttributes.forEach(attribute => {
const binValue = Number(attribute) % NUMBER_OF_BINS
hashTableClientA[binValue].push(attribute)
})
clientBConcateAttributes.forEach(attribute => {
const binValue = Number(attribute) % NUMBER_OF_BINS
hashTableClientB[binValue].push(attribute)
})
// Padding the bins up to MAXIMUM_LOAD value
for (let i = 0; i < NUMBER_OF_BINS; i++) {
const valuesInBinA = hashTableClientA[i].length
for (let j = 0; j < MAXIMUM_LOAD - valuesInBinA; j++) {
// hashTableClientA[i].push(field.rand())
hashTableClientA[i].push(0n) // For testing purposes
}
const valuesInBinB = hashTableClientB[i].length
for (let j = 0; j < MAXIMUM_LOAD - valuesInBinB; j++) {
// hashTableClientB[i].push(field.rand())
hashTableClientB[i].push(0n) // For testing purposes
}
}
// console.log(' ------------------ Hash Table ------------------')
// console.log('Hash Table (Client A):')
// console.log(hashTableClientA)
// console.log()
// console.log('Hash Table (Client B):')
// console.log(hashTableClientB)
// console.log()
// Creating the Polynomials in Point Value Representation
vectorX.forEach(x => {
for (let i = 0; i < NUMBER_OF_BINS; i++) {
let answer = 1n;
hashTableClientA[i].forEach(root => {
answer = field.mul(answer, field.sub(x, root))
})
hashTablePointValueA[i].push(answer)
}
for (let i = 0; i < NUMBER_OF_BINS; i++) {
let answer = 1n;
hashTableClientB[i].forEach(root => {
answer = field.mul(answer, field.sub(x, root))
})
hashTablePointValueB[i].push(answer)
}
})
// console.log(' ------------------ Hash Table Point Values ------------------')
// console.log('Hash Table Point Values (Client A):')
// console.log(hashTablePointValueA)
// console.log()
// console.log('Hash Table Point Values (Client B):')
// console.log(hashTablePointValueB)
// console.log()
// Creating Blinding Factors
for (let i = 0; i < NUMBER_OF_BINS; i++) {
const hashValueA = smallField.prng(BigInt(String(MASTER_KEY_CLIENTA) + String(i * 20)));
const hashValueB = smallField.prng(BigInt(String(MASTER_KEY_CLIENTB) + String(i * 20)));
for (let j = 0; j < 2 * MAXIMUM_LOAD + 1; j++) {
let blindingFactorA = smallField.prng(BigInt(String(hashValueA) + String(j * 20)))
let blindingFactorB = smallField.prng(BigInt(String(hashValueB) + String(j * 20)))
// To avoid a dividing by zero problem:
if (blindingFactorA === 0n) {
blindingFactorA = 1n
} else if (blindingFactorB === 0n) {
blindingFactorB = 1n
}
blindingFactorsA[i].push(blindingFactorA);
blindingFactorsB[i].push(blindingFactorB);
}
}
// console.log(' ------------------ Blinding Factors ------------------')
// console.log('Blinding Factors (Client A):')
// console.log(blindingFactorsA)
// console.log()
// console.log('Blinding Factors (Client B):')
// console.log(blindingFactorsB)
// console.log()
// Blinding the Point Value Pairs
const blindingFactorsAMatrix = field.newMatrixFrom(blindingFactorsA)
const blindingFactorsBMatrix = field.newMatrixFrom(blindingFactorsB)
const hashTablePointValueAMatrix = field.newMatrixFrom(hashTablePointValueA)
const hashTablePointValueBMatrix = field.newMatrixFrom(hashTablePointValueB)
const blindedValuesAMatrix = field.divMatrixElements(hashTablePointValueAMatrix, blindingFactorsAMatrix)
const blindedValuesBMatrix = field.divMatrixElements(hashTablePointValueBMatrix, blindingFactorsBMatrix)
// console.log(' ------------------ Blinded Values (Matrices) ------------------')
// console.log('Blinded Values (Client A):')
// console.log(blindedValuesAMatrix)
// console.log()
// console.log('Blinded Values (Client B):')
// console.log(blindedValuesBMatrix)
// console.log()
// console.time(`Starting from Computation Delegation Time`)
// Initiation of Improved EO-PSI
// Requester: Client B
// Requestee: Client A
// ================================== Client A Executes Computation Delegation ==================================
const TEMPORARY_KEY_A = 321n;
// Creating Random Polynomial
for (let i = 0; i < NUMBER_OF_BINS; i++) {
const hashValue = field.prng(BigInt(String(TEMPORARY_KEY_A) + String(i * 20)));
// Creating degree d random polynomial - note: degree d polynomial has d+1 coefficients
for (let j = 0; j < MAXIMUM_LOAD + 1; j++) {
const coefficient = field.prng(BigInt(String(hashValue) + String(j * 20)));
randomPolynomialA[i].push(coefficient)
}
}
// Converting to Point Value Representation
const randomPolynomialA_PointValue = []
randomPolynomialA.forEach((randomPolynomialInBin) => {
const polyArray = []
vectorX.forEach(x => {
polyArray.push(field.evalPolyAt(field.newVectorFrom(randomPolynomialInBin), x))
})
randomPolynomialA_PointValue.push(polyArray)
})
// console.log(' ------------------ Random Polynomial (Client A) ------------------')
// console.log(randomPolynomialA_PointValue)
// console.log()
const randomPolynomialAMatrix = field.newMatrixFrom(randomPolynomialA_PointValue)
const qValuesAMatrix = field.mulMatrixElements(randomPolynomialAMatrix, blindingFactorsAMatrix)
// console.log(' ------------------ Q Matrix (Client A) ------------------')
// console.log(qValuesAMatrix)
// console.log()
// ================================== Cloud Executes Results Computation ==================================
const qPrimeMatrix = field.mulMatrixElements(qValuesAMatrix, blindedValuesAMatrix)
const TEMPORARY_KEY_B = 987n;
// Creating Random Polynomial B
for (let i = 0; i < NUMBER_OF_BINS; i++) {
const hashValue = field.prng(BigInt(String(TEMPORARY_KEY_B) + String(i * 20)));
// Creating degree d random polynomial - note: degree d polynomial has d+1 coefficients
for (let j = 0; j < MAXIMUM_LOAD + 1; j++) {
const coefficient = field.prng(BigInt(String(hashValue) + String(j * 20)));
randomPolynomialB[i].push(coefficient)
}
}
// Converting to Point Value Representation
const randomPolynomialB_PointValue = []
randomPolynomialB.forEach(randomPolynomialInBin => {
const polyArray = []
vectorX.forEach(x => {
polyArray.push(field.evalPolyAt(field.newVectorFrom(randomPolynomialInBin), x))
})
randomPolynomialB_PointValue.push(polyArray)
})
// console.log(' ------------------ Random Polynomial (Cloud) ------------------')
// console.log(randomPolynomialB_PointValue)
// console.log()
const randomPolynomialBMatrix = field.newMatrixFrom(randomPolynomialB_PointValue)
const qPrimePrimeMatrix = field.mulMatrixElements(randomPolynomialBMatrix, blindedValuesBMatrix)
// console.log(` ------------------ q' and q" Matrices (Cloud) ------------------`)
// console.log(`q' Matrix:`)
// console.log(qPrimeMatrix)
// console.log()
// console.log(`q" Matrix:`)
// console.log(qPrimePrimeMatrix)
// console.log()
// q' + q''(z) = wA T(A) + wB T(B) = g
// ================================== Client B Executes Results Retrieval ==================================
const gMatrix = field.addMatrixElements(qPrimeMatrix, field.mulMatrixElements(qPrimePrimeMatrix, blindingFactorsBMatrix))
const gValues = gMatrix.toValues()
// console.log(` ------------------ g Values (Client B) ------------------`)
// console.log(gValues)
// console.log()
const resultantPolynomial = []
for (let i = 0; i < NUMBER_OF_BINS; i++) {
const polynomialYVector = field.newVectorFrom(gValues[i])
const result = field.interpolate(field.newVectorFrom(vectorX), polynomialYVector)
resultantPolynomial.push(result)
}
// console.log(` ------------------ Results (Client B) ------------------`)
// console.log('Resultant Polynomial:')
// console.log()
const answerArray = []
for (let i = 0; i < NUMBER_OF_BINS; i++) {
const binAnswerArray = []
// Fast "Factorisation"
hashTableClientB[i].forEach(attribute => {
const yValue = field.evalPolyAt(resultantPolynomial[i], BigInt(attribute))
if (yValue === 0n) {
binAnswerArray.push(attribute)
}
})
answerArray.push(binAnswerArray)
}
// console.log(` ------------------ Answer Array (Real and Junk Values) ------------------`)
// console.log(answerArray)
// console.log()
// Removing Fake Attributes from Real Attributes
realAnswerArray = []
console.log(answerArray)
answerArray.forEach(bin => {
if (bin.length !== 0) {
bin.forEach(answer => {
const {realValue, value } = checkHashValue(answer,smallField,SMALL_PRIME_NUMBER)
if(realValue){
realAnswerArray.push(value)
}
})
}
})
// console.log(` ------------------ Answer Array (Only Real Values) ------------------`)
console.log(realAnswerArray)
// console.log()
// console.log('Client A Attributes: ' + clientAAttributes)
// console.log('Client B Attributes: ' + clientBAttributes)
// console.log('Vector X: ' + vectorX)
console.timeEnd(`Full Protocol Time`)
// console.timeEnd(`Starting from Computation Delegation Time`)
<file_sep>import { Service } from 'typedi'
import IipRepo from '../dataAccess/IIPRepo'
interface getIPAddressRequest {
clientIDReq: string;
}
interface getIPAddressResponse {
clientID: string;
ipAddress: string;
}
@Service()
export default class GetIPAddressService {
// Get IP address
public async getIPAddress ({ clientIDReq } : getIPAddressRequest, dataAccess: IipRepo) : Promise<getIPAddressResponse> {
const { clientID, ipAddress } = await dataAccess.getIPAddress(clientIDReq)
return { clientID, ipAddress }
}
}
<file_sep>import express from 'express'
import { Container } from 'typedi'
import GetIPAddressService from '../../getIPAddress/service'
import InitClientService from '../../initClient/service'
import ResultsComputationService from '../service'
import DataRepo from '../dataAccess/dataRepo'
import AttributesRepo from '../../initClient/dataAccess/attributesRepo'
import IPRepo from '../../getIPAddress/dataAccess/ipRepo'
import { parseStringToMatrix } from '../../../common/util'
const router = express.Router()
const galois = require('@guildofweavers/galois')
router.post('/resultsComputation', async (req, res) => {
console.log('Cloud server begin results computation')
const initClientServiceInstance = Container.get(InitClientService)
const getIPAddressServiceInstance = Container.get(GetIPAddressService)
const resultsComputationServiceInstance = Container.get(ResultsComputationService)
const attributeRepoInstance = new AttributesRepo()
const ipRepoInstance = new IPRepo()
const dataRepoInstance = new DataRepo()
const requesteeID = req.body.requesteeID
const requesterID = req.body.requesterID
const qMatrix : bigint[][] = parseStringToMatrix(req.body.qMatrix)
// Get cloud config
const cloudConfig = await initClientServiceInstance.getCloudConfig(attributeRepoInstance)
const field = galois.createPrimeField(cloudConfig.finiteFieldNum)
const requesteeBlindedData = await resultsComputationServiceInstance.retrieveBlindedAttributes({ clientID: requesteeID }, dataRepoInstance)
const requesterBlindedData = await resultsComputationServiceInstance.retrieveBlindedAttributes({ clientID: requesterID }, dataRepoInstance)
console.log('Cloud server retreived client A and client B blinded data', requesteeID, requesterID)
const requesteeBlindedMatrix : bigint[][] = requesteeBlindedData.blindedAttributes.getParsedBlindedAttributes()
const requesterBlindedMatrix : bigint[][] = requesterBlindedData.blindedAttributes.getParsedBlindedAttributes()
// Result computation occurs
const computedResults = await resultsComputationServiceInstance.resultsComputation({ qMatrix, requesterID, requesteeID, requesterBlindedMatrix, requesteeBlindedMatrix, cloudConfig, field }, dataRepoInstance)
console.log('REQUESTER ID: ', requesterID)
const requesterIP = await getIPAddressServiceInstance.getIPAddress({ clientIDReq: requesterID }, ipRepoInstance)
resultsComputationServiceInstance.sendComputedResults(computedResults, requesterIP.ipAddress).then(() => {
res.status(200).json({ status: 200, response: { success: true } })
}).catch(err => {
res.status(500).json({ error: { type: 'general', message: err.message }, status: 500 })
})
})
export default router
<file_sep>import express from 'express'
import { Container } from 'typedi'
import InitClientService from '../service'
import ConfigRepo from '../../dataAccess/config/configRepo'
import { getHash } from '../../../common/util/hashAttributes'
import { generateTestData } from '../../../common/util/randomDataGenerator'
import Attribute from '../entities/attribute'
import AttributesRepo from '../../dataAccess/attributes/attributesRepo'
import { DatabaseError } from '../../../common/Error'
const router = express.Router()
const galois = require('@guildofweavers/galois')
/*
request body:
- Array of attribute objects: (Converted into a hashed value at the service layer)
- name
- phone
- mk : number
*/
router.post('/initClient', async (req, res) => {
const testSize = req.body.testSize
const attributesRequest = testSize ? generateTestData(testSize - 3) : req.body.attributes // generate the test data according to the number of attributes the user wants to compute the intersection for
const password = req.body.password
const url = req.body.url // url taken from local tunnel
const clientID = req.body.clientID // clientID assumed to be unique
const attributeRepoInstance = new AttributesRepo()
const initClientServiceInstance = Container.get(InitClientService)
const configRepoInstance = new ConfigRepo()
// 1) Get cloud config
const cloudConfig = await initClientServiceInstance.getCloudAttributes(attributeRepoInstance)
const field = galois.createPrimeField(cloudConfig.finiteFieldNum)
const smallField = galois.createPrimeField(cloudConfig.smallFiniteFieldNum)
// 2) Generate mk from password and save into db, and save clientID
const mk = await initClientServiceInstance.saveConfig({ password, dataAccess: configRepoInstance, field: smallField, clientID })
// 3) Create the attributes entity
const attributes = attributesRequest.map(({ name, number }: {name: string, number: string}) => {
return new Attribute(name, parseInt(number), smallField, getHash)
})
// 4) Call initClient
initClientServiceInstance.initClient({ attributes, mk, cloudConfig, field, url, clientID }, attributeRepoInstance).then(({ clientID }) => {
const stringified = JSON.stringify(clientID, (key, value) =>
typeof value === 'bigint'
? value.toString()
: value // return everything else unchanged
)
res.status(200).json({ status: 200, response: { blindedVectors: stringified } })
}).catch(err => {
let type = ''
if (err instanceof DatabaseError) { type = 'Database Error' } else if (err instanceof Error) { type = 'general' }
res.status(500).json({ error: { type, name: err.name, message: err.message }, status: 500 })
})
})
export default router
<file_sep>import express from 'express'
import { Container } from 'typedi'
import AcceptPSIRequestService from '../service'
import AttributesRepo from '../dataAccess/attributesRepo'
import ConfigRepo from '../../dataAccess/config/configRepo'
const router = express.Router()
const galois = require('@guildofweavers/galois')
/*
request body:
- Array of attribute objects: (Converted into a hashed value at the service layer)
- name
- phone number
- mk : number
*/
router.post('/acceptPSIRequest', async (req, res) => {
console.log('Begin Client B Accept PSI', req.body)
const requesterID = req.body.requesterID
const attributeRepoInstance = new AttributesRepo()
const acceptPSIRequestServiceInstance = Container.get(AcceptPSIRequestService)
const configRepoInstance = new ConfigRepo()
/**
* Seek approval and authentication from the requestee
*/
const { approved } = await acceptPSIRequestServiceInstance.acceptPSIRequest({ requesterID })
if (!approved) {
res.status(200).json({ status: 200, response: { success: false, text: 'PSI has been rejected' } })
}
// 1) Get cloud config
const cloudConfig = await acceptPSIRequestServiceInstance.getCloudAttributes(attributeRepoInstance)
const field = galois.createPrimeField(cloudConfig.finiteFieldNum)
console.log('Retrieved cloud config. Num bins:', cloudConfig.numBins)
// 2) Get local attributes
const mk = await configRepoInstance.getMasterKey()
const clientID = await configRepoInstance.getClientID()
if (typeof requesterID === 'string') {
/**
* Initiate the PSI with the cloud
*/
console.log('Client B Accepted PSI request')
acceptPSIRequestServiceInstance.computationDelegation({ requesterID, mk, cloudConfig, field, clientID }, attributeRepoInstance).then(() => {
res.status(200).json({ status: 200, response: { success: true } })
}).catch(err => {
res.status(500).json({ error: { type: 'general', message: err.message }, status: 500 })
})
} else {
res.status(500).json({ error: { type: 'general', message: 'bad request' }, status: 500 })
}
})
export default router
<file_sep>import CloudConfig from '../entities/cloudConfig'
/**
* Interface for the data access layer to communicate with the service layer
*/
export default interface IattributesRepo {
saveAttributesLocal : (clientID: string, url: string, blindedVectors: string) => void;
getCloudConfig : () => Promise<CloudConfig>
}
<file_sep>FROM node:12.18.1
ENV NODE_ENV=production
WORKDIR /app
COPY ["package.json", "package-lock.json*", "./"]
RUN npm install --production
# RUN npm install
COPY . .
EXPOSE 5000
# For development usage only
CMD [ "npm","run", "dev" ]
# Change to this before deployment
# CMD ["npm", "start"]
<file_sep>// Entry point to all routes
import logger from './middlewares/logger'
import express from 'express'
import initClientRoute from './initClient/controller'
import getIPAddress from './getIPAddress/controller'
import resultsComputation from './resultsComputation/controller'
import { corsImpl } from './middlewares/cors'
const router = express.Router()
// middlewares
router.use(logger)
router.use(express.json({ limit: '50mb' })) // Converts client requests to JSON
router.use(corsImpl) // cors settings
/**
* Unauthenticated routes
*/
/**
* Authenticated routes // Authentication is not implemented
*/
router.use('/initClient', initClientRoute)
router.use('/getIPAddress', getIPAddress)
router.use('/resultsComputation', resultsComputation)
export default router
<file_sep>import BlindedAttributes from '../entities/blindedAttributes'
/**
* Interface for the data access layer to communicate with the service layer
*/
export default interface IdataRepo {
getBlindedAttributes : (clientID: string) => Promise<BlindedAttributes>
}
<file_sep>import CloudConfig from '../entities/cloudConfig'
import galois from '@guildofweavers/galois'
/**
* Interface for the data access layer to communicate with the service layer
*/
export default interface IattributesRepo {
getCloudConfig: () => Promise<CloudConfig>
resultsComputation: (qMatrix: galois.Matrix, requesterID: string, requesteeID: string) => Promise<void>
}
<file_sep>// Entry point to all routes
import logger from './middlewares/logger'
import express from 'express'
import testRoute from './test/controller'
import usersRoute from './initClient/controller'
import resultsRetrieval from './resultsRetrieval/controller'
import initPSI from './initPSI/controller'
import acceptPSIRequest from './acceptPSIRequest/controller'
import { corsImpl } from './middlewares/cors'
const router = express.Router()
// middlewares
router.use(logger)
router.use(express.json({ limit: '50mb' })) // Converts client requests to JSON
router.use(corsImpl) // cors settings
/**
* Unauthenticated routes
*/
router.use('/test', testRoute)
router.use('/initClient', usersRoute)
router.use('/resultsRetrieval', resultsRetrieval)
router.use('/initPSI', initPSI)
router.use('/acceptPSIRequest', acceptPSIRequest)
/**
* Authenticated routes
*/
export default router
<file_sep>/* eslint-disable camelcase */
import { Service, Container } from 'typedi'
import Attribute from '../../entities/attribute'
import CloudConfig from '../../entities/cloudConfig'
import IAttributesRepo from '../../dataAccess/attributes/IAttributesRepo'
import Igalois from '@guildofweavers/galois'
import { checkHashValue, concatenateAttribute } from '../../../common/util/concat'
import AppState from '../../../AppState'
const galois = require('@guildofweavers/galois')
interface resultsRetrievalRequest {
qPrime: bigint[][];
qPrimePrime: bigint[][];
mk: string;
cloudConfig: CloudConfig;
field: Igalois.FiniteField;
}
@Service()
export default class ResultsRetrievalService {
public async resultsRetrieval ({ qPrime, qPrimePrime, mk, cloudConfig, field }: resultsRetrievalRequest, dataAccess : IAttributesRepo) : Promise<String[]> {
console.log('Cloud config num bins:', cloudConfig.numBins)
const appStateInstance = Container.get(AppState)
// Convert qprime and qprimeprime to galois matrix
const _qPrime = field.newMatrixFrom(qPrime)
const _qPrimePrime = field.newMatrixFrom(qPrimePrime)
// Retrieve attributes from stored DB
const localAttributesUnmarshalled = await dataAccess.getLocalAttributes()
const localAttributes = localAttributesUnmarshalled.map(({ hashed_value, name, phone }) => {
return new Attribute(name, phone, { hashedValue: hashed_value })
})
const hashField : Igalois.FiniteField = galois.createPrimeField(cloudConfig.smallFiniteFieldNum)
const blindingFactorsA : Igalois.Matrix = ResultsRetrievalService.generateBlindingFactors(mk, cloudConfig.numBins, cloudConfig.numElementsPerBin, hashField)
const resultPolynomial = ResultsRetrievalService.getResultantPolynomial(_qPrime, _qPrimePrime, blindingFactorsA, cloudConfig, field)
console.log('Result polynomial')
const intersectionResult = ResultsRetrievalService.factorisePolynomial(resultPolynomial, localAttributes, cloudConfig, field, hashField)
console.log('Final Intersection:', intersectionResult)
appStateInstance.setPendingRequest(false)
appStateInstance.setIntersectionResult(intersectionResult)
return intersectionResult
}
private static generateBlindingFactors (mk: string, numBins: number, numElementsPerBin: number, hashField: Igalois.FiniteField) : Igalois.Matrix {
console.log('Generating blinding factors')
const blindingFactorsA : bigint [][] = []
// Creating Blinding Factors
for (let i = 0; i < numBins; i++) {
const hashValueA = hashField.prng(BigInt(String(mk) + String(i * 20)))
blindingFactorsA.push([])
for (let j = 0; j < 2 * numElementsPerBin + 1; j++) {
let blindingFactorA = hashField.prng(BigInt(String(hashValueA) + String(j * 20)))
// To avoid a dividing by zero problem:
if (blindingFactorA === 0n) {
blindingFactorA = 1n
}
blindingFactorsA[i].push(blindingFactorA)
}
}
console.log('Blinding factors generated')
return hashField.newMatrixFrom(blindingFactorsA)
}
private static getResultantPolynomial (qPrime : Igalois.Matrix, qPrimePrime : Igalois.Matrix, blindingFactors: Igalois.Matrix, cloudConfig: CloudConfig, field: Igalois.FiniteField) : Igalois.Vector[] {
console.log('Stating get resultant polynomial')
try {
const gMatrix = field.addMatrixElements(qPrime, field.mulMatrixElements(qPrimePrime, blindingFactors))
const gValues = gMatrix.toValues()
const resultantPolynomial = []
for (let i = 0; i < cloudConfig.numBins; i++) {
const polynomialYVector = field.newVectorFrom(gValues[i])
const result = field.interpolate(field.newVectorFrom(cloudConfig.vectorX), polynomialYVector)
resultantPolynomial.push(result)
}
return resultantPolynomial
} catch (e) {
console.log('ERROR:', e.message)
throw new Error(e.message)
}
}
private static factorisePolynomial (resultantPolynomial : Igalois.Vector[], attributes: Attribute[], cloudConfig: CloudConfig, field: Igalois.FiniteField, hashField: Igalois.FiniteField) : String[] {
console.log('Starting factorization')
// Initialise hash table
const hashTableClient : bigint[][] = []
for (let i = 0; i < cloudConfig.numBins; i++) {
hashTableClient[i] = []
}
// Rebuilding attributes and placing them into bins in preparation for factorisation
const hashedAttributes = attributes.map((att) => (att.getHashedValue()))
hashedAttributes.forEach(attribute => {
const binValue = Number(attribute) % cloudConfig.numBins
hashTableClient[binValue].push(concatenateAttribute(attribute, hashField, cloudConfig.smallFiniteFieldNum))
})
// Factorisation Begins here
const answerArray : bigint[][] = []
for (let i = 0; i < cloudConfig.numBins; i++) {
const binAnswerArray : bigint [] = []
// Fast "Factorisation"
hashTableClient[i].forEach(attribute => {
const yValue = field.evalPolyAt(resultantPolynomial[i], BigInt(attribute))
if (yValue === 0n) {
binAnswerArray.push(attribute)
}
})
answerArray.push(binAnswerArray)
}
// Removing Fake Attributes from Real Attributes
const realAnswerArray : bigint[] = []
answerArray.forEach(bin => {
if (bin.length !== 0) {
bin.forEach(answer => {
const { realValue, value } = checkHashValue(answer, hashField, cloudConfig.smallFiniteFieldNum)
if (realValue) {
realAnswerArray.push(BigInt(value))
}
})
}
})
const commonAttributesNames : String[] = []
attributes.forEach(attribute => {
if (realAnswerArray.includes(attribute.getHashedValue())) {
commonAttributesNames.push(attribute.name)
}
})
return commonAttributesNames
}
}
<file_sep>import { Service } from 'typedi'
import Attribute from '../entities/attribute'
import CloudConfig from '../entities/cloudConfig'
import IAttributesRepo from '../../dataAccess/attributes/IAttributesRepo'
import IconfigRepo from '../../dataAccess/config/IconfigRepo'
import Igalois from '@guildofweavers/galois'
import { concatenateAttribute } from '../../../common/util/concat'
import { passwordToMk } from '../../../common/util/passwordUtil'
const galois = require('@guildofweavers/galois')
interface initClientRequest {
url: string;
attributes: Attribute[];
mk: string;
cloudConfig: CloudConfig
field: Igalois.FiniteField
clientID: string
}
@Service()
export default class InitClientService {
public async saveConfig ({ password, dataAccess, clientID, field }:{password: string, dataAccess: IconfigRepo, clientID: string, field: Igalois.FiniteField}):Promise<string> {
const mk = await this.parsePassword(password, dataAccess, field)
await this.saveClientID(clientID, dataAccess)
return mk
}
public async getCloudAttributes (dataAccess: IAttributesRepo) : Promise<CloudConfig> {
console.log('Retreived cloud config')
return dataAccess.getCloudConfig()
}
private async saveClientID (clientID: string, dataAccess:IconfigRepo) : Promise<void> {
await dataAccess.saveClientID(clientID)
}
private async parsePassword (password: string, dataAccess: IconfigRepo, field: Igalois.FiniteField) : Promise<string> {
const mk = passwordToMk(password, field)
console.log('Saving master key')
await dataAccess.saveMasterKey(mk)
return mk
}
public async initClient ({ attributes, mk, cloudConfig, field, url, clientID } : initClientRequest, dataAccess: IAttributesRepo) : Promise<{clientID: string}> {
console.log('init client')
console.log('Cloud config num bins:', cloudConfig.numBins)
// 1) Save attributes into local DB
await dataAccess.saveAttributesLocal(attributes)
console.log('Saved data to local DB')
// 2) Compute blinded vectors: O(x)
const smallField = galois.createPrimeField(cloudConfig.smallFiniteFieldNum)
const blindedVectors = this.computeBlindedVectors(attributes, mk, cloudConfig, field, smallField)
// console.log('Blinded vectors:', blindedVectors)
// 3) Send values to be stored in the cloud
await dataAccess.saveAttributesCloud(blindedVectors, url, clientID)
return { clientID }
}
// Takes in array of hashed attributes and returns an array of point value forms
private computeBlindedVectors (attributes: Attribute[], mk: string, cloudConfig: CloudConfig, field: Igalois.FiniteField, smallField: Igalois.FiniteField): Igalois.Matrix {
// Initialise hash tables
const hashTableClientA : bigint[][] = []
const hashTablePointValueA : bigint[][] = []
const blindingFactorsA : bigint[][] = []
const blindedValuesA : bigint[][] = []
for (let i = 0; i < cloudConfig.numBins; i++) {
hashTableClientA[i] = []
hashTablePointValueA[i] = []
blindingFactorsA[i] = []
blindedValuesA[i] = []
}
// Hashing the attributes into bins
const hashedAttributes = attributes.map((att) => (att.getHashedValue()))
hashedAttributes.forEach(attribute => {
const concatenatedAttribute = concatenateAttribute(attribute, smallField, cloudConfig.smallFiniteFieldNum)
const binValue = Number(concatenatedAttribute) % cloudConfig.numBins
hashTableClientA[binValue].push(concatenatedAttribute)
})
// Padding the bins up to numElementsPerBin value
for (let i = 0; i < cloudConfig.numBins; i++) {
const valuesInBinA = hashTableClientA[i].length
for (let j = 0; j < cloudConfig.numElementsPerBin - valuesInBinA; j++) {
// hashTableClientA[i].push(field.rand())
hashTableClientA[i].push(0n) // For testing purposes
}
}
console.log('created client hash table')
// Creating the Polynomials in Point Value Representation
cloudConfig.vectorX.forEach(x => {
for (let i = 0; i < cloudConfig.numBins; i++) {
let answer = 1n
hashTableClientA[i].forEach(root => {
answer = field.mul(answer, field.sub(x, root))
})
hashTablePointValueA[i].push(answer)
}
})
// generate blinding vectors
InitClientService.generateBlindingVectors(mk, cloudConfig.numBins, cloudConfig.numElementsPerBin, smallField, blindingFactorsA)
// Blinding the Point Value Pairs
const blindedValuesAMatrix = InitClientService.generateBlindedValues(blindingFactorsA, hashTablePointValueA, field)
return blindedValuesAMatrix
}
// Generates an array of blinding vectors
private static generateBlindingVectors (mk: string, numBins: number, numElementsPerBin: number, hashField: Igalois.FiniteField, blindingFactorsA: bigint[][]) : void {
// Creating Blinding Factors
for (let i = 0; i < numBins; i++) {
const hashValueA = hashField.prng(BigInt(String(mk) + String(i * 20)))
for (let j = 0; j < 2 * numElementsPerBin + 1; j++) {
let blindingFactorA = hashField.prng(BigInt(String(hashValueA) + String(j * 20)))
// To avoid a dividing by zero problem:
if (blindingFactorA === 0n) {
blindingFactorA = 1n
}
blindingFactorsA[i].push(blindingFactorA)
}
}
console.log('Generated Blinding factors')
}
// Blinds the point value pairs
private static generateBlindedValues (blindingFactorsA: bigint[][], hashTablePointValueA: bigint[][], field: Igalois.FiniteField) : Igalois.Matrix {
const blindingFactorsAMatrix = field.newMatrixFrom(blindingFactorsA)
const hashTablePointValueAMatrix = field.newMatrixFrom(hashTablePointValueA)
const blindedValuesAMatrix = field.divMatrixElements(hashTablePointValueAMatrix, blindingFactorsAMatrix)
return blindedValuesAMatrix
}
}
<file_sep>/* eslint-disable camelcase */
import { Service } from 'typedi'
import CloudConfig from '../entities/cloudConfig'
import IAttributesRepo from '../dataAccess/IAttributesRepo'
import Igalois from '@guildofweavers/galois'
const galois = require('@guildofweavers/galois')
interface acceptPSIRequest {
requesterID: string
}
@Service()
export default class AcceptPSIRequestService {
public async getCloudAttributes (dataAccess: IAttributesRepo): Promise<CloudConfig> {
return dataAccess.getCloudConfig()
}
public async acceptPSIRequest ({ requesterID: string }: acceptPSIRequest): Promise<{ approved: boolean; password: string; }> {
// Use requesterID to send notif to FE to seek approval and retrieve password
// Need a pub sub model here
const approved = true
const password = '<PASSWORD>' // take in from FE
return { approved, password }
}
public async computationDelegation ({ requesterID, mk, cloudConfig, field, clientID }: {requesterID: string, mk: string, cloudConfig: CloudConfig, field: Igalois.FiniteField, clientID: string }, dataAccess: IAttributesRepo): Promise<void> {
console.log('Client B begin computation delegation', mk)
console.log('Cloud config num bins:', cloudConfig.numBins)
const qMatrix = this.calculateQMatrix(mk, cloudConfig, field)
const requesteeID = clientID
console.log('Client B generated qMatrix from master key')
await dataAccess.resultsComputation(qMatrix, requesterID, requesteeID)
}
private calculateQMatrix (mk: string, cloudConfig: CloudConfig, field: Igalois.FiniteField): Igalois.Matrix {
const tk = 321n
const randomPolynomialA: bigint[][] = []
const blindingFactorsA: bigint[][] = []
for (let i = 0; i < cloudConfig.numBins; i++) {
randomPolynomialA[i] = []
blindingFactorsA[i] = []
}
for (let i = 0; i < cloudConfig.numBins; i++) {
const hashValue = field.prng(BigInt(String(tk) + String(i * 20)))
// Creating degree d random polynomial - note: degree d polynomial has d+1 coefficients
for (let j = 0; j < cloudConfig.numElementsPerBin + 1; j++) {
const coefficient = field.prng(BigInt(String(hashValue) + String(j * 20)))
randomPolynomialA[i].push(coefficient)
}
}
// Converting to Point Value Representation
const randomPolynomialA_PointValue: bigint[][] = []
randomPolynomialA.forEach((randomPolynomialInBin) => {
const polyArray: bigint[] = []
cloudConfig.vectorX.forEach(x => {
polyArray.push(field.evalPolyAt(field.newVectorFrom(randomPolynomialInBin), x))
})
randomPolynomialA_PointValue.push(polyArray)
})
// console.log(' ------------------ Random Polynomial (Client A) ------------------')
// console.log(randomPolynomialA_PointValue)
// console.log()
const randomPolynomialAMatrix = field.newMatrixFrom(randomPolynomialA_PointValue)
const hashField = galois.createPrimeField(cloudConfig.smallFiniteFieldNum)
const blindingVectors = AcceptPSIRequestService.generateBlindingVectors(mk, cloudConfig.numBins, cloudConfig.numElementsPerBin, hashField, blindingFactorsA)
const blindingFactorsAMatrix = field.newMatrixFrom(blindingVectors)
const qValuesAMatrix = field.mulMatrixElements(randomPolynomialAMatrix, blindingFactorsAMatrix)
// console.log(' ------------------ Q Matrix (Client A) ------------------')
return qValuesAMatrix
}
// Generates an array of blinding vectors
private static generateBlindingVectors (mk: string, numBins: number, numElementsPerBin: number, hashField: Igalois.FiniteField, blindingFactorsA: bigint[][]): bigint[][] {
const temp = [...blindingFactorsA]
// Creating Blinding Factors
for (let i = 0; i < numBins; i++) {
const hashValueA = hashField.prng(BigInt(String(mk) + String(i * 20)))
for (let j = 0; j < 2 * numElementsPerBin + 1; j++) {
let blindingFactorA = hashField.prng(BigInt(String(hashValueA) + String(j * 20)))
// To avoid a dividing by zero problem:
if (blindingFactorA === 0n) {
blindingFactorA = 1n
}
temp[i].push(blindingFactorA)
}
}
return temp
}
}
<file_sep>import IipRepo from './IIPRepo'
import IPAddress from '../entities/ipAddress'
import { query } from '../../../common/dataAccess/dbAccess'
// Accesses data from local database or cloud service
export default class IPRepo implements IipRepo {
public async getIPAddress (clientID: string): Promise<IPAddress> {
const queryString = 'select url from cloud.clients where clientid = $1'
const results = await query(queryString, [clientID])
const url = results.rows[0].url
return new IPAddress(clientID, url)
}
}
<file_sep>import IPAddress from '../entities/ipAddress'
/**
* Interface for the data access layer to communicate with the service layer
*/
export default interface IipRepo {
getIPAddress : (clientID: string) => Promise<IPAddress>
}
<file_sep>import express, { Request, Response } from 'express'
import { Container } from 'typedi'
import ConfigRepo from '../../dataAccess/config/configRepo'
import InitClientService from '../../initClient/service'
import ResultsRetrievalService from '../service'
import AttributesRepo from '../../dataAccess/attributes/attributesRepo'
import { unmarshallGaloisMatrix } from '../../../common/util/marshallMatrix'
const router = express.Router()
const galois = require('@guildofweavers/galois')
/*
This method is called by the cloud
request body:
- password : <PASSWORD>
- qPrime : Igalois.Matrix
- qPrimePrime : Igalois.Matrix
*/
router.post('/resultsRetrieval', async (req: Request, res: Response) => {
console.log('Begin results retrieval')
const qPrime = unmarshallGaloisMatrix(req.body.qPrime)
const qPrimePrime = unmarshallGaloisMatrix(req.body.qPrimePrime)
// const clientID = req.body.clientID
const attributeRepoInstance = new AttributesRepo()
const initClientServiceInstance = Container.get(InitClientService)
const resultsRetrievalServiceInstance = Container.get(ResultsRetrievalService)
const configRepoInstance = new ConfigRepo()
// Get cloud config
const cloudConfig = await initClientServiceInstance.getCloudAttributes(attributeRepoInstance)
const field = galois.createPrimeField(cloudConfig.finiteFieldNum)
// Retreive master key from database
const mk = await configRepoInstance.getMasterKey()
// Call Results Retrieval Service
resultsRetrievalServiceInstance.resultsRetrieval({ qPrime, qPrimePrime, mk, cloudConfig, field }, attributeRepoInstance).then((commonAttributes: String[]) => {
const stringified = JSON.stringify(commonAttributes, (key, value) =>
typeof value === 'bigint'
? value.toString()
: value
)
res.status(200).json({ status: 200, response: { commonAttributes: stringified } })
}).catch((err: any) => {
res.status(500).json({ error: { type: 'general', message: err.message }, status: 500 })
})
})
export default router
<file_sep>import { parseStringToMatrix } from '../../../common/util'
export default class BlindedAttributes {
blindedAttributes: string
constructor (blindedAttributes: string) {
this.blindedAttributes = blindedAttributes
}
// Convert each string value to big int
public getParsedBlindedAttributes () {
return parseStringToMatrix(this.blindedAttributes)
}
}
<file_sep>import express from 'express'
import { Container } from 'typedi'
import GetIPAddressService from '../service'
import IPRepo from '../dataAccess/ipRepo'
const router = express.Router()
// To get client IP address
router.get('/getIPAddress', async (req, res) => {
const getIPAddressServiceInstance = Container.get(GetIPAddressService)
const ipRepoInstance = new IPRepo()
const clientID = req.body.clientID
getIPAddressServiceInstance.getIPAddress({ clientIDReq: clientID }, ipRepoInstance).then(ipAddress => {
const stringified = JSON.stringify(ipAddress, (key, value) =>
typeof value === 'bigint'
? value.toString()
: value // return everything else unchanged
)
res.status(200).json({ status: 200, ipAddress: stringified })
}).catch(err => {
res.status(500).json({ error: { type: 'general', message: err.message }, status: 500 })
})
})
export default router
<file_sep>export default class IPAddress {
clientID: string
ipAddress: string
constructor (clientID: string, ipAddress: string) {
this.clientID = clientID
this.ipAddress = ipAddress
}
}
|
4042794916f1a51883a9ce36c573bbcc612e2b2e
|
[
"Markdown",
"TypeScript",
"JavaScript",
"Dockerfile"
] | 40 |
TypeScript
|
vincentwong2188/Improved-EOPSI
|
7614d61c81ef7ccca30a237c2b6ed6de7254c969
|
a2ba80c945364df93bf2c30a1483a1151d6ddc14
|
refs/heads/master
|
<repo_name>ox/glTF-Blender-IO<file_sep>/tools/copy_doc.py
# This file copy documentation into local svn repo
# in order to update online doc on blender server
# Example:
# copy_doc -r /home/<user>/blender_docs/
import argparse
import shutil
from os.path import isfile, isdir, dirname, realpath
from os import listdir
ap = argparse.ArgumentParser()
ap.add_argument("-r", "--repo", required=True, help="repo path")
args = vars(ap.parse_args())
doc = dirname(realpath(__file__)) + "/../docs/blender_docs/io_gltf2.rst"
images = dirname(realpath(__file__)) + "/../images/"
if not isdir(args["repo"]):
sys.exit()
shutil.copy(doc, args["repo"] + "/manual/addons/io_gltf2.rst")
images_list = listdir(images)
for img in images_list:
if not isfile(images + img):
continue
shutil.copy(images + img, args["repo"] + "/manual/images/" + img)
|
de3bf85f8d879c80564c41416aa33f22956b05d5
|
[
"Python"
] | 1 |
Python
|
ox/glTF-Blender-IO
|
fbb2c50723e5eaa2635672fedfb0f53df7d0798f
|
601d80ff633824d9091b842d220eedeb3f232e82
|
refs/heads/master
|
<repo_name>LiHe0308/CustomUIKit<file_sep>/Example/Podfile
use_frameworks!
platform :ios, '9.0'
target 'CustomUIKit_Example' do
pod 'CustomUIKit', :path => '../'
end
|
583a8bb38d47625d1028df123c1787cc6fa022cd
|
[
"Ruby"
] | 1 |
Ruby
|
LiHe0308/CustomUIKit
|
b80220b8c757815feefd4bf3ed8b2f6e9463baa1
|
db68b1a218a75f266a01f8324e32b0fcb1a29b06
|
refs/heads/master
|
<repo_name>tanhongze/ComputerNetwork<file_sep>/dcn-topo-exp/tools/tools.py
from mininet.topo import MultiGraph
from copy import deepcopy
import subprocess
import random
import re
import sys
def __xThrput(stream):
while True:
line = stream.readline()
res = re.match(r"^.*?([0-9\.]*)\sMbits/sec.*", line)
if res:
return float(res.group(1))
"""
@param: net, Mininet Class
"""
def iperfTest(net, pairs = 1):
print "iperfTest-------------------------------------------------START"
hosts = net.hosts
number = pairs
server = random.sample(hosts, number)
client = random.sample(filter(lambda x: x not in server, hosts), number)
for s in server:
s.stdout.flush()
s.stdin.flush()
#s.cmd("\x1a")
for c in client:
c.stdout.flush()
c.stdin.flush()
#s.cmd("\x1a")
#server = hosts[0:2]
#client = hosts[2:4]
serverTasks = {}
clientTasks = {}
avgThrput = 0.0
for s in server:
serverTasks[s.name] = s.popen("iperf -s -u -f m", stdout=subprocess.PIPE, shell=True)
for i in range(0, len(client)):
c = client[i]
s = server[i]
print "C (%s) -----> S (%s)" % (c, s)
clientTasks[c.name] = c.popen("iperf -c " + s.IP() + " -u -t 10 -b 100m -f m", stdout=subprocess.PIPE, shell=True)
for h, t in clientTasks.iteritems():
#t.wait()
t.communicate()
for h, t in serverTasks.iteritems():
thrput = __xThrput(t.stdout)
avgThrput += thrput / number
print "S <%s> throughput: %.2f Mbps" % (h, thrput)
print >> sys.stderr, "S <%s> throughput: %.2f Mbps" % (h, thrput)
t.kill()
print "Average Throughput: %.2f Mbps" % avgThrput
print "Aggregated Throughput: %.2f Mbps" % (avgThrput * number)
print "iperfTest-------------------------------------------------FINISH"
print >> sys.stderr, "Aggregated Throughput: %.2f Mbps" % (avgThrput * number)
print >> sys.stderr, "iperfTest-------------------------------------------------FINISH"
"""
@param: mg, Topo.g (MultiGraph member of Topo Class)
"""
def minCut(mg):
adjList = deepcopy(mg.edge)
#remove all host related edge
for k, v in adjList.items():
if mg.node[k].get("isSwitch", False) == False:
del adjList[k]
continue
for vert, attr in v.items():
if mg.node[vert].get("isSwitch", False) == False:
del adjList[k][vert]
comb = {}
mincut = 0xffffffff
for i in range(0, len(adjList) - 1):
s, t, ans = __contract(adjList, comb)
comb[t] = 1
if mincut > ans:
mincut = ans
if mincut == 0:
break
for vert, attr in adjList[t].iteritems():
capa = attr[1].get("bw", 1)
if not comb.get(vert):
adjList[s].setdefault(vert, {1:{}})
adjList[s][vert][1]["bw"] = adjList[s][vert][1].get("bw", 0) + capa
adjList[vert][s] = adjList[s][vert]
return mincut
def __contract(adjList, comb):
visit = {}
weight = {}
s = t = None
update = None
for k1 in adjList:
mmax = -1
temp = None
for k2 in adjList:
if not comb.get(k2) and not visit.get(k2) and weight.get(k2, 0) > mmax:
temp = k2
mmax = weight.get(k2, 0)
if temp == None:
break
s, t = t, temp
update = mmax
visit[t] = 1
for vert, attr in adjList[t].iteritems():
capa = attr[1].get("bw", 1)
if not comb.get(vert) and not visit.get(vert):
weight[vert] = weight.get(vert, 0) + capa
return s, t, update
<file_sep>/dcn-topo-exp/jelly/jelly_routing.py
from struct import pack
from zlib import crc32
from jellyfish.routing.shortest_path import KPathsRouting
import random
import os
import sys
def setRoutes(net):
routing = KPathsRouting(net.topo)
hosts = [net.topo.id_gen(name = h.name) for h in net.hosts]
for src in hosts:
print >> sys.stderr, "installing %s" % src.name_str()
for dst in hosts:
_install_proactive_path(net, routing, src, dst)
print "all routes were installed"
def _src_dst_hash(src_dpid, dst_dpid):
return crc32(pack('QQ', src_dpid, dst_dpid))
def _install_proactive_path(net, routing, src, dst):
src_sw = net.topo.up_nodes(src.name_str())
assert len(src_sw) == 1
src_sw_name = src_sw[0]
dst_sw = net.topo.up_nodes(dst.name_str())
assert len(dst_sw) == 1
dst_sw_name = dst_sw[0]
hash_ = _src_dst_hash(src.dpid, dst.dpid)
route = routing.get_route(src_sw_name, dst_sw_name, hash_)
#print >> sys.stderr, "route: %s" % route
final_out_port, ignore = net.topo.port(route[-1], dst.name_str())
for i, node in enumerate(route):
next_node = None
if i < len(route) - 1:
next_node = route[i + 1]
port_pairs = net.topo.port(node, next_node)
if type(port_pairs) == list:
out_port = [t[0] for t in port_pairs]
out_port = out_port[hash_ % len(out_port)]
else:
out_port = port_pairs[0]
else:
out_port = final_out_port
##add routes statically
os.system("ovs-ofctl add-flow %s dl_type=0x0800,nw_dst=%s,nw_src=%s,idle_timeout=0,hard_timeout=0,priority=10,action=output:%d" % (node, dst.ip_str(), src.ip_str(), out_port))
os.system("ovs-ofctl add-flow %s dl_type=0x0806,nw_dst=%s,nw_src=%s,idle_timeout=0,hard_timeout=0,priority=10,action=output:%d" % (node, dst.ip_str(), src.ip_str(), out_port))
<file_sep>/dcn-topo-exp/jelly/jelly_swim.sh
sudo mn -c
sudo python ./jelly.py 20 40 2 2 0 > resultK4.txt
#sudo python ./jelly.py 45 120 3 3 0 > resultK6more.txt
sudo python ./jelly.py 45 60 3 3 0 > resultK6.txt<file_sep>/dcn-topo-exp/jelly/jelly.py
#!/usr/bin/env python
"""
Create a 1024-host network, and run the CLI on it.
If this fails because of kernel limits, you may have
to adjust them, e.g. by adding entries to /etc/sysctl.conf
and running sysctl -p. Check util/sysctl_addon.
"""
from mininet.net import Mininet
from mininet.cli import CLI
from mininet.log import setLogLevel
from mininet.node import OVSSwitch, Controller, RemoteController
from mininet.link import TCLink
from jellyfish.topologies.jellyfish import JellyfishTopo
from jelly_routing import setRoutes
import sys
sys.path.append("..")
from tools.tools import iperfTest, minCut
from threading import Timer
import time
import threading
from time import ctime,sleep
import multiprocessing
import random
def JellyfishNet(seed=0, switches=16, nodes=8, ports_per_switch=2, hosts_per_switch=1, bw=1, **kwargs):
topo = JellyfishTopo(seed, switches, nodes, ports_per_switch, hosts_per_switch, bw)
return Mininet(topo, **kwargs)
if __name__ == '__main__':
setLogLevel( 'info' )
switches_ = int(sys.argv[1])
nodes_ = int(sys.argv[2])
ports_per_switch_=int(sys.argv[3])
hosts_per_switch_=int(sys.argv[4])
seed_ = int(sys.argv[5])
network = JellyfishNet(seed=seed_, switches=switches_, nodes=nodes_, ports_per_switch=ports_per_switch_, hosts_per_switch=hosts_per_switch_, switch=OVSSwitch, link=TCLink, controller=RemoteController, autoSetMacs=True)
network.start()
setRoutes(network)
time_limit = 600
#network.pingAll()
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
#for i in [nodes_/2]:
for i in range(nodes_/2,0,-max(1,nodes_/20)):
j = 0
if(i == 20):
j = 3
for k in range(10):
print >> sys.stderr, "launch pair %d time %d" % (i,j)
print "launch pair %d time %d" % (i,j)
p = multiprocessing.Process(target=iperfTest,args=(network,i))
p.daemon=True
startTime=time.time()
p.start()
lim = 0
while( p.is_alive() and lim < time_limit ) :
sleep(1)
lim=lim+1
if(p.is_alive()):
p.terminate()
print >> sys.stderr, "Time out... @pair %d time %d" % (i,j)
print "Time out... @pair %d time %d" % (i,j)
network.stop()
network = JellyfishNet(seed=seed_, switches=switches_, nodes=nodes_, ports_per_switch=ports_per_switch_, hosts_per_switch=hosts_per_switch_, switch=OVSSwitch, link=TCLink, controller=RemoteController, autoSetMacs=True)
network.start()
setRoutes(network)
random.seed((29*i+13*j+7*k) % 37)
time_limit = int(time_limit*0.9+60)
else:
j=j+1
endTime=time.time()
time_limit = int(1+(endTime-startTime)*1.5+time_limit/2)
if(j>=5):
break
#CLI(network)
print ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"
network.stop()
|
7317f9a48d8bef67a8c0530834fd1a00b13803ad
|
[
"Python",
"Shell"
] | 4 |
Python
|
tanhongze/ComputerNetwork
|
a52784b72d6387bd692ddf516d4638fd1231fd98
|
42f3024c1afc9785463218f92bc5db28d98937ef
|
refs/heads/master
|
<repo_name>arol/sinatrest-cedar<file_sep>/spec/application_spec.rb
require File.dirname(__FILE__) + '/spec_helper'
describe "Application" do
it "should respond to /" do
get "/"
last_response.status.should == 200
end
end<file_sep>/config.ru
require 'rubygems'
require 'sinatra'
require 'slim'
require 'haml'
require 'mongoid'
require 'rufus/scheduler'
require './application'
run Application
<file_sep>/jobs.rb
# require 'restclient'
# require 'json'
job 'api.poll' do
puts 'hello'
end
<file_sep>/clock.rb
require 'stalker'
handler { |job| Stalker.enqueue(job) }
every 1.seconds, 'api.poll'
<file_sep>/README.md
Sinatra Prototype
==================================
Install
---------------------
First of all run bundle to setup gems
bundle install
Install mongodb and run it
brew install mongodb
mongod run --config /usr/local/Cellar/mongodb/2.0.3-x86_64/mongod.conf
Then you can run the server
rackup config.ru
A Sinatra application
---------------------
This is a simple sinatra application for rapid web app prototyping which
has been configured to be hosted on the amazing [Heroku Platform](http://heroku.com/).
Runs on both:
* bamboo-ree-1.8.7 stack
* bamboo-mri-1.9.2 stack
The application comes with jQuery 1.5.1 loaded from Google Ajax Libraries
Current Gems
------------
* Sinatra
* Sinatra-mongoid
* Bson_ext ( for mongoDB performance )
* Haml ( for SASS )
* Slim
* Rspec 2
* Cucumber
* Capybara
* Rack-Test
Licence
-------
This application is released under the MIT licence.<file_sep>/Gemfile
source :rubygems
gem 'thin', "1.3.1"
gem 'sinatra', "1.2.1"
gem 'mongoid', "1.9.5"
gem "bson_ext", "1.3.1"
gem 'slim'
gem 'haml'
gem "rufus-scheduler"
gem 'daemons'
gem 'stalker', '0.3.0'
gem 'clockwork', '0.2.0'
gem 'foreman', '0.40.0'
group :test do
gem "rspec"
gem "cucumber-sinatra"
gem "cucumber"
gem "rack-test"
gem "capybara"
end<file_sep>/features/step_definitions/application_steps.rb
Given /^I am viewing the home page$/ do
visit('/')
end
Then /^I should see "([^"]*)"$/ do |text|
page.should have_content(text)
end
<file_sep>/application.rb
Dir["./models/**/*.rb"].each { |model| require model }
class Application < Sinatra::Base
configure do
set :root, File.dirname(__FILE__)
set :static, true
set :template, :slim
# Haml & Sass options
set :sass, :style => :compressed
end
Mongoid.configure do |config|
if ENV['MONGOHQ_URL']
conn = Mongo::Connection.from_uri(ENV['MONGOHQ_URL'])
uri = URI.parse(ENV['MONGOHQ_URL'])
config.master = conn.db(uri.path.gsub(/^\//, ''))
else
config.master = Mongo::Connection.from_uri("mongodb://localhost:27017").db('test')
end
end
get '/' do
slim :index
end
get '/nou_tweet' do
@tweet = Tweet.new(:screen_name=>"arolet",:lat=>1.2238293829382,:lon=>10.2238293829382,:time=>'03/04/2012 21:43:45',:num_retweets=>25, :status=>"Si no lo veo no lo creo")
@tweet.save
slim :nou_tweet
end
get '/get_tweet' do
@tweets = Tweet.where(:screen_name => "arolet").to_a
slim :get_tweet
end
get '/last_tweet' do
@tweets = Tweet.last.to_a
slim :get_tweet
end
get '/stylesheets/application.css' do
sass :application
end
end
# scheduler = Rufus::Scheduler.start_new
# ENV['flag']=false;
# scheduler.every '1s', :blocking => true do
# @tweet = Tweet.new(:screen_name=>"sergijonama",:lat=>1.2238293829382,:lon=>10.2238293829382,:time=>'03/04/2012 21:43:45',:num_retweets=>25, :status=>"Si no lo veo no lo creo")
#
# if ENV['flag'] == false
# @tweet.save
# ENV['flag'] = true
# puts 'saved'
# else
# ENV['flag'] = false
# end
#
#
# end
<file_sep>/features/support/env.rb
require 'rubygems'
require 'sinatra'
require 'slim'
require 'haml'
require 'mongoid'
require File.join(File.dirname(__FILE__), '..', '..', 'application.rb')
require 'capybara'
require 'capybara/cucumber'
require 'rspec'
Application.set(:environment, :test)
World do
Capybara.app = Application
include Capybara
include RSpec::Expectations
include RSpec::Matchers
end
<file_sep>/spec/spec_helper.rb
require 'rubygems'
require 'sinatra'
require 'slim'
require 'haml'
require 'mongoid'
require File.join(File.dirname(__FILE__), '..', 'application.rb')
require 'rack/test'
require 'rspec'
RSpec.configure do |config|
config.include Rack::Test::Methods
def app
Application
end
end
|
c2ed6ce464ccccc416bfe93a20d1e7f6efa2e485
|
[
"Markdown",
"Ruby"
] | 10 |
Ruby
|
arol/sinatrest-cedar
|
64a5aada7f5cc1c0a650b39cdc44d6ab1aa03df2
|
cbacbc6b6ef73b670e0e7edfad6246b9da7fd7a1
|
refs/heads/main
|
<repo_name>hluitel/CS206-ER<file_sep>/README.md
# CS206-ER
|
6fb34b4ea468c6510f0aea5e45df2f4a62a72e1a
|
[
"Markdown"
] | 1 |
Markdown
|
hluitel/CS206-ER
|
e3ce6afd55b0c966f4612ce7c487d085f841cdd3
|
aa9d08147d0c444c1a22f5715b3723b8632faf5b
|
refs/heads/master
|
<file_sep>import { CompletionsFormat, generateAlloyCompletions, generateSDKCompletions, loadCompletions } from '../src/completions';
import { CustomError } from '../src/completions/util';
import { expect } from 'chai';
import fs from 'fs-extra';
import mockFS from 'mock-fs';
import os from 'os';
import * as path from 'path';
import { parsers } from './fixtures/parsers';
const FIXTURES_DIR = path.join(__dirname, 'fixtures');
describe('completions', () => {
beforeEach(() => {
mockFS.restore();
});
afterEach(() => {
mockFS.restore();
});
describe('completions.generateAlloyCompletions', () => {
it('Generate Alloy Completions', async () => {
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
mockFS({
[installPath]: {
'.version': '4.2.0',
'4.2.0': {
package: {
'package.json': '{ "version": "4.2.0" }',
node_modules: {
alloy: {
'package.json': '{"version": "0.2.0"}',
Alloy: {
commands: {
compile: {
parsers: mockFS.directory({
items: parsers
}),
}
}
}
}
}
}
}
},
});
const completions = await generateAlloyCompletions(true);
expect(completions).to.equal('0.2.0');
});
it('Generate Alloy Completions without alloy installed', async () => {
try {
await generateAlloyCompletions(true);
} catch (error) {
expect(error).to.be.instanceOf(Error);
expect(error.message).to.equal('Unable to find installed alloy version.');
}
});
it('Generate Alloy Completions with pre-existing completions', async () => {
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
const completionsPath = path.join(os.homedir(), '.titanium', 'completions', 'alloy', '0.2.0');
mockFS({
[installPath]: {
'.version': '4.2.0',
'4.2.0': {
package: {
'package.json': '{ "version": "4.2.0" }',
node_modules: {
alloy: {
'package.json': '{"version": "0.2.0"}',
Alloy: {
commands: {
compile: {
parsers: mockFS.directory({
items: parsers
}),
}
}
}
}
}
}
}
},
[completionsPath]: {
'completions-v1.json': ''
},
});
const completions = await generateAlloyCompletions(false);
expect(completions).to.equal(undefined);
});
});
describe('completions.generateSDKCompletions', () => {
it('Generate SDK Completions', async () => {
mockFS({
[FIXTURES_DIR]: {
'api.jsca': await fs.readFile(path.join(FIXTURES_DIR, 'ti-api.jsca'))
},
});
const completions = await generateSDKCompletions(true, '8.1.0.GA', FIXTURES_DIR, CompletionsFormat.v1);
expect(completions).to.equal('8.1.0.GA');
});
it('Generate SDK Completions without sdk', async () => {
try {
await generateSDKCompletions(true, '8.1.0.GA', '', CompletionsFormat.v1);
} catch (error) {
expect(error).to.be.instanceOf(CustomError);
expect(error.message).to.equal('The current projects SDK version 8.1.0.GA, is not installed. Please update the SDK version in the tiapp to generate autocomplete suggestions.');
expect(error.code).to.equal('ESDKNOTINSTALLED');
}
});
it('Generate SDK Completions with pre-existing completions', async () => {
const completionsPath = path.join(os.homedir(), '.titanium', 'completions', 'titanium', '8.1.0.GA');
mockFS({
[completionsPath]: {
'completions-v1.json': ''
},
});
const completions = await generateSDKCompletions(false, '8.1.0.GA', FIXTURES_DIR, CompletionsFormat.v1);
expect(completions).to.equal(undefined);
});
});
describe('completions.loadCompletions', () => {
it('Load Completions', async () => {
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
mockFS({
[installPath]: {
'.version': '4.2.0',
'4.2.0': {
package: {
'package.json': '{ "version": "4.2.0" }',
node_modules: {
alloy: {
'package.json': '{"version": "0.2.0"}',
Alloy: {
commands: {
compile: {
parsers: mockFS.directory({
items: parsers
}),
}
}
}
}
}
}
}
},
[FIXTURES_DIR]: {
'api.jsca': await fs.readFile(path.join(FIXTURES_DIR, 'ti-api.jsca'))
},
});
const sdkCompletions = await generateSDKCompletions(true, '8.1.0.GA', FIXTURES_DIR, CompletionsFormat.v1);
expect(sdkCompletions).to.equal('8.1.0.GA');
const alloyCompletions = await generateAlloyCompletions(true);
expect(alloyCompletions).to.equal('0.2.0');
const completions = await loadCompletions('8.1.0.GA');
expect(completions.alloy.alloyVersion).to.equal('0.2.0');
expect(completions.alloy.version).to.equal(1);
expect(completions.titanium.sdkVersion).to.equal('8.1.0.GA');
expect(completions.titanium.version).to.equal(1);
});
});
describe('completions.loadCompletions V2', () => {
it('Load Completions', async () => {
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
mockFS({
[installPath]: {
'.version': '4.2.0',
'4.2.0': {
package: {
'package.json': '{ "version": "4.2.0" }',
node_modules: {
alloy: {
'package.json': '{"version": "0.2.0"}',
Alloy: {
commands: {
compile: {
parsers: mockFS.directory({
items: parsers
}),
}
}
},
docs: {
'api.jsca': await fs.readFile(path.join(FIXTURES_DIR, 'alloy-api.jsca'))
}
}
}
}
}
},
[FIXTURES_DIR]: {
'api.jsca': await fs.readFile(path.join(FIXTURES_DIR, 'ti-api.jsca'))
},
});
const sdkCompletions = await generateSDKCompletions(true, '8.1.0.GA', FIXTURES_DIR, CompletionsFormat.v2);
expect(sdkCompletions).to.equal('8.1.0.GA');
const alloyCompletions = await generateAlloyCompletions(true, CompletionsFormat.v2);
expect(alloyCompletions).to.equal('0.2.0');
const completions = await loadCompletions('8.1.0.GA', CompletionsFormat.v2);
expect(completions.alloy.alloyVersion).to.equal('0.2.0');
expect(completions.alloy.version).to.equal(2);
expect(completions.titanium.sdkVersion).to.equal('8.1.0.GA');
expect(completions.titanium.version).to.equal(2);
});
});
});
<file_sep>import { run } from 'appcd-subprocess';
import * as libnpm from 'libnpm';
import * as semver from 'semver';
import { UpdateInfo } from '..';
import { ProductNames } from '../product-names';
import * as util from '../util';
export async function checkInstalledVersion (): Promise<string|undefined> {
// First try running appc cli to get the version
try {
const { stdout } = await run('appc', [ '--version', '--output', 'json' ], { shell: true });
const { NPM } = JSON.parse(stdout);
return NPM;
} catch (error) {
// squelch
}
// If that fails because it's not installed, or we don't have a core, fallback to npm cli which is generally slower
try {
const { stdout } = await run('npm', [ 'ls', 'appcelerator', '--json', '--depth', '0', '--global' ], { shell: true });
const { dependencies: { appcelerator } } = JSON.parse(stdout);
return appcelerator.version;
} catch (error) {
// squelch
}
return;
}
export async function checkLatestVersion (): Promise<string> {
const { version } = await libnpm.manifest('appcelerator@latest');
return version;
}
export async function installUpdate (version: string): Promise<void> {
const { code, stdout, stderr } = await run('npm', [ 'install', '-g', `appcelerator@${version}`, '--json' ], { shell: true, ignoreExitCode: true });
if (code) {
const metadata = {
errorCode: '',
exitCode: code,
stderr,
stdout,
command: `npm install -g appcelerator@${version}`
};
try {
const jsonResponse = JSON.parse(stdout);
metadata.errorCode = jsonResponse.error && jsonResponse.error.code;
} catch (error) {
// squash
}
throw new util.InstallError('Failed to install package', metadata);
}
}
export function getReleaseNotes (): string {
// There are no public release notes for appc-install, so just point to the latest CLI release notes
return 'https://docs.appcelerator.com/platform/latest/#!/guide/Appcelerator_CLI_Release_Notes';
}
export async function checkForUpdate (): Promise<UpdateInfo> {
const [ currentVersion, latestVersion ] = await Promise.all<string|undefined, string>([
checkInstalledVersion(),
checkLatestVersion()
]);
const updateInfo: UpdateInfo = {
currentVersion,
latestVersion,
action: installUpdate,
productName: ProductNames.AppcInstaller,
releaseNotes: getReleaseNotes(),
priority: 10,
hasUpdate: false
};
if (!currentVersion || semver.gt(latestVersion, currentVersion)) {
updateInfo.hasUpdate = true;
}
return updateInfo;
}
<file_sep>import { appc, titanium, node } from '../src/updates/';
import * as titaniumlib from 'titaniumlib';
import { expect } from 'chai';
import child_process from 'child_process';
import { EventEmitter } from 'events';
import mockFS from 'mock-fs';
import nock from 'nock';
import os from 'os';
import * as path from 'path';
import stream from 'stream';
import { mockAppcCoreRequest, mockNpmRequest, mockSDKRequest, mockNodeRequest } from './fixtures/network/network-mocks';
import * as sinon from 'sinon';
function createChildMock (): child_process.ChildProcess {
const fakeChild = new EventEmitter() as child_process.ChildProcess;
fakeChild.stdout = new EventEmitter() as stream.Readable;
fakeChild.stderr = new EventEmitter() as stream.Readable;
return fakeChild;
}
describe('updates', () => {
beforeEach(() => {
mockFS.restore();
});
afterEach(() => {
nock.cleanAll();
mockFS.restore();
});
describe('titanium.sdk', () => {
it('checkForUpdate with installed SDKS', async () => {
const sdkStub = global.sandbox.stub(titaniumlib.sdk, 'getInstalledSDKs');
sdkStub.returns([
{
name: '7.0.2.GA',
manifest: {
name: '7.0.2.v20180209105903',
version: '7.0.2',
moduleAPIVersion: {
iphone: '2',
android: '4',
windows: '4'
},
timestamp: '2/9/2018 19:05',
githash: '5ef0c56',
platforms: [
'iphone',
'android'
]
},
path: '/Users/eharris/Library/Application Support/Titanium/mobilesdk/osx/7.0.2.GA'
},
{
name: '7.5.0.GA',
manifest: {
name: '7.5.0.v20181115134726',
version: '7.5.0',
moduleAPIVersion: {
iphone: '2',
android: '4',
windows: '6'
},
timestamp: '11/15/2018 21:52',
githash: '2e5a7423d0',
platforms: [
'iphone',
'android'
]
},
path: '/Users/eharris/Library/Application Support/Titanium/mobilesdk/osx/7.5.0.GA'
},
{
name: '8.1.0.v20190416065710',
manifest: {
name: '8.1.0.v20190416065710',
version: '8.1.0',
moduleAPIVersion: {
iphone: '2',
android: '4',
windows: '7'
},
timestamp: '4/16/2019 14:03',
githash: '37f6d88',
platforms: [
'iphone',
'android'
]
},
path: '/Users/eharris/Library/Application Support/Titanium/mobilesdk/osx/8.1.0.v20190416065710'
}
]);
mockSDKRequest('sdk-response.json');
const update = await titanium.sdk.checkForUpdate();
expect(update.currentVersion).to.equal('7.5.0.GA');
expect(update.latestVersion).to.equal('8.0.0.GA');
expect(update.productName).to.equal('Titanium SDK');
expect(update.hasUpdate).to.equal(true);
});
it('checkForUpdate with no installed SDKS', async () => {
const sdkStub = global.sandbox.stub(titaniumlib.sdk, 'getInstalledSDKs');
sdkStub.returns([]);
mockSDKRequest('sdk-response.json');
const update = await titanium.sdk.checkForUpdate();
expect(update.currentVersion).to.equal('');
expect(update.latestVersion).to.equal('8.0.0.GA');
expect(update.productName).to.equal('Titanium SDK');
expect(update.hasUpdate).to.equal(true);
});
it('checkForUpdate with latest installed', async () => {
const sdkStub = global.sandbox.stub(titaniumlib.sdk, 'getInstalledSDKs');
sdkStub.returns([
{
name: '8.0.0.GA',
manifest: {
name: '8.0.0.v20190314105657',
version: '8.0.0',
moduleAPIVersion: {
iphone: '2',
android: '4',
windows: '7'
},
githash: '3726240fa2',
platforms: [
'iphone',
'android'
],
timestamp: '4/2/2019 17:36'
},
path: '/Users/eharris/Library/Application Support/Titanium/mobilesdk/osx/8.0.0.GA'
},
{
name: '8.1.0.v20190416065710',
manifest: {
name: '8.1.0.v20190416065710',
version: '8.1.0',
moduleAPIVersion: {
iphone: '2',
android: '4',
windows: '7'
},
timestamp: '4/16/2019 14:03',
githash: '37f6d88',
platforms: [
'iphone',
'android'
]
},
path: '/Users/eharris/Library/Application Support/Titanium/mobilesdk/osx/8.1.0.v20190416065710'
}
]);
mockSDKRequest('sdk-response.json');
const update = await titanium.sdk.checkForUpdate();
expect(update.currentVersion).to.equal('8.0.0.GA');
expect(update.latestVersion).to.equal('8.0.0.GA');
expect(update.productName).to.equal('Titanium SDK');
expect(update.hasUpdate).to.equal(false);
});
});
describe('appc.installer', () => {
it('checkForUpdates with install', async () => {
mockNpmRequest();
const appcChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.withArgs('appc', sinon.match.any, sinon.match.any)
.returns(appcChild);
setTimeout(() => {
appcChild.stdout?.emit('data', '{"NPM":"4.2.12","CLI":"7.1.0-master.13"}');
appcChild.emit('close', 0);
}, 500);
const update = await appc.install.checkForUpdate();
expect(update.currentVersion).to.equal('4.2.12');
expect(update.latestVersion).to.equal('4.2.13');
expect(update.productName).to.equal('Appcelerator CLI (npm)');
expect(update.hasUpdate).to.equal(true);
});
it('checkForUpdates with no core', async () => {
mockNpmRequest();
const appcChild = createChildMock();
const npmChild = createChildMock();
const stub = global.sandbox.stub(child_process, 'spawn');
stub
.withArgs('appc', sinon.match.any, sinon.match.any)
.returns(appcChild);
stub
.withArgs('npm', sinon.match.any, sinon.match.any)
.returns(npmChild);
setTimeout(() => {
appcChild.stderr?.emit('data', '/bin/sh: appc: command not found\n');
appcChild.emit('close', 127);
}, 500);
setTimeout(() => {
npmChild.stdout?.emit('data', `{
"dependencies": {
"appcelerator": {
"version": "4.2.12",
"from": "appcelerator@4.2.11",
"resolved": "https://registry.npmjs.org/appcelerator/-/appcelerator-4.2.11.tgz"
}
}
}`);
npmChild.emit('close', 0);
}, 750);
const update = await appc.install.checkForUpdate();
expect(update.currentVersion).to.equal('4.2.12');
expect(update.latestVersion).to.equal('4.2.13');
expect(update.productName).to.equal('Appcelerator CLI (npm)');
expect(update.hasUpdate).to.equal(true);
});
it('checkForUpdates with no install', async () => {
mockNpmRequest();
const appcChild = createChildMock();
const npmChild = createChildMock();
const stub = global.sandbox.stub(child_process, 'spawn');
stub
.withArgs('appc', sinon.match.any, sinon.match.any)
.returns(appcChild);
stub
.withArgs('npm', sinon.match.any, sinon.match.any)
.returns(npmChild);
setTimeout(() => {
appcChild.stderr?.emit('data', '/bin/sh: appc: command not found');
appcChild.emit('close', 127);
}, 500);
setTimeout(() => {
npmChild.stdout?.emit('data', '{}');
npmChild.emit('close', 0);
}, 750);
const update = await appc.install.checkForUpdate();
expect(update.currentVersion).to.equal(undefined);
expect(update.latestVersion).to.equal('4.2.13');
expect(update.productName).to.equal('Appcelerator CLI (npm)');
expect(update.hasUpdate).to.equal(true);
});
it('checkForUpdates with latest already', async () => {
mockNpmRequest();
const appcChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.returns(appcChild);
setTimeout(() => {
appcChild.stdout?.emit('data', '{"NPM":"4.2.13","CLI":"7.1.0-master.13"}');
appcChild.emit('close', 0);
}, 500);
const update = await appc.install.checkForUpdate();
expect(update.currentVersion).to.equal('4.2.13');
expect(update.latestVersion).to.equal('4.2.13');
expect(update.productName).to.equal('Appcelerator CLI (npm)');
expect(update.hasUpdate).to.equal(false);
});
});
describe('appc.core', () => {
it('checkForUpdate with install', async () => {
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
mockFS({
[installPath]: {
'.version': '4.2.0',
'4.2.0': {
package: {
'package.json': '{ "version": "4.2.0" }'
}
}
},
});
mockAppcCoreRequest('6.6.6');
const update = await appc.core.checkForUpdate();
expect(update.currentVersion).to.equal('4.2.0');
expect(update.latestVersion).to.equal('6.6.6');
expect(update.productName).to.equal('Appcelerator CLI');
expect(update.hasUpdate).to.equal(true);
});
it('checkForUpdate with no install', async () => {
mockFS({});
mockAppcCoreRequest('6.6.6');
const update = await appc.core.checkForUpdate();
expect(update.currentVersion).to.equal(undefined);
expect(update.latestVersion).to.equal('6.6.6');
expect(update.productName).to.equal('Appcelerator CLI');
expect(update.hasUpdate).to.equal(true);
});
it('checkForUpdate with latest installed', async () => {
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
mockFS({
[installPath]: {
'.version': '6.6.6',
'6.6.6': {
package: {
'package.json': '{ "version": "6.6.6" }'
}
}
},
});
mockAppcCoreRequest('6.6.6');
const update = await appc.core.checkForUpdate();
expect(update.currentVersion).to.equal('6.6.6');
expect(update.latestVersion).to.equal('6.6.6');
expect(update.productName).to.equal('Appcelerator CLI');
expect(update.hasUpdate).to.equal(false);
});
it('checkForUpdate with different version file and package.json (dev environment)', async () => {
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
mockFS({
[installPath]: {
'.version': '6.6.6',
'6.6.6': {
package: {
'package.json': '{ "version": "4.2.0" }'
}
}
},
});
mockAppcCoreRequest('6.6.6');
const update = await appc.core.checkForUpdate();
expect(update.currentVersion).to.equal('4.2.0');
expect(update.latestVersion).to.equal('6.6.6');
expect(update.productName).to.equal('Appcelerator CLI');
expect(update.hasUpdate).to.equal(true);
});
});
describe('node', () => {
it('validateEnvironment with no node installed', async () => {
const nodeChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
setTimeout(() => {
nodeChild.emit('close', 0);
}, 500);
const env = await node.checkInstalledVersion();
expect(env).to.equal(undefined);
});
it('validateEnvironment with node installed', async () => {
const nodeChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
setTimeout(() => {
nodeChild.stdout?.emit('data', 'v12.18.1');
nodeChild.emit('close', 0);
}, 500);
const env = await node.checkInstalledVersion();
expect(env).to.deep.equal('12.18.1');
});
it('validateEnvironment with new supported SDK ranges', async () => {
const nodeChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
setTimeout(() => {
nodeChild.stdout?.emit('data', 'v8.7.0');
nodeChild.emit('close', 0);
}, 500);
const env = await node.checkInstalledVersion();
expect(env).to.deep.equal('8.7.0');
});
it('Get update with older version (v8.7.0)', async () => {
mockNodeRequest();
const nodeChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
setTimeout(() => {
nodeChild.stdout?.emit('data', 'v8.7.0');
nodeChild.emit('close', 0);
}, 500);
const url = await node.checkLatestVersion();
expect(url).to.deep.equal('12.18.2');
});
it('Check for update with update availale', async () => {
mockNodeRequest();
const nodeChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
setTimeout(() => {
nodeChild.stdout?.emit('data', 'v12.18.1');
nodeChild.emit('close', 0);
}, 500);
const update = await node.checkForUpdate();
expect(update.currentVersion).to.deep.equal('12.18.1');
expect(update.latestVersion).to.deep.equal('12.18.2');
expect(update.action).to.be.instanceOf(Function);
expect(update.productName).to.deep.equal('Node.js');
expect(update.priority).to.deep.equal(1);
expect(update.hasUpdate).to.deep.equal(true);
});
it('Check for update with up to date version', async () => {
mockNodeRequest();
const nodeChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
setTimeout(() => {
nodeChild.stdout?.emit('data', 'v12.18.2');
nodeChild.emit('close', 0);
}, 500);
const update = await node.checkForUpdate();
expect(update.currentVersion).to.deep.equal('12.18.2');
expect(update.latestVersion).to.deep.equal('12.18.2');
expect(update.action).to.be.instanceOf(Function);
expect(update.productName).to.deep.equal('Node.js');
expect(update.priority).to.deep.equal(1);
expect(update.hasUpdate).to.deep.equal(false);
});
it('Get node release notes', async () => {
const url = await node.getReleaseNotes('v10.13.0');
expect(url).to.deep.equal('https://nodejs.org/en/blog/release/v10.13.0/');
});
});
});
<file_sep>import { run } from 'appcd-subprocess';
import * as fs from 'fs-extra';
import got from 'got';
import os from 'os';
import * as path from 'path';
import * as semver from 'semver';
import { UpdateInfo } from '..';
import { ProductNames } from '../product-names';
import { InstallError } from '../util';
const LATEST_URL = 'https://registry.platform.axway.com/api/appc/latest';
export async function checkInstalledVersion (): Promise<string|undefined> {
const versionFilePath = path.join(os.homedir(), '.appcelerator', 'install', '.version');
if (!await fs.pathExists(versionFilePath)) {
return;
}
const cliVersion = await fs.readFile(versionFilePath, 'utf8');
const packageJson = path.join(os.homedir(), '.appcelerator', 'install', cliVersion, 'package', 'package.json');
const { version } = await fs.readJSON(packageJson);
return version;
}
export async function checkLatestVersion (): Promise<string> {
const { body } = await got(LATEST_URL, {
json: true
});
return body.result[0].version;
}
export async function installUpdate (version: string): Promise<void> {
// todo
const { code, stdout, stderr } = await run('appc', [ 'use', version ], { shell: true, ignoreExitCode: true });
if (code) {
throw new InstallError('Failed to install package', {
code,
stderr,
stdout
});
}
}
export function getReleaseNotes (version: string): string {
return `https://docs.appcelerator.com/platform/latest/#!/guide/Appcelerator_CLI_${version}.GA_Release_Note`;
}
export async function checkForUpdate (): Promise<UpdateInfo> {
const [ currentVersion, latestVersion ] = await Promise.all<string|undefined, string>([
checkInstalledVersion(),
checkLatestVersion()
]);
const updateInfo: UpdateInfo = {
currentVersion,
latestVersion,
action: installUpdate,
productName: ProductNames.AppcCore,
releaseNotes: getReleaseNotes(latestVersion),
priority: 20,
hasUpdate: false
};
if (!currentVersion || semver.gt(latestVersion, currentVersion)) {
updateInfo.hasUpdate = true;
}
return updateInfo;
}
<file_sep>import nock from 'nock';
import * as path from 'path';
export function mockAppcCoreRequest (version: string): void {
nock('https://registry.platform.axway.com')
.get('/api/appc/latest')
.reply(200, {
key: 'result',
'request-id': '6c4fb0e4-a84c-4e46-8d21-c4dee184a84d',
result: [
{
id: '55d62d2a6c03980c1d58fc47',
name: 'appc-cli/appcelerator',
version
}
],
success: true
});
}
export function mockSDKRequest (file: string): void {
nock('https://appc-mobilesdk-server.s3-us-west-2.amazonaws.com')
.get('/releases.json')
.replyWithFile(200, path.join(__dirname, file));
}
export function mockNpmRequest (): void {
nock('https://registry.npmjs.org')
.get('/appcelerator')
.replyWithFile(200, path.join(__dirname, 'npm-response.json'));
}
export function mockNodeRequest(): void {
nock('https://nodejs.org')
.get('/download/release/index.json')
.replyWithFile(200, path.join(__dirname, 'node-response.json'));
}
<file_sep>import * as updates from '../updates';
interface Missing {
name: string;
getInstallInfo (): Promise<updates.UpdateInfo>;
}
interface Installed {
name: string;
version: string;
}
interface EnvironmentInfo {
installed: Installed[];
missing: Missing[];
}
export async function validateEnvironment(supportedVersions?: updates.SupportedVersions): Promise<EnvironmentInfo> {
const environmentInfo: EnvironmentInfo = {
installed: [],
missing: []
};
const nodeVersion = await updates.node.checkInstalledVersion();
if (nodeVersion) {
environmentInfo.installed.push({
name: updates.ProductNames.Node,
version: nodeVersion
});
} else {
environmentInfo.missing.push({
name: updates.ProductNames.Node,
getInstallInfo: () => {
return updates.node.checkForUpdate(supportedVersions?.nodeJS);
}
});
return environmentInfo;
}
const [ coreVersion, installVersion, sdkVersion ] = await Promise.all([
await updates.appc.core.checkInstalledVersion(),
await updates.appc.install.checkInstalledVersion(),
await updates.titanium.sdk.checkInstalledVersion()
]);
if (coreVersion) {
environmentInfo.installed.push({
name: updates.ProductNames.AppcCore,
version: coreVersion
});
} else {
environmentInfo.missing.push({
name: updates.ProductNames.AppcCore,
getInstallInfo: () => {
return updates.appc.core.checkForUpdate();
}
});
}
if (installVersion) {
environmentInfo.installed.push({
name: updates.ProductNames.AppcInstaller,
version: installVersion
});
} else {
environmentInfo.missing.push({
name: updates.ProductNames.AppcInstaller,
getInstallInfo: () => {
return updates.appc.install.checkForUpdate();
}
});
}
if (sdkVersion) {
environmentInfo.installed.push({
name: updates.ProductNames.TitaniumSDK,
version: sdkVersion.name
});
} else {
environmentInfo.missing.push({
name: updates.ProductNames.TitaniumSDK,
getInstallInfo: () => {
return updates.titanium.sdk.checkForUpdate();
}
});
}
return environmentInfo;
}
<file_sep>## [1.0.2](https://github.com/appcelerator/titanium-editor-commons/compare/v1.0.1...v1.0.2) (2020-10-02)
### Bug Fixes
* **env/node:** remove installed version check and sudo ([#215](https://github.com/appcelerator/titanium-editor-commons/issues/215)) ([6c27bf7](https://github.com/appcelerator/titanium-editor-commons/commit/6c27bf7aeb4e3617213744d3a20eb3665e9766be))
## [1.0.1](https://github.com/appcelerator/titanium-editor-commons/compare/v1.0.0...v1.0.1) (2020-09-22)
### Bug Fixes
* **update:** make nodejs supported versions optional ([#208](https://github.com/appcelerator/titanium-editor-commons/issues/208)) ([a20b335](https://github.com/appcelerator/titanium-editor-commons/commit/a20b335b99b6fa37f7b3b6fa471c322e9ab6150f))
# [1.0.0](https://github.com/appcelerator/titanium-editor-commons/compare/v0.4.2...v1.0.0) (2020-09-10)
* chore(deps)!: update dependencies ([e27d041](https://github.com/appcelerator/titanium-editor-commons/commit/e27d041960339e26bcf4e61e64b5268274397c08))
### Features
* **updates:** support installing and detecting nodejs ([#175](https://github.com/appcelerator/titanium-editor-commons/issues/175)) ([11b9bbf](https://github.com/appcelerator/titanium-editor-commons/commit/11b9bbf40a09720b561809447f20ac6e6da985c2))
### BREAKING CHANGES
* Minimum node version is now 10.0.0
# Changelog
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
## [0.5.0](https://github.com/appcelerator/titanium-editor-commons/compare/v0.4.2...v0.5.0) (2020-04-02)
Dependency updates
### โ BREAKING CHANGES
* **deps:** Minimum node version is now 10.0.0
* **deps:** update dependencies ([c3174bc](https://github.com/appcelerator/titanium-editor-commons/commit/c3174bc92f36ad03c4e2a4314fdccee662628d6b))
### [0.4.2](https://github.com/appcelerator/titanium-editor-commons/compare/v0.4.1...v0.4.2) (2019-11-22)
Dependency updates
### [0.4.1](https://github.com/appcelerator/titanium-editor-commons/compare/v0.4.0...v0.4.1) (2019-10-07)
### Features
* generate alloy completions v2 ([#5](https://github.com/appcelerator/titanium-editor-commons/issues/5)) ([65127e3](https://github.com/appcelerator/titanium-editor-commons/commit/65127e3))
## [0.4.0](https://github.com/appcelerator/titanium-editor-commons/compare/v0.3.0...v0.4.0) (2019-09-27)
### โ BREAKING CHANGES
* **deps:** Drops support for version of Node lower than 8.12.0
* **deps:** update to latest dependencies ([4b8cc45](https://github.com/appcelerator/titanium-editor-commons/commit/4b8cc45))
## [0.3.0](https://github.com/appcelerator/titanium-editor-commons/compare/v0.2.0...v0.3.0) (2019-08-26)
### Bug Fixes
* **updates/core:** correct core check to improve usage when using dev env setup ([9196c1a](https://github.com/appcelerator/titanium-editor-commons/commit/9196c1a))
### Features
* **completions:** added completions creation ([#4](https://github.com/appcelerator/titanium-editor-commons/issues/4)) ([30ac157](https://github.com/appcelerator/titanium-editor-commons/commit/30ac157))
## [0.2.0](https://github.com/appcelerator/titanium-editor-commons/compare/v0.1.2...v0.2.0) (2019-06-24)
### Features
* **environment:** add environment check functionality ([#2](https://github.com/appcelerator/titanium-editor-commons/issues/2)) ([a454ac1](https://github.com/appcelerator/titanium-editor-commons/commit/a454ac1))
### [0.1.2](https://github.com/appcelerator/titanium-editor-commons/compare/v0.1.1...v0.1.2) (2019-05-22)
### Bug Fixes
* **updates/appc:** increase priority of appc install ([5ef76f9](https://github.com/appcelerator/titanium-editor-commons/commit/5ef76f9))
<a name="0.1.1"></a>
## [0.1.1](https://github.com/ewanharris/titanium-editor-commons/compare/v0.1.0...v0.1.1) (2019-05-10)
### Bug Fixes
* **updates:** provide direct link to release notes rather than just to latest ([ddbb8b6](https://github.com/ewanharris/titanium-editor-commons/commit/ddbb8b6))
* **updates/appc:** spawn appc to get version, falling back to npm ([13c0c0c](https://github.com/ewanharris/titanium-editor-commons/commit/13c0c0c))
<a name="0.1.0"></a>
# [0.1.0](https://github.com/appcelerator/titanium-editor-commons/compare/v0.0.2...v0.1.0) (2019-05-03)
### Features
* provide metadata on the error object when installing updates ([a09a868](https://github.com/appcelerator/titanium-editor-commons/commit/a09a868))
<a name="0.0.2"></a>
## [0.0.2](https://github.com/appcelerator/titanium-editor-commons/compare/v0.0.1...v0.0.2) (2019-04-29)
# Change Log
All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines.
<file_sep>import * as completion from './completions';
import * as environment from './environment';
import * as updates from './updates';
export {
completion,
environment,
updates
};
<file_sep>import * as core from './core';
import * as install from './installer';
export {
core,
install
};
<file_sep>import * as fs from 'fs-extra';
import * as path from 'path';
import * as core from '../updates/appc/core';
import os from 'os';
export class CustomError extends Error {
public code: string;
constructor (message: string, code: string) {
super(message);
this.code = code;
}
}
export async function getAlloyVersion (): Promise<string> {
const appcPath = path.join(os.homedir(), '.appcelerator', 'install');
const appcVersion = await core.checkInstalledVersion();
if (!appcVersion) {
throw Error('Unable to find installed CLI version.');
}
const alloyPath = path.join(appcPath, appcVersion, 'package', 'node_modules', 'alloy');
const { version: alloyVersion } = await fs.readJSON(path.join(alloyPath, 'package.json'));
return alloyVersion;
}
export function getSDKCompletionsFileName (sdkVersion: string, completionsVersion: number): string {
return path.join(os.homedir(), '.titanium', 'completions', 'titanium', sdkVersion, `completions-v${completionsVersion}.json`);
}
export function getAlloyCompletionsFileName (alloyVersion: string, completionsVersion: number): string {
return path.join(os.homedir(), '.titanium', 'completions', 'alloy', alloyVersion, `completions-v${completionsVersion}.json`);
}
<file_sep>import * as sdk from './sdk';
export {
sdk
};
<file_sep>declare module 'libnpm';
<file_sep>import * as semver from 'semver';
import { sdk } from 'titaniumlib';
import { UpdateInfo } from '..';
import { ProductNames } from '../product-names';
import * as util from '../util';
interface SDKInfo {
name: string;
version: string;
}
export async function checkInstalledVersion (): Promise<SDKInfo|undefined> {
let latestSDK;
for (const { manifest, name } of sdk.getInstalledSDKs(true)) {
// ignore if not a GA
if (!name.includes('.GA')) {
continue;
}
if (!latestSDK || semver.gt(manifest.version, latestSDK.version)) {
latestSDK = {
name,
version: manifest.version
};
}
}
return latestSDK;
}
export async function checkLatestVersion (): Promise<SDKInfo> {
const { latest } = await sdk.getReleases();
return {
name: latest.name,
version: latest.version
};
}
export async function installUpdate (version: string): Promise<void> {
try {
await sdk.install({
uri: version
});
} catch (error) {
throw new util.InstallError('Failed to install package', error);
}
}
export function getReleaseNotes (version: string): string {
return `https://docs.appcelerator.com/platform/latest/#!/guide/Titanium_SDK_${version}_Release_Note`;
}
export async function checkForUpdate (): Promise<UpdateInfo> {
const [ currentVersion, latestVersion ] = await Promise.all<SDKInfo|undefined, SDKInfo>([
checkInstalledVersion(),
checkLatestVersion()
]);
const updateInfo: UpdateInfo = {
currentVersion: currentVersion ? currentVersion.name : '',
latestVersion: latestVersion.name,
action: installUpdate,
productName: ProductNames.TitaniumSDK,
releaseNotes: getReleaseNotes(latestVersion.name),
priority: 100,
hasUpdate: false
};
if (!currentVersion || semver.gt(latestVersion.version, currentVersion.version)) {
updateInfo.hasUpdate = true;
}
return updateInfo;
}
<file_sep>import * as fs from 'fs-extra';
import * as semver from 'semver';
import * as util from '../util';
import { run } from 'appcd-subprocess';
import { UpdateInfo, ProductNames } from '..';
import { promisify } from 'util';
import stream from 'stream';
import got from 'got';
import os from 'os';
async function getVersion(): Promise<string | undefined> {
let version;
try {
const { stdout } = await run('node', [ '--version' ], { shell: true });
version = semver.clean(stdout) || undefined;
} catch (error) {
return;
}
return version;
}
export async function checkInstalledVersion(): Promise<string | undefined> {
const version = await getVersion();
return version;
}
export async function checkLatestVersion(supportedVersions = '10.x || 12.x'): Promise<string> {
const { body } = await got('https://nodejs.org/download/release/index.json', {
json: true
});
const versions = body.map(((element: { version: string }) => element.version));
let latestVersion: string|null = semver.maxSatisfying(versions, supportedVersions) as string;
latestVersion = semver.clean(latestVersion);
if (!latestVersion) {
throw new Error(`No versions satisfy the supported version ${supportedVersions}`);
}
return latestVersion;
}
export async function installUpdate(version: string): Promise<void> {
let extension = '.pkg';
if (process.platform === 'win32') {
extension = ((process.arch === 'x64') ? '-x64.msi' : '-x86.msi');
}
const url = `https://nodejs.org/dist/v${semver.clean(version)}/node-v${semver.clean(version)}${extension}`;
const pipeline = promisify(stream.pipeline);
try {
await pipeline(
got.stream(url),
fs.createWriteStream(`${os.tmpdir()}file${extension}`)
);
await fs.ensureFile(`${os.tmpdir()}file${extension}`);
} catch (err) {
throw new Error('Node.js failed to download');
}
if (process.platform === 'win32') {
const { code, stdout, stderr } = await run('msiexec', [ '/i', `${os.tmpdir()}file${extension}` ], { shell: true, ignoreExitCode: true });
if (code) {
const metadata = {
errorCode: '',
exitCode: code,
stderr,
stdout,
command: `msiexec /i ${os.tmpdir()}file${extension}`
};
throw new util.InstallError('Failed to install package', metadata);
}
} else if (process.platform === 'darwin') {
const { code, stdout, stderr } = await run('installer', [ '-pkg', `${os.tmpdir()}file${extension}`, '-target', '/' ], { shell: true, ignoreExitCode: true });
if (code) {
const metadata = {
errorCode: '',
exitCode: code,
stderr,
stdout,
command: `installer -pkg ${os.tmpdir()}file${extension} -target /`
};
if (stdout === 'installer: Must be run as root to install this package.\n') {
metadata.errorCode = 'EACCES';
}
throw new util.InstallError('Failed to install package', metadata);
}
} else {
throw new Error('Failed to download due to unsupported platform');
}
}
export function getReleaseNotes(version: string): string {
return `https://nodejs.org/en/blog/release/v${semver.clean(version)}/`;
}
export async function checkForUpdate(supportedVersions?: string): Promise<UpdateInfo> {
const [ currentVersion, latestVersion ] = await Promise.all<string | undefined, string>([
checkInstalledVersion(),
checkLatestVersion(supportedVersions)
]);
const updateInfo: UpdateInfo = {
currentVersion,
latestVersion,
action: installUpdate,
productName: ProductNames.Node,
releaseNotes: getReleaseNotes(latestVersion),
priority: 1,
hasUpdate: false
};
if (!currentVersion || semver.gt(latestVersion, currentVersion)) {
updateInfo.hasUpdate = true;
}
return updateInfo;
}
<file_sep>interface BranchData {
defaultBranch: string;
branches: string[];
}
interface BuildData {
[key: string]: {
date: Date;
githash: string;
ts: string;
url: string;
version: string;
};
}
interface ReleaseInfo {
[key: string]: {
name: string;
url: string;
version: string;
};
}
declare class TitaniumSDK {
name: string;
manifest: {
githash: string;
moduleAPIVersion: {
[key: string]: string;
};
name: string;
platforms: string[];
timestamp: string;
version: string;
};
path: string;
}
declare module 'titaniumlib' {
namespace sdk {
interface InstallParams {
downloadDir?: string;
installDir?: string;
keep?: boolean;
overwrite?: boolean;
uri?: string;
}
function getBranches (): Promise<BranchData>;
function getBuilds (branch?: string): Promise<BuildData>;
function getInstalledSDKs (force?: boolean): TitaniumSDK[];
function getPaths (): string[];
function getReleases (noLatest?: boolean): Promise<ReleaseInfo>;
function install (params?: InstallParams): Promise<string>;
function uninstall (nameOrPath: string): Promise<TitaniumSDK[]>;
}
}
<file_sep>/* eslint @typescript-eslint/no-namespace: off */
import os from 'os';
import * as sinon from 'sinon';
import * as tmp from 'tmp';
declare global {
namespace NodeJS {
interface Global {
sandbox: sinon.SinonSandbox;
TMP_DIR: tmp.DirResult;
}
}
}
beforeEach(() => {
global.TMP_DIR = tmp.dirSync();
global.sandbox = sinon.createSandbox();
global.sandbox.stub(os, 'homedir').returns(global.TMP_DIR.name);
});
afterEach(() => {
global.TMP_DIR.removeCallback();
global.sandbox.restore();
});
<file_sep>interface InstallErrorMetadata {
code?: number;
errorCode?: string;
exitCode?: number;
stderr: string;
stdout: string;
command?: string;
}
export class InstallError extends Error {
public code: string;
public metadata: InstallErrorMetadata;
constructor (
message: string,
metadata: InstallErrorMetadata
) {
super(message);
this.code = 'EINSTALLFAILED';
this.metadata = metadata || {};
}
}
<file_sep>declare module 'appcd-subprocess' {
import { SpawnOptions } from 'child_process';
interface RunResponse {
code: number;
stdout: string;
stderr: string;
}
interface RunOptions extends SpawnOptions {
ignoreExitCode?: boolean;
}
function run (cmd: string, args: string[], opts: RunOptions): RunResponse;
}
// export const bat: string;
// export const cmd: string;
// export const exe: string;
// export function spawn(params: any): any;
// export function which(executables: any, opts: any): any;
<file_sep># titanium-editor-commons
titanium-editor-commons in a common library for the [VS Code] and [atom] editor plugins for [Titanium SDK]. It aims to provide a common layer for the two projects.
<file_sep>import { environment } from '../src';
import * as titaniumlib from 'titaniumlib';
import { expect } from 'chai';
import child_process from 'child_process';
import { EventEmitter } from 'events';
import mockFS from 'mock-fs';
import nock from 'nock';
import os from 'os';
import * as path from 'path';
import stream from 'stream';
import * as sinon from 'sinon';
import { node } from '../src/updates';
function createChildMock (): child_process.ChildProcess {
const fakeChild = new EventEmitter() as child_process.ChildProcess;
fakeChild.stdout = new EventEmitter() as stream.Readable;
fakeChild.stderr = new EventEmitter() as stream.Readable;
return fakeChild;
}
describe('environment', () => {
beforeEach(() => {
mockFS.restore();
});
afterEach(() => {
nock.cleanAll();
mockFS.restore();
});
describe('validateEnvironment', () => {
it('validateEnvironment with all installed component ', async () => {
const sdkStub = global.sandbox.stub(titaniumlib.sdk, 'getInstalledSDKs');
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
sdkStub.returns([
{
name: '7.5.0.GA',
manifest: {
name: '7.5.0.v20181115134726',
version: '7.5.0',
moduleAPIVersion: {
iphone: '2',
android: '4',
windows: '6'
},
timestamp: '11/15/2018 21:52',
githash: '2e5a7423d0',
platforms: [
'iphone',
'android'
]
},
path: '/Users/eharris/Library/Application Support/Titanium/mobilesdk/osx/7.5.0.GA'
},
{
name: '8.1.0.v20190416065710',
manifest: {
name: '8.1.0.v20190416065710',
version: '8.1.0',
moduleAPIVersion: {
iphone: '2',
android: '4',
windows: '7'
},
timestamp: '4/16/2019 14:03',
githash: '37f6d88',
platforms: [
'iphone',
'android'
]
},
path: '/Users/eharris/Library/Application Support/Titanium/mobilesdk/osx/8.1.0.v20190416065710'
}
]);
mockFS({
[installPath]: {
'.version': '4.2.0',
'4.2.0': {
package: {
'package.json': '{ "version": "4.2.0" }'
}
}
},
});
const appcChild = createChildMock();
global.sandbox.stub(child_process, 'spawn')
.returns(appcChild);
setTimeout(() => {
appcChild.stdout?.emit('data', '{"NPM":"4.2.12","CLI":"4.2.0"}');
appcChild.emit('close', 0);
}, 500);
global.sandbox.stub(node, 'checkInstalledVersion')
.resolves('12.18.2');
const env = await environment.validateEnvironment();
expect(env.missing).to.deep.equal([]);
expect(env.installed).to.deep.equal(
[
{ name: 'Node.js', version: '12.18.2' },
{ name: 'Appcelerator CLI', version: '4.2.0' },
{ name: 'Appcelerator CLI (npm)', version: '4.2.12' },
{ name: 'Titanium SDK', version: '7.5.0.GA' }
]
);
});
it('validateEnvironment with no installed SDKS', async () => {
const sdkStub = global.sandbox.stub(titaniumlib.sdk, 'getInstalledSDKs');
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
sdkStub.returns([]);
mockFS({
[installPath]: {
'.version': '4.2.0',
'4.2.0': {
package: {
'package.json': '{ "version": "4.2.0" }'
}
}
},
});
const appcChild = createChildMock();
const nodeChild = createChildMock();
const stub = global.sandbox.stub(child_process, 'spawn');
stub
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
stub
.withArgs('appc', sinon.match.any, sinon.match.any)
.returns(appcChild);
setTimeout(() => {
nodeChild.stdout?.emit('data', 'v12.18.1');
nodeChild.emit('close', 0);
}, 500);
setTimeout(() => {
appcChild.stdout?.emit('data', '{"NPM":"4.2.12","CLI":"4.2.0"}');
appcChild.emit('close', 0);
}, 750);
const env = await environment.validateEnvironment();
expect(env.missing[0].name).to.deep.equal('Titanium SDK');
expect(env.installed).to.deep.equal(
[
{ name: 'Node.js', version: '12.18.1' },
{ name: 'Appcelerator CLI', version: '4.2.0' },
{ name: 'Appcelerator CLI (npm)', version: '4.2.12' }
]
);
});
it('validateEnvironment with no installed core', async () => {
mockFS({});
const appcChild = createChildMock();
const nodeChild = createChildMock();
const stub = global.sandbox.stub(child_process, 'spawn');
stub
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
stub
.withArgs('appc', sinon.match.any, sinon.match.any)
.returns(appcChild);
setTimeout(() => {
nodeChild.stdout?.emit('data', 'v12.18.1');
nodeChild.emit('close', 0);
}, 500);
setTimeout(() => {
appcChild.stdout?.emit('data', '{"NPM":"4.2.12"}');
appcChild.emit('close', 0);
}, 750);
const env = await environment.validateEnvironment();
expect(env.missing[0].name).to.deep.equal('Appcelerator CLI');
expect(env.installed).to.deep.equal(
[
{ name: 'Node.js', version: '12.18.1' },
{ name: 'Appcelerator CLI (npm)', version: '4.2.12' }
]
);
});
it('validateEnvironment with no installed appc npm', async () => {
const sdkStub = global.sandbox.stub(titaniumlib.sdk, 'getInstalledSDKs');
const installPath = path.join(os.homedir(), '.appcelerator', 'install');
sdkStub.returns([
{
name: '7.5.0.GA',
manifest: {
name: '7.5.0.v20181115134726',
version: '7.5.0',
moduleAPIVersion: {
iphone: '2',
android: '4',
windows: '6'
},
timestamp: '11/15/2018 21:52',
githash: '2e5a7423d0',
platforms: [
'iphone',
'android'
]
},
path: '/Users/eharris/Library/Application Support/Titanium/mobilesdk/osx/7.5.0.GA'
}
]);
mockFS({
[installPath]: {
'.version': '4.2.0',
'4.2.0': {
package: {
'package.json': '{ "version": "4.2.0" }'
}
}
},
});
const appcChild = createChildMock();
const npmChild = createChildMock();
const nodeChild = createChildMock();
const stub = global.sandbox.stub(child_process, 'spawn');
stub
.withArgs('node', sinon.match.any, sinon.match.any)
.returns(nodeChild);
stub
.withArgs('appc', sinon.match.any, sinon.match.any)
.returns(appcChild);
stub
.withArgs('npm', sinon.match.any, sinon.match.any)
.returns(npmChild);
setTimeout(() => {
nodeChild.stdout?.emit('data', 'v12.18.1');
nodeChild.emit('close', 0);
}, 500);
setTimeout(() => {
appcChild.stderr?.emit('data', '/bin/sh: appc: command not found');
appcChild.emit('close', 127);
}, 750);
setTimeout(() => {
npmChild.stdout?.emit('data', '{}');
npmChild.emit('close', 0);
}, 1000);
const env = await environment.validateEnvironment();
expect(env.missing[0].name).to.deep.equal('Appcelerator CLI (npm)');
expect(env.installed).to.deep.equal(
[
{ name: 'Node.js', version: '12.18.1' },
{ name: 'Appcelerator CLI', version: '4.2.0' },
{ name: 'Titanium SDK', version: '7.5.0.GA' }
]
);
});
});
});
<file_sep>export enum ProductNames {
AppcInstaller = 'Appcelerator CLI (npm)',
AppcCore = 'Appcelerator CLI',
TitaniumSDK = 'Titanium SDK',
Node = 'Node.js'
}
<file_sep>import * as appc from './appc';
import { ProductNames } from './product-names';
import * as node from './node';
import * as titanium from './titanium';
interface UpdateInfo {
currentVersion: string|undefined;
hasUpdate: boolean;
latestVersion: string;
productName: string;
releaseNotes: string;
priority: number;
action (version: string): void;
}
export interface SupportedVersions {
nodeJS?: string;
}
async function checkAllUpdates(supportedVersions?: SupportedVersions): Promise<UpdateInfo[]> {
const updates = await Promise.all([
node.checkForUpdate(supportedVersions?.nodeJS),
appc.core.checkForUpdate(),
appc.install.checkForUpdate(),
titanium.sdk.checkForUpdate()
]);
return updates.filter(update => update && update.hasUpdate);
}
export {
UpdateInfo,
checkAllUpdates,
appc,
node,
titanium,
ProductNames
};
|
47c1da15405728d7d99cc8b54f8f5ea389302054
|
[
"Markdown",
"TypeScript"
] | 22 |
TypeScript
|
longton95/titanium-editor-commons
|
ad9b307c73c751364ca337003fc4bea572c51483
|
6ac567d2fa23bef86c89122e59f122696f04b66d
|
refs/heads/master
|
<repo_name>nlaz/hackny-checkin<file_sep>/README.md
# hackNY Checkin
**An example hackathon checkin app built on [my.mlh.io](http://my.mlh.io/) for Android**

<file_sep>/app/src/main/java/hackny/checkin/MainActivityFragment.java
package hackny.checkin;
import android.app.Fragment;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;
import hackny.checkin.models.User;
import retrofit.Callback;
import retrofit.RestAdapter;
import retrofit.RetrofitError;
import retrofit.client.Response;
/**
* A placeholder fragment containing a simple view.
*/
public class MainActivityFragment extends Fragment {
private static final String TAG = "MainActivityFragment";
private List<User> objects;
private ListView listView;
private CheckInAdapter adapter;
private CheckInService service;
private Callback callback;
public MainActivityFragment() {
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_main, container, false);
setHasOptionsMenu(true);
listView = (ListView) view.findViewById(R.id.listview);
objects = new ArrayList<User>();
adapter = new CheckInAdapter(getActivity(), objects);
listView.setAdapter(adapter);
RestAdapter restAdapter = new RestAdapter.Builder()
.setEndpoint("http://my.mlh.io")
.build();
service = restAdapter.create(CheckInService.class);
callback = new Callback<List<User>>() {
@Override
public void success(List<User> users, Response response) {
Log.d(TAG, users.toString());
objects.clear();
for (User user : users) {
objects.add(user);
}
adapter.notifyDataSetChanged();
}
@Override
public void failure(RetrofitError error) {
Log.e(TAG, error.toString());
}
};
service.listUsers(BuildConfig.HACKNY_APP_ID, BuildConfig.HACKNY_APP_SECRET, callback);
return view;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
return false;
case R.id.refresh:
service.listUsers(BuildConfig.HACKNY_APP_ID, BuildConfig.HACKNY_APP_SECRET, callback);
return true;
default:
break;
}
return false;
}
public class CheckInAdapter extends BaseAdapter {
private LayoutInflater mInflater;
private List<User> objects;
public CheckInAdapter(Context context, List<User> objects){
mInflater = LayoutInflater.from(context);
this.objects = objects;
}
@Override
public int getCount() {
return objects.size();
}
@Override
public Object getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view;
ViewHolder holder;
if (convertView == null){
view = mInflater.inflate(R.layout.list_item, parent, false);
holder = new ViewHolder(view);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
User user = objects.get(position);
holder.name.setText(user.getFull_name());
holder.school.setText(user.getSchool().getName());
holder.shirt.setText(user.getShirt_size());
return view;
}
private class ViewHolder {
public CheckBox checkBox;
public TextView name;
public TextView school;
public TextView shirt;
public ViewHolder(View view){
checkBox = (CheckBox) view.findViewById(R.id.checkin);
name = (TextView) view.findViewById(R.id.name);
school = (TextView) view.findViewById(R.id.school);
shirt = (TextView) view.findViewById(R.id.shirt_size);
}
}
}
}
|
e1992077b6b10cb6076ef40d22cba70e37dfa13b
|
[
"Markdown",
"Java"
] | 2 |
Markdown
|
nlaz/hackny-checkin
|
5cbdf8c9e17c34e8518ae2e5af19a8101790abe3
|
e8931ce4c339aac6adb04e55ba38e11548a3934f
|
refs/heads/main
|
<file_sep>class CountdownTimer {
constructor({ selector, targetDate }) {
this.selector = selector;
this.targetDate = targetDate;
this.intervalId = null;
this.start();
}
start() {
const refs = {
daysClock: document.querySelector(`${this.selector} [data-value="days"]`),
hoursClock: document.querySelector(
`${this.selector} [data-value="hours"]`,
),
minsClock: document.querySelector(`${this.selector} [data-value="mins"]`),
secsClock: document.querySelector(`${this.selector} [data-value="secs"]`),
};
this.intervalId = setInterval(() => {
const currentTime = Date.now();
const time = this.targetDate - currentTime;
if (time < 1000) {
clearInterval(this.intervalId);
}
refs.daysClock.textContent = Math.floor(time / (1000 * 60 * 60 * 24));
refs.hoursClock.textContent = String(
Math.floor((time % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)),
).padStart(2, '0');
refs.minsClock.textContent = String(
Math.floor((time % (1000 * 60 * 60)) / (1000 * 60)),
).padStart(2, '0');
refs.secsClock.textContent = String(
Math.floor((time % (1000 * 60)) / 1000),
).padStart(2, '0');
}, 1000);
}
}
new CountdownTimer({
selector: '#timer-1',
targetDate: new Date('00:00 Aug 29, 2021'),
});
|
e0194fb2add9d1edf60e7655a7d0491983169bf5
|
[
"JavaScript"
] | 1 |
JavaScript
|
Sashalom1991/goit-js-hw-11-timer
|
aeb3801cd64b7d5e1f15feb40f7b969db442b1ed
|
8108debd7518a9b86def05415b7164ef4064187a
|
refs/heads/master
|
<file_sep>package ru.ok.technopolis.students;
import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
public class MainActivity extends Activity {
private List<Student> students;
private StudentAdapter studentAdapter;
private Student currentStudent;
private Student prevStudent;
private final Student DEFAULTPREV = new Student(" ", " ", false, android.R.color.transparent);
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
RecyclerView recyclerView = findViewById(R.id.list);
students = new ArrayList<>();
prevStudent = DEFAULTPREV;
studentAdapter = new StudentAdapter(students, new StudentAdapter.Listener() {
@Override
public void onStudentClick(Student student) {
EditText firstName = findViewById(R.id.first_name_info);
firstName.setText(student.getFirstName());
if (student.getFirstName().equals("")) {
firstName.setHint(R.string.default_firstname);
}
EditText secondName = findViewById(R.id.second_name_info);
secondName.setText(student.getSecondName());
if (student.getSecondName().equals("")) {
secondName.setHint(R.string.default_secondname);
}
ImageView photo = findViewById(R.id.big_photo);
photo.setImageResource(student.getPhoto());
CheckBox checkBox = findViewById(R.id.checkbox);
checkBox.setChecked(student.isMaleGender());
student.setInFocus(true);
if (currentStudent != null) {
prevStudent = currentStudent;
}
currentStudent = student;
if (!prevStudent.equals(currentStudent)) {
prevStudent.setInFocus(false);
}
studentAdapter.notifyDataSetChanged();
}
});
recyclerView.setAdapter(studentAdapter);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
recyclerView.setLayoutManager(linearLayoutManager);
setupAddButton();
setupDeleteButton();
setupSaveButton();
}
private void setupAddButton() {
Button addButton = findViewById(R.id.add_button);
addButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Random random = new Random();
boolean maleGender = random.nextBoolean();
int startPhoto = 0;
if (maleGender) {
switch (random.nextInt(3)) {
case 0: startPhoto = R.drawable.male_1;
break;
case 1: startPhoto = R.drawable.male_2;
break;
case 2: startPhoto = R.drawable.male_3;
break;
}
} else {
switch (random.nextInt(3)) {
case 0: startPhoto = R.drawable.female_1;
break;
case 1: startPhoto = R.drawable.female_2;
break;
case 2: startPhoto = R.drawable.female_3;
break;
}
}
students.add(new Student("", "", maleGender, startPhoto));
studentAdapter.notifyDataSetChanged();
}
});
}
private void setupDeleteButton() {
Button deleteButton = findViewById(R.id.delete_button);
deleteButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
int size = students.size();
if (size != 0) {
if (size > 1) {
int index = students.indexOf(currentStudent);
if (index == 0) {
++index;
} else {
if (index == size - 1) {
--index;
} else {
++index;
}
}
Student tempStd = currentStudent;
currentStudent = students.get(index);
currentStudent.setInFocus(true);
students.remove(tempStd);
EditText firstName = findViewById(R.id.first_name_info);
firstName.setText(currentStudent.getFirstName());
EditText secondName = findViewById(R.id.second_name_info);
secondName.setText(currentStudent.getSecondName());
ImageView photo = findViewById(R.id.big_photo);
photo.setImageResource(currentStudent.getPhoto());
CheckBox checkBox = findViewById(R.id.checkbox);
checkBox.setChecked(currentStudent.isMaleGender());
} else {
students.remove(currentStudent);
currentStudent = null;
prevStudent = DEFAULTPREV;
EditText firstName = findViewById(R.id.first_name_info);
firstName.setText("");
firstName.setHint(R.string.default_firstname);
EditText secondName = findViewById(R.id.second_name_info);
secondName.setText("");
secondName.setHint(R.string.default_secondname);
ImageView photo = findViewById(R.id.big_photo);
photo.setImageResource(android.R.color.transparent);
CheckBox checkBox = findViewById(R.id.checkbox);
checkBox.setChecked(false);
}
}
studentAdapter.notifyDataSetChanged();
}
});
}
private void setupSaveButton() {
Button saveButton = findViewById(R.id.save_button);
saveButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentStudent != null) {
EditText firstNameInfo = findViewById(R.id.first_name_info);
EditText secondNameInfo = findViewById(R.id.second_name_info);
firstNameInfo.setText(firstNameInfo.getText().toString().trim().replace("\n", "").replace(" ", ""));
secondNameInfo.setText(secondNameInfo.getText().toString().trim().replace("\n", "").replace(" ", ""));
if (!firstNameInfo.getText().toString().equals("") &&
!secondNameInfo.getText().toString().equals("")) {
int index = students.indexOf(currentStudent);
currentStudent.setFirstName(firstNameInfo.getText().toString());
currentStudent.setSecondName(secondNameInfo.getText().toString());
ImageView image = findViewById(R.id.big_photo);
CheckBox checkBox = findViewById(R.id.checkbox);
if (checkBox.isChecked() != currentStudent.isMaleGender()) {
Random random = new Random();
if (checkBox.isChecked()) {
switch (random.nextInt(3)) {
case 0: currentStudent.setPhoto(R.drawable.male_1);
break;
case 1: currentStudent.setPhoto(R.drawable.male_2);
break;
case 2: currentStudent.setPhoto(R.drawable.male_3);
break;
}
} else {
switch (random.nextInt(3)) {
case 0: currentStudent.setPhoto(R.drawable.female_1);
break;
case 1: currentStudent.setPhoto(R.drawable.female_2);
break;
case 2: currentStudent.setPhoto(R.drawable.female_3);
break;
}
}
}
image.setImageResource(currentStudent.getPhoto());
currentStudent.setMaleGender(checkBox.isChecked());
students.set(index, currentStudent);
studentAdapter.notifyDataSetChanged();
}
else {
Toast.makeText(MainActivity.this, R.string.toast_invalid, Toast.LENGTH_SHORT).show();
}
}
}
});
}
}
|
5c113189060cdd28711260bbbbf89e2a6f19a4fb
|
[
"Java"
] | 1 |
Java
|
yaroslaver/students_homework
|
42cc5dccf393111fb43bea0e7b5468e9ff8f75a9
|
737df34d757865e69cc9f7b460fa331847c857b9
|
refs/heads/master
|
<repo_name>Hild-Franck/yapwe<file_sep>/ducks/index.js
import { reducer as mainReducer } from './main'
export const reducers = {
mainReducer
}<file_sep>/ducks/main/actionCreators.js
import { PAGE_NOT_FOUND, WELCOME } from './actions'
export const pageNotFound = () => ({
type: PAGE_NOT_FOUND
})
export function sayWelcome(message) {
return {
type: WELCOME,
payload: message
}
}<file_sep>/ducks/main/actions.js
export const PAGE_NOT_FOUND = '@app/PAGE_NOT_FOUND'
export const WELCOME = '@app/WELCOME'
|
3e1dd84100b02ff2f44d3402df67b1716fcc610f
|
[
"JavaScript"
] | 3 |
JavaScript
|
Hild-Franck/yapwe
|
6261915baaea0109a33e734f2690325b8ef064a3
|
16003bfe5f1ae294b5fe19053da53834b48a8f4a
|
refs/heads/master
|
<file_sep># cookiecutter-golang-gin
This sets up a Golang Gin web application with a health check, basic test, docker and JSON logging
## Prerequisites
Install cookiecutter
```
sudo pip install cookiecutter
```
## Using
```
cookiecutter https://github.com/shokunin/cookiecutter-golang-gin.git
```
Answer the questions
cd into the app directory and run
```
make
./APPLICATION_NAME
curl localhost:8080/health
```
<file_sep>package main
import (
"github.com/{{cookiecutter.github_handle}}/{{cookiecutter.app_name}}/handlers/healthcheck"
"github.com/{{cookiecutter.github_handle}}/{{cookiecutter.app_name}}/handlers/app"
"github.com/gin-gonic/gin"
"github.com/shokunin/contrib/ginrus"
"github.com/sirupsen/logrus"
"time"
)
func main() {
router := gin.New()
logrus.SetFormatter(&logrus.JSONFormatter{})
router.Use(ginrus.Ginrus(logrus.StandardLogger(), time.RFC3339, true, "{{cookiecutter.app_name}}"))
// Start routes
router.GET("/health", healthcheck.HealthCheck)
router.GET("/", app.AppRoot)
// RUN rabit run
router.Run() // listen and serve on 0.0.0.0:8080
}
<file_sep># {{cookiecutter.app_name}}
{{cookiecutter.short_description}}
## Building
### Mac/Linux
0) set GOROOT environment variable
1) Install Go and Make
2) make
### Docker
0) set GOROOT environment variable
1) Install Docker, Go and Make
2) make docker
## Running
### Mac/Linux
```
./{{cookiecutter.app_name}}
```
### Docker
```
docker pull {{cookiecutter.docker_location}}/{{cookiecutter.app_name}}:latest
docker run -i -t -p 8080:8080 {{cookiecutter.docker_location}}/{{cookiecutter.app_name}}
```
## Testing
run either the docker container or the raw application binary
```
curl http://localhost:8080/health
```
---
Copyright ยฉ {{cookiecutter.release_date.split('-')[0]}}, {{ cookiecutter.full_name }}
<file_sep># Note you cannot run golang binaries on Alpine directly
FROM debian:buster-slim
MAINTAINER {{cookiecutter.email}}
COPY {{cookiecutter.app_name}} /{{cookiecutter.app_name}}
WORKDIR /
ENV GIN_MODE=release
EXPOSE 8080
ENTRYPOINT [ "/{{cookiecutter.app_name}}" ]
<file_sep>package app
import (
"github.com/gin-gonic/gin"
)
func AppRoot(c *gin.Context) {
c.JSON(200, gin.H{
"message": "This is root",
})
}
|
cbfb87c26eb75f1b08d62aaaf562f36d61a78840
|
[
"Markdown",
"Go",
"Dockerfile"
] | 5 |
Markdown
|
shokunin/cookiecutter-golang-gin
|
f74352d98037097b3d6ebf0126413e8d0f310e8a
|
89745faadec4051e0b4ad0ead137b1fa9eaeaf37
|
refs/heads/master
|
<file_sep>library(shiny)
library(datasets)
data(Orange)
# calcul for the mean of the circumference between the trees
x <- unique(Orange$age)
y <- numeric()
for(i in 1:7){y <- c(y, mean(Orange$circumference[Orange$age==x[i]]))}
# regression model for inputage
reg <- nls(y~SSlogis(x, Asym, xmid, scal))
predictioncirc <- function(inputage) predict(reg, list(x=inputage))[1]
# regression model for inputcirc
reg2 <- nls(x~SSlogis(y, Asym, xmid, scal))
predictionage <- function(inputcirc) predict(reg2, list(y=inputcirc))[1]
shinyServer(
function(input, output) {
# plot
output$graph <- renderPlot({
plot(circumference~age, col=Tree, data=Orange, xlab="Age (days)", ylab="Circumference (mm)", main="Circumference according to the age for 5 orange trees")
age <- seq(0, 1600, length.out = 101)
lines(age, predict(reg, list(x = age)))
})
# prediction
output$circ <- renderPrint({predictioncirc(input$inputage)})
output$age <- renderPrint({predictionage(input$inputcirc)})
}
)<file_sep># ShinyApp
ui.R and server.R of ShinyApp Coursera
<file_sep>library(shiny)
shinyUI(pageWithSidebar(
headerPanel("Prediction of the age of an Orange Tree"),
sidebarPanel(
p("Age of the trees can be approximate by their circumference. Thanks to a database (Orange, from datasets package in R), we can do some predictions! Try it !"),
numericInput("inputage", "Enter an age (days)", 100, min=100, max=1600, step=1),
h2("Prediction of the circumference:"),
verbatimTextOutput("circ"),
numericInput("inputcirc", "Enter a circumference (mm)", 30, min=30, max=300, step=1),
h2("Prediction of the age:"),
verbatimTextOutput("age"),
submitButton("Calcul")
),
mainPanel(
plotOutput("graph"),
br(),
p("Of course, due to the small size of the data base, and due to the type of the fitting curve, it exists an error in the approximation, error which increases when we go far from the middle of the S-shape fitting curve. It could be a first model, which can be improved with other datasets, and maybe other trees ! It could be interesting to see the difference in the growth between tree species for example ! Have fun !")
)
))
|
198d4b011c344260b53819ed373fc158b2cc3b58
|
[
"Markdown",
"R"
] | 3 |
R
|
steph-d/ShinyApp
|
767fdac26996bf2a5cac4257074a799701beea57
|
824b72976c81764a6a4a46c692aec47f3a84741e
|
refs/heads/master
|
<repo_name>evry-bergen/toolbox-reference-angular<file_sep>/src/app/error/shared/error.module.ts
// modules
import { TranslateModule } from '@ngx-translate/core';
import { ErrorRouterModule } from 'app/error/shared/error.route';
// component
import { ErrorComponent } from 'app/error/error.component';
import {NgModule} from '@angular/core';
@NgModule({
imports: [TranslateModule, ErrorRouterModule],
exports: [],
declarations: [ErrorComponent],
providers: [],
})
export class ErrorModule {
}
<file_sep>/src/app/error/error.component.spec.ts
import { TranslateModule } from '@ngx-translate/core';
import { ErrorComponent } from 'app/error/error.component';
import {async, TestBed} from '@angular/core/testing';
import {RouterTestingModule} from '@angular/router/testing';
describe('AdminComponent test', () => {
beforeEach(async(() => {
// Example service mock
TestBed.configureTestingModule({
declarations: [
ErrorComponent,
],
imports: [
RouterTestingModule,
TranslateModule.forRoot(),
],
providers: [],
}).compileComponents();
}));
it('should create the admin component', async(() => {
const fixture = TestBed.createComponent(ErrorComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
});
<file_sep>/src/app/error/shared/error.route.ts
import { ErrorComponent } from 'app/error/error.component';
import {RouterModule, Routes} from '@angular/router';
const ERROR_ROUTES: Routes = [
{
path: '404',
component: ErrorComponent,
},
];
export let ErrorRouterModule = RouterModule.forRoot(ERROR_ROUTES);
<file_sep>/src/app/shared/interceptor/HttpInterceptorHandler.ts
/**
* The following class is intercepting the HTTP-request.
* Make it possible to grab HTML status codes etc for instance logging or error handling.
*/
import {HttpEvent, HttpHandler, HttpInterceptor, HttpRequest} from '@angular/common/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs';
@Injectable()
export class HttpInterceptorHandler implements HttpInterceptor {
intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
return next.handle(req);
}
}
<file_sep>/src/app/shared/spinner/spinner.service.ts
import {Injectable} from '@angular/core';
import {BehaviorSubject} from 'rxjs';
@Injectable()
export class SpinnerService {
counter = 0;
private _httpRequestInProgress = new BehaviorSubject<number>(0);
requestInProgress$ = this._httpRequestInProgress.asObservable();
startRequest(): void {
this.counter++;
this.setRequestNumber(this.counter);
}
endRequest(): void {
this.counter--;
this.setRequestNumber(this.counter);
}
private setRequestNumber(number) {
this._httpRequestInProgress.next(number);
}
}
<file_sep>/src/app/shared/utility/validation.service.ts
/**
*
* Service for handeling custom validation.
*
* @author <NAME>
*
*/
import {Injectable} from '@angular/core';
import {AbstractControl, FormControl} from '@angular/forms';
@Injectable()
export class ValidatorService {
constructor() {
}
private static mod11OfNumberWithControlDigit(input: any) {
let controlNumber = 2;
let sumForMod = 0;
for (let i = input.toString().length - 2; i >= 0; --i) {
sumForMod += input.toString().charAt(i) * controlNumber;
if (++controlNumber > 7) {
controlNumber = 2;
}
}
const result = (11 - sumForMod % 11);
return result === 11 ? 0 : result;
}
/**
* Validate if from control has a valid email address.
* @param control
* @returns {any} null if everything is OK or a json with error
*/
emailValidator(control: FormControl) {
const EMAIL_REGEXP = /^[a-z0-9!#$%&'*+\/=?^_`{|}~.-]+@[a-z0-9]([a-z0-9-]*[a-z0-9])?(\.[a-z0-9]([a-z0-9-]*[a-z0-9])?)*$/i;
if ((control.value !== '' && control.value !== null) && (control.value.length <= 5 || !EMAIL_REGEXP.test(control.value))) {
return {'incorrectMailFormat': true};
}
return null;
}
/**
* Check if input is a valid number
*
* @param input
* @returns {boolean}
*/
isNumber(input: string) {
const pattern = /^[0-9]+$/;
if (!pattern.test(input)) {
return false;
}
return true;
}
/**
* Check if input is a valid number as formbuilder
*
* @param input
* @returns {boolean}
*/
isValidPhoneFormBuilder(control: FormControl) {
const pattern = /^-?[0-9]*$/;
if ((control.value !== '' && control.value !== null) && (control.value.length !== 8 || !pattern.test(control.value))) {
return {'isInvalidPhone': true};
}
return null;
}
/**
* Form Builder
* @Input input: string to validate
*/
isValidPasswordFormBuilder(control: FormControl) {
const CAPITAL = /.*[A-Z].*/;
const LOWER_CASE = /.*[a-z].*/;
const DIGIT = /\d/;
const input = control.value;
if (input) {
if (input.length < 8) {
return {'invalidPasswordFormat': true};
}
if (!CAPITAL.test(input)) {
return {'invalidPasswordFormat': true};
}
if (!LOWER_CASE.test(input)) {
return {'invalidPasswordFormat': true};
}
if (!DIGIT.test(input)) {
return {'invalidPasswordFormat': true};
}
}
return null;
}
isValidPersonalNumber(control: FormControl) {
let personalNumber = control.value;
personalNumber = personalNumber.toString().replace(/\./g, '');
personalNumber = personalNumber.toString().replace(/ /g, '');
if (personalNumber) {
if (!isNaN(personalNumber)) {
if (!personalNumber) {
return {'invalidAccountNumber': true};
}
if (personalNumber.toString().length !== 11) {
return {'invalidAccountNumber': true};
}
if (parseInt(personalNumber.charAt(personalNumber.length - 1), 10) ===
ValidatorService.mod11OfNumberWithControlDigit(personalNumber)) {
return null;
} else {
return {'invalidAccountNumber': true};
}
} else {
return {'invalidAccountNumber': true};
}
}
return null;
}
matchPassword(AC: AbstractControl) {
const password = AC.get('p' +
'assword').value;
const confirmPassword = AC.get('repeatPassword').value;
if (password !== confirmPassword) {
return {'missmatchPassword': true};
} else {
return null;
}
}
}
<file_sep>/src/app/home/index.home.ts
// component
export { HomeComponent } from 'app/home/home.component';
export { GreeterComponent } from 'app/home/shared/greeter/greeter.component';
// module
export { HomeModule } from 'app/home/shared/home.module';
<file_sep>/e2e/app.e2e-spec.ts
import {AppPage} from './app.po';
import {browser, by, element} from 'protractor';
describe('angular-boilerplate App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('check title and welcome text', () => {
page.navigateTo();
expect(browser.getTitle()).toEqual('Angular Boilerplate');
});
it('check welcome text', () => {
const el = element(by.tagName('h1'));
expect(el.getText()).toContain('Welcome to this Angular Boilerplate');
});
it('navigate to new route', () => {
const newCaseLink = element(by.css('.navigation-link'));
newCaseLink.click();
expect(element(by.tagName('h1')).getText()).toBe('You just navigated!');
});
});
<file_sep>/Dockerfile
FROM nginx:1.20.0-alpine
COPY ./dist/ /usr/share/nginx/html
COPY ./nginx-custom.conf /etc/nginx/conf.d/default.conf
<file_sep>/src/app/shared/README.md
Do declare components, directives, and pipes in a shared module when those items will be re-used and referenced by the components declared in other feature modules.
Do import all modules required by the assets in the SharedModule; for example, CommonModule and FormsModule.
# Index.shared.ts (i.e. Barrel)
This file contains the exports statement of files of shared folder. This is to avoid cumbersome
of large number of export statements.
<file_sep>/src/app/app.routes.ts
/**
* Created by orjanertkjern on 24/04/2017.
*/
import { HomeComponent } from 'app/home/home.component';
import {RouterModule, Routes} from '@angular/router';
const APP_ROUTES: Routes = [
{
path: '',
component: HomeComponent,
},
{
path: '**',
redirectTo: '404',
},
];
export let AppRouterModule = RouterModule.forRoot(APP_ROUTES, {scrollPositionRestoration: 'enabled'});
<file_sep>/src/app/navigation-destination/navigation-destination.component.ts
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'boilerplate-navigation-destination',
templateUrl: 'navigation-destination.component.html',
styleUrls: ['./navigation-destination.component.scss'],
})
export class NavigationDestinationComponent implements OnInit {
constructor() {
}
ngOnInit() {
}
}
<file_sep>/src/app/navigation-destination/shared/navigation-destination.route.ts
import { NavigationDestinationComponent } from 'app/navigation-destination/navigation-destination.component';
import {RouterModule, Routes} from '@angular/router';
const NAVIGATE_ROUTES: Routes = [
{
path: 'navigate',
component: NavigationDestinationComponent,
},
];
export let NavigateDestinationRouterModule = RouterModule.forChild(NAVIGATE_ROUTES);
<file_sep>/src/app/home/home.component.spec.ts
import { TranslateModule } from '@ngx-translate/core';
// components
import { HomeComponent } from 'app/home/home.component';
import { GreeterComponent } from 'app/home/shared/greeter/greeter.component';
// services
import { ExampleService } from 'app/shared/utility/example.service';
import {Observable, of} from 'rxjs';
import {async, TestBed} from '@angular/core/testing';
import {RouterTestingModule} from '@angular/router/testing';
// pipe
describe('HomeComponent', () => {
class ExampleServiceStub {
serviceExampleFunction(): Observable<boolean> {
return of(true);
}
}
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
HomeComponent,
GreeterComponent,
],
imports: [
RouterTestingModule,
TranslateModule.forRoot(),
],
providers: [
[{ provide: ExampleService, useClass: ExampleServiceStub }],
],
}).compileComponents();
}));
it('should create the home component', async(() => {
const fixture = TestBed.createComponent(HomeComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
});
<file_sep>/src/app/navigation-destination/index.navigation.ts
// component
export { NavigationDestinationComponent } from 'app/navigation-destination/navigation-destination.component';
// module
export { NavigationDestinationModule } from 'app/navigation-destination/shared/navigation-destination.module';
<file_sep>/src/app/responsive_table/README.md
Responsive table folder displays the table control with responsive layout
# Index.table.ts (i.e. Barrel)
This file contains the exports statement of files of current folder. This is to avoid cumbersome
of large number of export statements.
# responsive-table/Shared
Here scss, services, module and route file of current feature is place to implement the lazy loading.
In turn table.module file is exported into the app.module.ts file
<file_sep>/README.md
# Angular Toolbox & Reference Project

This project is a reference and a toolbox project for **Angular 6.1.1.** The project could be used as a reference and toolbox for new or existing internal projects.
The most used modules, component and libaries has been implemented into this project.
The project can be viewed here: https://toolbox-reference-angular.dev.evry.site/
The project is following *John Papas Angular Styleguide*: https://angular.io/guide/styleguide
The project is using the CSS-framework **Bootsrap 4**.
The following boilerplate was mainly created using the **Angular CLI**. It is recommended to use the CLI when creating new projects and use this project more as a reference.
If you decide to clone this project and make changes, it is still recommended to use the commands integrated in the CLI, to create new components, modules, services etc.
The relevant files will then be imported, created and imported in the correct modules etc. This will help ensuring correct style and folder structure.
## Content
* [Installation](#installation)
* [Contribution](#contribution)
* [Elements](#elements)
* [External Modules](#external-modules)
* [Testing](#testing)
* [TSLint](#tslint)
* [External References](#external-references)
## Installation
Start by cloning the project:
```
git clone https://github.com/evry-bergen/reference-angular.git
```
When the project is cloned, install the npm packages:
```
npm install
```
You can now run the project, and the angular project should be visible at localhost:4200
```
npm start
```
To save 95 % build time, you can use the new Angular 5 feature
```
ng serve --aot
```
--aot will be standard when running npm start in future Angular versions.
## Contribution
If you want to contribute to this project, please read the [Contribution guidelines for this project](CONTRIBUTING.md)
## Elements
### Components
In this reference project there has been created a few components, mainly to describe the best pratice folder structure.
The folder structure is based on <NAME>'s style guide: https://angular.io/guide/styleguide. This is also the official
Angular 2 style guide.
All components in the project has the following naming convention:
`component-name.component.ts|html|scss|spec.ts.`
When creating a new component a .ts, .html .scss and .spec should always be included!
### Services
A simple ```example.service.ts``` has been included in the project to show the usage of services and **D**ependency **I**njection (**DI**) in Angular.
It only returns a Observable that returns true value. An Observable is used to display how to handle them, using [rxjs](https://github.com/ReactiveX/rxjs) with Observables.
The service is injected in the greeter component. It should only show the greeting if the service works as expected, and
the ```h1``` elements contains an *ngIf.
### HTTP Interceptor
A HTTP Interceptor is created as an reference. If you ever need to log based on status, or have to handle HTTP requests/response etc.
somehow. This is the way to go.
## TSLint
## External Modules
In the project a few external modules that we use frequently has been imported into the project, to show how to use them.
A detailed description of each of the modules will not be given. But a link to the GitHub repository is given as a reference.
They are all implemented and used in the project.
### @ngx-translate
https://github.com/ngx-translate
## Testing
End-to-end testing and Unit Testing are both supported in this project and can be used as followed:
npm test // run unit tests
ng e2e // run end to end tests
## TSLint
To ensure good syntax standard and code quality, linting has been added to the project. You can run this by using the following command:
ng lint -format stylish
Do not create a Pull Requests before running this command. This makes it easier for the reviewer to review the code.
## External References
### Hook up with backend
The following project by @salilsaini868 is a good reference project on how to combine a DOTNET project with an Angular 5 project.
In the following project a swagger generation tool has been used to hook up the front end to the webapi:
[Example project](https://github.com/salilsaini868/Recruitment-System/tree/develop/web)
<file_sep>/src/app/error/README.md
Error folder is to display error page
# Index.error.ts (i.e. Barrel)
This file contains the exports statement of files of current folder. This is to avoid cumbersome
of large number of export statements.
# Error/Shared
Here scss, services, module and route file of current feature is place to implement the lazy loading.
In turn error.module file is exported into the app.module.ts file
<file_sep>/src/app/shared/index.shared.ts
// services
export { SpinnerService } from 'app/shared/spinner/spinner.service';
export { ExampleService } from 'app/shared/utility/example.service';
export { ValidatorService } from 'app/shared/utility/validation.service';
// module
export { SharedModule } from 'app/shared/shared.module';
<file_sep>/src/app/responsive_table/shared/table.module.ts
// modules
import { TranslateModule } from '@ngx-translate/core';
import { SharedModule } from 'app/shared/shared.module';
import { TableRouterModule } from 'app/responsive_table/shared/table.route';
// component
import { TableComponent } from 'app/responsive_table/table.component';
import {NgModule} from '@angular/core';
@NgModule({
imports: [
TranslateModule,
TableRouterModule,
SharedModule,
],
exports: [],
declarations: [
TableComponent,
],
providers: [],
})
export class TableModule {
}
<file_sep>/src/app/shared/shared.module.ts
// spinner
import { SpinnerDirective } from 'app/shared/spinner/spinner.directive';
// services
import { SpinnerService } from 'app/shared/spinner/spinner.service';
import { ValidatorService } from 'app/shared/utility/validation.service';
import { ExampleService } from 'app/shared/utility/example.service';
import { HttpInterceptorHandler } from './interceptor/HttpInterceptorHandler';
import {NgModule} from '@angular/core';
import {HTTP_INTERCEPTORS, HttpClientModule} from '@angular/common/http';
import {CommonModule} from '@angular/common';
import {RouterModule} from '@angular/router';
@NgModule({
imports: [
HttpClientModule,
CommonModule,
RouterModule,
],
declarations: [
SpinnerDirective,
],
exports: [
HttpClientModule,
CommonModule,
RouterModule,
SpinnerDirective,
],
providers: [
SpinnerService,
ExampleService,
ValidatorService,
{
provide: HTTP_INTERCEPTORS,
useClass: HttpInterceptorHandler,
multi: true,
},
],
})
export class SharedModule {
}
<file_sep>/src/app/home/shared/greeter/greeter.component.ts
import { ExampleService } from 'app/shared/utility/example.service';
import {Component, Input, OnInit} from '@angular/core';
@Component({
selector: 'boilerplate-greeter',
templateUrl: 'greeter.component.html',
styleUrls: ['./shared/greeter.component.scss'],
})
export class GreeterComponent implements OnInit {
@Input() greetings: string;
isServiceWorking: boolean;
showServiceStatus: boolean;
constructor(private exampleService: ExampleService) {
}
ngOnInit() {
if (!this.greetings) {
this.greetings = 'home.welcome';
}
this.callService();
}
toggleServiceStatus() {
this.showServiceStatus = !this.showServiceStatus;
}
private callService() {
this.exampleService.serviceExampleFunction().subscribe(
result => {
this.isServiceWorking = result;
},
err => {
console.log(err);
});
}
}
<file_sep>/src/app/app.module.ts
// app component
import { AppComponent } from './app.component';
// Module
import { SharedModule } from 'app/shared/index.shared';
import { AppRouterModule } from 'app/app.routes';
import { HomeModule } from 'app/home/index.home';
import { ErrorModule } from 'app/error/index.error';
import { TableModule } from 'app/responsive_table/index.responsive';
import { NavigationDestinationModule } from 'app/navigation-destination/index.navigation';
// translation
import { TranslateLoader, TranslateModule } from '@ngx-translate/core';
import { TranslateHttpLoader } from '@ngx-translate/http-loader';
import { HttpClient } from '@angular/common/http';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
// create loader for translation
export function HttpLoaderFactory(http: HttpClient) {
return new TranslateHttpLoader(http);
}
@NgModule({
declarations: [AppComponent],
imports: [
SharedModule,
AppRouterModule,
BrowserAnimationsModule,
ErrorModule,
HomeModule,
NavigationDestinationModule,
TableModule,
TranslateModule.forRoot({
loader: {
provide: TranslateLoader,
useFactory: HttpLoaderFactory,
deps: [HttpClient],
},
}),
],
exports: [],
providers: [],
bootstrap: [AppComponent],
})
export class AppModule {}
<file_sep>/src/app/shared/utility/example.service.ts
import {Observable, of} from 'rxjs';
import {Injectable} from '@angular/core';
@Injectable()
export class ExampleService {
constructor() {
}
serviceExampleFunction(): Observable<boolean> {
return of(false);
}
}
<file_sep>/src/app/home/shared/home.route.ts
// Component
import { HomeComponent } from 'app/home/home.component';
import {RouterModule, Routes} from '@angular/router';
const HOME_ROUTES: Routes = [
{
path: '',
component: HomeComponent,
},
];
export let HomeRouterModule = RouterModule.forRoot(HOME_ROUTES);
<file_sep>/src/app/shared/spinner/spinner.directive.ts
// Services
import { SpinnerService } from 'app/shared/spinner/spinner.service';
import {Directive, ElementRef, OnDestroy, OnInit} from '@angular/core';
import {Subscription} from 'rxjs';
@Directive({
selector: '[boilerplateSpinner]',
})
export class SpinnerDirective implements OnInit, OnDestroy {
subscription: Subscription;
private spinnerElement;
constructor(elementRef: ElementRef, private spinner: SpinnerService) {
this.spinnerElement = elementRef.nativeElement;
}
ngOnInit() {
this.subscription = this.spinner.requestInProgress$
.subscribe(item => {
if (item <= 0) {
this.spinnerElement.style.display = 'none';
} else {
this.spinnerElement.style.display = 'block';
}
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
}
<file_sep>/src/app/error/index.error.ts
// component
export { ErrorComponent } from 'app/error/error.component';
// module
export { ErrorModule } from 'app/error/shared/error.module';
<file_sep>/src/app/home/shared/greeter/greeter.component.spec.ts
import { TranslateModule } from '@ngx-translate/core';
import { GreeterComponent } from 'app/home/shared/greeter/greeter.component';
import { ExampleService } from 'app/shared/utility/example.service';
import {async, TestBed} from '@angular/core/testing';
import {RouterTestingModule} from '@angular/router/testing';
describe('HomeComponent', () => {
beforeEach(async(() => {
// Example service mock
TestBed.configureTestingModule({
declarations: [
GreeterComponent,
],
imports: [
RouterTestingModule,
TranslateModule.forRoot(),
],
providers: [
ExampleService,
],
}).compileComponents();
}));
it('should create the greeter component', async(() => {
const fixture = TestBed.createComponent(GreeterComponent);
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
}));
it('should render title in a h1 and', async(() => {
const fixture = TestBed.createComponent(GreeterComponent);
fixture.detectChanges();
const compiled = fixture.debugElement.nativeElement;
expect(compiled.querySelector('h1').innerText).toContain('home.welcome');
}));
});
<file_sep>/CONTRIBUTING.md
# Contribution to the Angular Toolbox Reference Project
### About the project
The following project should allways be up to date with the newest stable features.
If you find any npm packages or dependencies that are not up to date a reported Issue, or even better a Pull Request linked to an issue, should be created.
### Pull Requests
A pull request must comply with the following requirements:
1. The Pull Rquest must be building.
1.1. The following commands should be running without any erros:
ng build --target=production --environment=prod // Build for production
npm test // Run all unit tests
ng e2e // Run all end-to-end tets
ng lint // Run lint to avoid bad code style
2. A detailed description about the pull request. For instance "why it has been fixed and how it has been fixed"?
3. If any Issues are releated to the PR they should be linked
### Issues
Should have a clear desciption of the releated issue.
<file_sep>/src/app/navigation-destination/shared/navigation-destination.module.ts
// modules
import { SharedModule } from 'app/shared/shared.module';
import { TranslateModule } from '@ngx-translate/core';
import { NavigateDestinationRouterModule } from 'app/navigation-destination/shared/navigation-destination.route';
// component
import { NavigationDestinationComponent } from 'app/navigation-destination/navigation-destination.component';
import {NgModule} from '@angular/core';
@NgModule({
imports: [
TranslateModule,
NavigateDestinationRouterModule,
SharedModule,
],
exports: [],
declarations: [
NavigationDestinationComponent,
],
providers: [],
})
export class NavigationDestinationModule {
}
<file_sep>/src/app/home/shared/home.module.ts
import { TranslateModule } from '@ngx-translate/core';
// components
import { HomeComponent } from 'app/home/home.component';
import { GreeterComponent } from 'app/home/shared/greeter/greeter.component';
// modules
import { HomeRouterModule } from 'app/home/shared/home.route';
import { SharedModule } from 'app/shared/shared.module';
import {NgModule} from '@angular/core';
@NgModule({
imports: [
TranslateModule,
SharedModule,
HomeRouterModule,
],
exports: [],
declarations: [
HomeComponent,
GreeterComponent,
],
providers: [],
})
export class HomeModule {
}
<file_sep>/src/app/home/README.md
Home folder is to display landing page
# Index.home.ts (i.e. Barrel)
This file contains the exports statement of files of current folder. This is to avoid cumbersome
of large number of export statements.
# home/Shared
Here scss, services, module and route file of current feature is place to implement the lazy loading.
In turn home.module file is exported into the app.module.ts file
<file_sep>/src/app/responsive_table/shared/table.route.ts
// Component
import { TableComponent } from 'app/responsive_table/table.component';
import {RouterModule, Routes} from '@angular/router';
const RESPONSIVETABLE_ROUTES: Routes = [
{
path: 'table',
component: TableComponent,
},
];
export let TableRouterModule = RouterModule.forChild(RESPONSIVETABLE_ROUTES);
<file_sep>/src/app/navigation-destination/README.md
Navigation Destination folder implements the routerLink
# Index.navigation.ts (i.e. Barrel)
This file contains the exports statement of files of current folder. This is to avoid cumbersome
of large number of export statements.
# home/Shared
Here scss, services, module and route file of current feature is place to implement the lazy loading.
In turn navigation-destination.module file is exported into the app.module.ts file
<file_sep>/src/app/responsive_table/index.responsive.ts
// component
export { TableComponent } from 'app/responsive_table/table.component';
// module
export { TableModule } from 'app/responsive_table/shared/table.module';
<file_sep>/BEST_PRACTICES.md
### 1. trackBy
Use the `trackBy` function when using `ngFor`
Angular will keep track of changes and only re-render changed elements
``` javascript
// in the template
<li *ngFor="let item of items; trackBy: trackByFn">{{ item }}</li>
// in the component
trackByFn(index, item) => return item.id; // unique id corresponding to the item
```
### 2. const vs let
When declaring variables, use `const` when the value is not going to be reassigned.
### 3. Always pipe RXJS operators
DON'T `observable.map()`
DO `observable.pipe(map())`
### 4. Subscribe in templates
Use the `async` pipe in templates to subscribe to Observables instead of in the component.
### 5. Lazy loading
Lazy load where possible for performance
### 6. No subscriptions inside subscriptions
### 7. Avoid the `any` keyword, type everything
### 8. Components should only deal with display logic
Business logic should be contained in services (or utils, not preferable), we want to keep these separate.
### 9. Avoid logic in templates
Avoid using `&&` clauses and other similar logic:
DON'T: `<p *ngIf="role==='developer'"> Status: Developer </p>`
DO: `<p *ngIf="showDeveloperStatus"> Status: Developer </p>`
### 10. Use the shared module for shareable code
DO declare and export `components`, `pipes`, `directives`.
DO import and export other shareable modules like `FormsModule` or `CommonModule`
DON'T declare services or singletons here. These should be imported in the `CoreModule`.
### 11. Use the core module for services and singletons
DO import modules that should be instantiated once in your app.
DO place services in the module, but do not provide them.
### 12. Simplify you imports
Create an `index.ts` for simplifying imports/exports of components.
[Example](https://github.com/RikdeVos/angular-scalable-project-structure/blob/master/src/app/shared/components/index.ts)
### 13. Shorten relative paths with aliases
Add aliases for commonly used paths
``` javascript
{
...
"compilerOptions": {
...
"baseUrl": "src",
"paths": {
"@env": ["environments/environment"],
"@shared/*": ["app/shared/*"],
"@core/*": ["app/core/*"]
}
}
}
```
### 14. Use SCSS variables
We don't like to repeat ourselves, so any color or other variables should be defined in `/styles/utilities/variables.scss`
### 15. Clean up subscriptions
When subscribing to observables, always make sure you unsubscribe from them appropriately by using operators like `take`, `takeUntil`, etc. Failing to unsubscribe may cause unwanted memory leaks.
``` javascript
private _destroyed$ = new Subject();
public ngOnInit (): void {
iAmAnObservable
.pipe(
map(value => value.item)
// We want to listen to iAmAnObservable until the component is destroyed,
takeUntil(this._destroyed$)
)
.subscribe(item => this.textToDisplay = item);
}
public ngOnDestroy (): void {
this._destroyed$.next();
this._destroyed$.complete();
}
```
## Read more at:
- https://www.freecodecamp.org/news/best-practices-for-a-clean-and-performant-angular-application-288e7b39eb6f/
- https://medium.com/dev-jam/5-tips-best-practices-to-organize-your-angular-project-e900db08702e
## Example projects:
- https://github.com/RikdeVos/angular-scalable-project-structure
|
2c0c90be8f3a13465cdbd182b6f1273abb532f99
|
[
"Markdown",
"TypeScript",
"Dockerfile"
] | 36 |
TypeScript
|
evry-bergen/toolbox-reference-angular
|
26f7e3e7d6ea592e91c70a3ba77038f6d5b74569
|
67162ad4bb025b7af7487815b9ae765637f5f691
|
refs/heads/master
|
<file_sep># tictactoe
Sencillo juego de gato para Android.
Quise acelerar la maquetaciรณn y usรฉ materializecss, por eso hay un materialize.js, un materialize.css y un jquery.js.
Si usas css puro y duro te puedes ahorrar esos archivos.
El archivo index.js es sรณlo javascript plano, no usรฉ el jquery para la lรณgica.
No esperes grandes alardes, es un proyecto de dos horas que hice para mostrarle a mi hijo de nueve aรฑos cรณmo se crea un software.
<file_sep>var gato = document.getElementsByClassName("gato");
var play = document.getElementById("play");
var player = null;
var gato1 = document.getElementById("gato1");
var gato2 = document.getElementById("gato2");
var gato3 = document.getElementById("gato3");
var gato4 = document.getElementById("gato4");
var gato5 = document.getElementById("gato5");
var gato6 = document.getElementById("gato6");
var gato7 = document.getElementById("gato7");
var gato8 = document.getElementById("gato8");
var gato9 = document.getElementById("gato9");
function start(){
for (i = 0; i < gato.length; i++){
gato[i].addEventListener("click",function(){
cambiar(this);
});
}
play.addEventListener("click",function(){
empezar();
});
}
//Cambia la imagen
function cambiar(param){
var touched = hasClass(param,"touched");
if(play.innerHTML != "ยกEmpezar!"){
if(!touched){
if(player == 1){
param.setAttribute("src","img/x.png");
player = 0;
play.innerHTML = "ยกJuega O!";
}
else if(player == 0){
param.setAttribute("src","img/o.png");
player = 1;
play.innerHTML = "ยกJuega X!";
}
param.setAttribute("class","responsive-img gato touched");
verificar();
}
}
}
//Inicia el juego
function empezar(){
if(play.innerHTML == "ยกEmpezar!"){
play.innerHTML = "ยกJuega X!";
player = 1;
}
else if(play.innerHTML == "ยกOtra vez!"){
location.reload();
}
}
//Confirma que no se haya seleccionado antes
function hasClass(elem, clase) {
return new RegExp('(\\s|^)'+clase+'(\\s|$)').test(elem.className);
}
function verificar(){
if(gato1.getAttribute("src") == "img/x.png" && gato2.getAttribute("src") == "img/x.png" && gato3.getAttribute("src") == "img/x.png"){
alert("ยกGanรณ X!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato1.getAttribute("src") == "img/o.png" && gato2.getAttribute("src") == "img/o.png" && gato3.getAttribute("src") == "img/o.png"){
alert("ยกGanรณ O!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato4.getAttribute("src") == "img/x.png" && gato5.getAttribute("src") == "img/x.png" && gato6.getAttribute("src") == "img/x.png"){
alert("ยกGanรณ X!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato4.getAttribute("src") == "img/o.png" && gato5.getAttribute("src") == "img/o.png" && gato6.getAttribute("src") == "img/o.png"){
alert("ยกGanรณ O!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato7.getAttribute("src") == "img/x.png" && gato8.getAttribute("src") == "img/x.png" && gato9.getAttribute("src") == "img/x.png"){
alert("ยกGanรณ X!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato7.getAttribute("src") == "img/o.png" && gato8.getAttribute("src") == "img/o.png" && gato9.getAttribute("src") == "img/o.png"){
alert("ยกGanรณ O!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato1.getAttribute("src") == "img/x.png" && gato4.getAttribute("src") == "img/x.png" && gato7.getAttribute("src") == "img/x.png"){
alert("ยกGanรณ X!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato1.getAttribute("src") == "img/o.png" && gato4.getAttribute("src") == "img/o.png" && gato7.getAttribute("src") == "img/o.png"){
alert("ยกGanรณ O!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato2.getAttribute("src") == "img/x.png" && gato5.getAttribute("src") == "img/x.png" && gato8.getAttribute("src") == "img/x.png"){
alert("ยกGanรณ X!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato2.getAttribute("src") == "img/o.png" && gato5.getAttribute("src") == "img/o.png" && gato8.getAttribute("src") == "img/o.png"){
play.innerHTML = "ยกGanรณ O!";
}
else if(gato3.getAttribute("src") == "img/x.png" && gato6.getAttribute("src") == "img/x.png" && gato9.getAttribute("src") == "img/x.png"){
alert("ยกGanรณ X!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato3.getAttribute("src") == "img/o.png" && gato6.getAttribute("src") == "img/o.png" && gato9.getAttribute("src") == "img/o.png"){
alert("ยกGanรณ O!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato1.getAttribute("src") == "img/x.png" && gato5.getAttribute("src") == "img/x.png" && gato9.getAttribute("src") == "img/x.png"){
alert("ยกGanรณ X!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato1.getAttribute("src") == "img/o.png" && gato5.getAttribute("src") == "img/o.png" && gato9.getAttribute("src") == "img/o.png"){
alert("ยกGanรณ O!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato3.getAttribute("src") == "img/x.png" && gato5.getAttribute("src") == "img/x.png" && gato7.getAttribute("src") == "img/x.png"){
alert("ยกGanรณ X!");
play.innerHTML = "ยกOtra vez!";
}
else if(gato3.getAttribute("src") == "img/o.png" && gato5.getAttribute("src") == "img/o.png" && gato7.getAttribute("src") == "img/o.png"){
alert("ยกGanรณ O!");
play.innerHTML = "ยกOtra vez!";
}
else{
if(hasClass(gato1,"touched") && hasClass(gato2,"touched") && hasClass(gato3,"touched") && hasClass(gato4,"touched") && hasClass(gato5,"touched")
&& hasClass(gato6,"touched") && hasClass(gato7,"touched") && hasClass(gato8,"touched") && hasClass(gato9,"touched")){
play.innerHTML = "ยกEmpate!";
alert("ยกEmpate!");
play.innerHTML = "ยกOtra vez!";
}
}
}
|
68c4d9722e2ef61c879b31fe542e9aa81e7600cf
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
JBdesarrollo/tictactoe
|
5910fc4fe06a8fcf4ea652a56e147edc67acfd1e
|
f1ae508f9309a5e077c9f2aa3198591116723cfd
|
refs/heads/master
|
<repo_name>msar15/mRICH_pid<file_sep>/mRICH.C
#include "mRICH.h"
using namespace std;
mRICH::mRICH(double trackResolution, double incidentAngle, double pix, double p)
{
// In this arameterization we assume that the particle enters the mRICH perpendicular to its front face. More realistic case will be implemented in the subsequent updates.
fTrackResolution = trackResolution;
mom = p;
pLow = 0;
pHigh = 10.;
c = 0.0299792458; // cm/picosecond
n = 1.03; //Aerogel
a = pix;// pixel size 3.0; // mm -- one side
f = 152.4; //focal length mm = 6"
N_gam = 10;
mElectron = 0.00051099895; //GeV/c^2
mPion = 0.13957018; //GeV/c^2
mKaon = 0.493677; //GeV/c^2
mProton = 0.93827208816; //GeV/c^2
pi = 3.14159;
alpha = 0.0072973525693; // hyperfine const
L = 3.0;//Aerogel block thickness in cm
//===============
th0 = incidentAngle; //incidence angle in radians
double dth = 0., dth_epi = 0.;
Nsigma = 0., Nsigma_epi = 0.;
if(mom>2.) {
dth = getAng(mPion) - getAng(mKaon);
//Detector uncertainty
double sigTh = sqrt(pow(getdAng(mPion),2)+pow(getdAng(mKaon),2));
//Global uncertainty
double sigThTrk = getdAngTrk(mKaon);
double sigThc = sqrt(pow(sigTh/sqrt(getNgamma(L,mPion)),2)+pow(sigThTrk,2));
Nsigma = dth/sigThc;
}
if(mom>0.58) {
dth_epi = getAng(mElectron) - getAng(mPion);
double sigTh_epi = sqrt(pow(getdAng(mElectron),2)+pow(getdAng(mPion),2));
double sigThTrk_epi = getdAngTrk(mPion);
double sigThc_epi = sqrt(pow(sigTh_epi/sqrt(getNgamma(L,mElectron)),2)+pow(sigThTrk_epi,2));
Nsigma_epi = dth_epi/sigThc_epi;
}
#if 0
//From simulations
ReadMap("mRICHresol.root");
Nsigma = fpixMap->GetBinContent(p,pix);
#endif
//cout<<getNgamma(mPion)<<"\t"<<getNgamma(mKaon)<<endl;
char nameit[500];
sprintf(nameit,"mRICH Pixel Size =%dx%d (mm^{2}) / p =%.f (GeV/c)",pix,pix,p);
myName = nameit;
//cout<<".................\t"<<Nsigma<<endl;
}
double mRICH::maxP(double eta, double p, double numSigma, PID::type PID)
{
if (valid(eta,p))
{
return Nsigma;
}
else
{
cout << "mRICH.C: Invalid (eta) for this detector." <<endl;
return 0.0;
}
}
//Angle exiting the Aerogel
double mRICH::getAng(double mass)
{
double beta = mom/sqrt(pow(mom,2)+pow(mass,2));
double thc = acos(1./n/beta);
double th0p = asin(sin(th0)/n);
double dthc = thc - th0p;
double theta = asin(n*sin(dthc));
return theta;
}
//Uncertainty due to detector effects
double mRICH::getdAng(double mass)
{
double beta = mom/sqrt(pow(mom,2)+pow(mass,2));
double thc = acos(1./n/beta);
double th0p = asin(sin(th0)/n);
double dthc = thc - th0p;
double theta = asin(n*sin(dthc));
double sig_ep = 0;//Emission point error
double sig_chro = 0; //Chromatic dispersion error
double sig_pix = a*pow(cos(theta),2)/f/sqrt(12.);;
double sigTh = sqrt(pow(sig_ep,2)+pow(sig_chro,2)+pow(sig_pix,2));
return sigTh;
}
//Uncertainty due to tracking resolution
double mRICH::getdAngTrk(double mass)
{
double beta = mom/sqrt(pow(mom,2)+pow(mass,2));
double thc = acos(1./n/beta);
double th0p = asin(sin(th0)/n);
double dthc = thc - th0p;
double theta = asin(n*sin(dthc));
double sig_trk = (cos(dthc)/cos(theta))*(cos(th0)/cos(th0p))*fTrackResolution;;
return sig_trk;
}
//no. of gamms
double mRICH::getNgamma(double t, double mass)
{
int tot = 10000;
double beta = mom/sqrt(pow(mom,2)+pow(mass,2));
double fact = 2.*pi*alpha*t*(1.-1./pow(n*beta,2));
double T_lensWin = 0.92*0.92;
double xmin = 300.e-7;
double xmax = 650.e-7;
double dx = (xmax-xmin)/tot;
double sum = 0;
for(int j=0; j<tot; j++){
double x = xmin + j*dx + dx/2.;
sum += T_QE(x)*T_Aer(t,x)/pow(x,2);
}
return fact*T_lensWin*sum*dx;
}
//Quantum efficiency
double mRICH::T_QE(double lam)
{
return 0.34*exp(-1.*pow(lam-345.e-7,2)/(2.*pow(119.e-7,2)));
}
//Transmissions of the radiator block
double mRICH::T_Aer(double t, double lam)
{
return 0.83*exp(-1.*t*56.29e-20/pow(lam,4));
}
//Read histogram from MC parametrization
void mRICH::ReadMap(TString name){
TFile* file = TFile::Open(name);
fpixMap = (TH2F *) file->Get("h2pix");
}
void mRICH::description()
{
// Here one should describe what this detector is and what assumptions are
// made in calculating the performance specifications.
cout << "My name is \"" << myName << "\" and I am described as follows:" <<endl;
cout << " Momentum coverage for k/pi separation= [" << 3.0 << " to " << 10.0 <<" (GeV/c) ]"<<endl;
cout << " Since mRICH detector system consists of array of identical shoebox-like modules, in principle, " << endl;
cout << " the mRICH pid performance is invariant relative to the tracking polar angle but the momentum of the " << endl;
cout << " charge particle and the entrance point location on the front face of a given mRICH module." << endl;
cout << " Assumed time precision = " << fTimePrecision << " ns" <<endl;
cout << " Assumed track resolution = "<< fTrackResolution << " mrad" <<endl;
//cout << " Assumed quantum efficiency of the photosensors = "<< fSensorQMefficiency << "%" <<endl;
cout << endl;
}
<file_sep>/RUNME.C
#include "mRICH.C"
#include <vector>
#include <TMath.h>
#include <TH1.h>
#include <TH2.h>
std::vector<PID*> Detectors;
std::vector<TH1*> Plots;
PID::type myType = PID::pi_k; // This means I want to plot the pi_K separation;
double numSigma = 3.001; // This means I want to plot teh contour for three sigma separation
double mom=5.;//GeV/c
void RUNME()
{
gStyle->SetOptStat(0);
// Add as many detectors as your heart desires....
Detectors.push_back( new mRICH(0.00175, 1, 3, mom) ); // 1.74 mrad tracking recolution & 3 mm pixel size
// Select the booking criterion for the performance plot.
TH1* Performance = new TH1D("Performance","Performance",100,-6,6); // Format for detector Performance.
//----------------------------------------------------------------------------------
// At least in the beginning, you might not want to change the lines below here...
//----------------------------------------------------------------------------------
// Now we call upon all detectors to present their descriptions and assumptions.
for (int i=0; i<Detectors.size(); i++)
{
Detectors[i]->description();
}
// Now we clone the original performance plot once for every known detector.
for (int i=0; i<Detectors.size(); i++)
{
Plots.push_back( (TH1*)Performance->Clone(Detectors[i]->name().c_str()) );
Plots[i]->SetLineColor(i+1); // Works well only for the first 9 colors...
Plots[i]->SetLineWidth(4);
}
// Now we fill all the performance plots:
for (int i=1; i<Plots[0]->GetNbinsX(); i++) // Remember root is weird...bin0 is the underflow bin
{
double eta = Plots[0]->GetBinCenter(i);
for (int j=0; j<Detectors.size(); j++)
{
if (Detectors[j]->valid(eta,mom))
{
Plots[j]->SetBinContent(i, Detectors[j]->maxP(eta, mom, numSigma, myType) );
//cout<<numSigma<<"\t"<<Detectors[j]->maxP(eta, numSigma, myType)<<endl;
}
}
}
TCanvas *c1 = new TCanvas("c1","c1",700,500);
// Now we display the performance plots
for (int i=0; i<Plots.size(); i++)
{
Plots[i]->Draw("same");
}
// Now we put colored names on top of the plot (too fancy?)...
TPaveText *pt = new TPaveText(0.15,0.7,0.4,0.90,"NDC");
for (int i=0; i<Detectors.size(); i++)
{
pt->AddText( Detectors[i]->name().c_str() );
((TText*)pt->GetListOfLines()->Last())->SetTextColor(i+1);
}
pt->Draw();
}
<file_sep>/mRICH.h
#ifndef __MRICH_H__
#define __MRICH_H__
//
// Hello <NAME>:
//
// This is an example class that inherits from the PID base class.
// We shall implement all the necessary functions as required by the
// base class.
//
// The UNIQUE identifiers for this class are radius, eta extent, and
// time resolution.
//
// Note that in keeping with any well written base class, we shall
// give default values to all the constructor arguments.
//
// This routine assumes units of cm for distances and picoSeconds for time.
//
#include "PID.h"
#include "TVector3.h"
#include "TRandom.h"
#include <iostream>
#include <TH1.h>
#include <TH2.h>
class mRICH: public PID
{
public:
mRICH(double trackResolution=0.5, double timePrecision=1.0, double pixS=0.5, double p=5.0);
virtual ~mRICH() {}
//bool valid (double eta, double p) {return (((eta>-8&&eta<-1) || (eta>1&&eta<8)) && (p>pLow && p<pHigh));}
bool valid (double eta, double p) {return (((eta>-8&&eta<8)) && (p>pLow && p<pHigh));}
double maxP (double eta, double p, double numSigma, PID::type PID);
double minP (double eta, double numSigma, PID::type PID) {return 0;}
string name () {return myName;}
void description ();
void ReadMap(TString name);
double getAng(double mass);
double getdAng(double mass);
double getNgamma(double t, double mass);
double T_Aer(double t, double lam);
double T_QE(double lam);
double SetLensFocalLength(double f);
double SetAerogelThickness(double t);
double GetmRICHParameters();
protected:
std::string myName;
double Nsigma;
// Physical constants (should come from elsewhere!)
double mPion; // GeV/c^2
double mKaon; // GeV/c^2
double mProton; // GeV/c^2
double mom; // GeV/c
double c; // cm/picosecond;
double n;
double f; //mm
double a; //mm
double N_gam;
double pi;
double alpha;
double L;
double th0;
double fTrackResolution;
double fTimePrecision;
double pLow;
double pHigh;
TH2F *fpixMap;
};
#endif /* __PID_H__ */
|
fa741a2f6d49343b0c8347b48bd91d52a634d6cf
|
[
"C",
"C++"
] | 3 |
C
|
msar15/mRICH_pid
|
1ab2fac48cdb72ad17839ec47d8b76d9a99cb3fc
|
7015458dd236e16315fbb4a343fa65758524515b
|
refs/heads/master
|
<repo_name>acarz/assignment3<file_sep>/question3.cxx
// <NAME>
// Question 3
// We include necessary libraries
#include <iostream>
#include <cmath>
using namespace std;
// We define our class FourVector
class FourVector
{
// We made all members and methods public
public:
// We define the members of the class: the energy and three momentum (px, py, pz) of a given particle
float E, Px, Py, Pz;
// This is the constructor to force the user to initialize the members of the class
FourVector (float E, float Px, float Py, float Pz):
E(E), Px(Px), Py(Py), Pz(Pz) {}
// We define first method to replace the contents of the full four vector with the E, px, py, and pz
void SetFourVector (float E, float Px, float Py, float Pz)
{
this->E = E;
this->Px = Px;
this->Py = Py;
this->Pz = Pz;
}
// GetMass() method returns the invariant mass of the four vector (as a float)
float GetMass()
{
// We used this equation to calculate invariant mass: m=SQRT (E^2 - Px^2 - Py^2 - Pz^2)
float InvariantMass = sqrt(pow(E, 2) - pow(Px, 2) - pow(Py, 2) - pow(Pz, 2));
return InvariantMass;
}
// GetEta method returnas the pseudorapity (ฮท : Greek โetaโ) of the four vector (as a float)
float GetEta()
{
// p=sqrt(Px^2+Py^2+Pz^2)
float p = sqrt(pow(Px, 2) + pow(Py, 2) + pow(Pz, 2));
float theta = acos(Pz / p);
float eta = -log(tan(theta / 2));
return eta;
}
// DeltaPhi(FourVector v2) method takes second vector as an argument and
// returns the difference in the azimuthal angle (โฯ) between the two three-momenta of these vectors.
float DeltaPhi(FourVector v2)
{
float p = sqrt(pow(Px, 2) + pow(Py, 2) + pow(Pz, 2));
float p2 = sqrt(pow(v2.Px, 2) + pow(v2.Py, 2) + pow(v2.Pz, 2));
float cosDeltaPhi = ((Px * v2.Px) + (Py * v2.Py) + (Pz * v2.Pz)) / (sqrt(pow(p, 2) * pow(p2,2)));
float deltaPhi = acos(cosDeltaPhi);
return deltaPhi;
}
float DeltaEta(FourVector v2)
{
return -log(tan(DeltaPhi(v2) / 2));
}
};
int main(int argc, char const *argv[])
{
cout << "Hello CERN" << endl;
cout << "--------------" << endl;
cout << " Assignment 3, Question 3 " << endl;
// We create instance of two vectors and initialize the energy and three momentum (px, py, pz) of a given particle
FourVector v1(45, 5, 6, 2);
FourVector v2(25, 6, 7, 8);
cout << " " << endl;
cout << "________The results____________" << endl;
cout << "The FourVector v1 has E = " << v1.E << ", Px = " << v1.Px << ", Py = " << v1.Py << ", Pz = " << v1.Pz << endl;
cout << "The Invariant Mass is: " << v1.GetMass() << endl;
cout << "The pseudorapity is : " << v1.GetEta() << endl;
cout << " " << endl;
cout << "The FourVector v2 has E = " << v2.E << ", Px = " << v2.Px << ", Py = " << v2.Py << ", Pz = " << v2.Pz << endl;
cout << "The Invariant Mass is: " << v2.GetMass() << endl;
cout << "The pseudorapity is : " << v2.GetEta() << endl;
cout << "____________________" << endl;
cout << "The difference in the azimuthal angle (โฯ) between the two three-momenta of these vectors : " << v1.DeltaPhi(v2) << endl;
cout << "the pseudorapity (ฮท) of the two four-vectors : " << v1.DeltaEta(v2) << endl;
cout << " " << endl;
return 99;
}<file_sep>/question1.cxx
// my solution to Question 1 for Assignment 3
// I have done this assingment without seeing the code providied in the assignment.
#include <iostream>
#include <vector>
#include <cmath>
#include <fstream>
using namespace std;
float compute_sum(std::vector<float> &v)
{
float total = 0;
// using for loop to visit every element in a vector and add them up
for (int i = 0; i < v.size(); i++)
{
total = total + v[i];
}
return ( total);
}
// this function calculates the mean by taking vector and the total calculated with abore function as paramteters
float compute_avg(std::vector<float> &v, float total)
{
return ( total / v.size());
}
// This function takes avg from the above function and calculates RMS
float compute_rms(std::vector<float> &v, float avg)
{
float sum = 0;
for (int i = 0; i < v.size(); i++)
{
sum = sum + pow((v[i] - avg), 2);
}
return ( sqrt(sum / v.size()));
}
int main(int argc, char const *argv[])
{
cout << "Hello CERN" << endl;
cout << "--------------" << endl;
cout << " Assignment 3, Question 1 " << endl;
// define which file to read
ifstream in("assignment3_newline_numbers.txt");
std::vector<float> Q;
float data;
while (in >> data)
{
Q.push_back(data);
}
// we make sure if we read all the values correctly
cout << "____ The values we read from the txt file ___" << endl;
for (int i = 0; i < Q.size(); i++)
{
cout << Q[i] << endl;
}
// we call the funcctions
float total= compute_sum(Q);
float avg =compute_avg(Q,total);
float rms=compute_rms(Q,avg);
// We print the results
cout << "________The results____________" << endl;
cout <<"The total :"<< total<< endl;
cout <<"The Average :"<< avg << endl;
cout <<"The RMS :"<< rms << endl;
return 99;
}<file_sep>/README.md
# Assignment 3: LHC Programming Prep Assignment 3 : Memory, Loops, and Classes
## <NAME>
### Question 1
My coding for Question #1 can be found here [Question1](https://github.com/acarz/assignment3/blob/master/question1.cxx)
### Question 2
* My Comments can be found here [Question2](https://github.com/acarz/assignment3/blob/master/question2.cxx)
* Screenshot of the running code can be found here [Screenshot](https://github.com/acarz/assignment3/blob/master/Screenshot.png)
### Question 3
- My coding for Question 3 can be found here [Question3](https://github.com/acarz/assignment3/blob/master/question3.cxx)
<file_sep>/question2.cxx
// this is not the same as you saw in class
#include <iostream>
using namespace std;
int main ()
{
// We defined an array which will hold 6 elements and *p is the pointer
int numbers[6];
int *p;
// numbers[0]=1 we assign the first element of the array to 1
p = numbers;
*p = 1;
// we inreament p
p++;
*p = 4; // // numbers[1]=4
// we make numbers[2] = numbers[0] which is 1
p = &numbers[2];
*p = numbers[0];
// numbers[3] = memory address of 4
p = numbers + *p;
*p = 4;
//numbers[5] = 5
p = numbers + 1;
*(p + 4) = 5;
// Prints the elements of the array
cout << "Numbers : " << numbers[0]
<< " " << numbers[1]
<< " " << numbers[2]
<< " " << numbers[3]
<< " " << numbers[4]
<< " " << numbers[5] << endl;
return 0;
}
|
a355e21d8a734443bf8ace3f8da16ef7cdde94c6
|
[
"Markdown",
"C++"
] | 4 |
C++
|
acarz/assignment3
|
81d6f095cbc5ed70103e3a01c8e0f9ffbec47745
|
0b4ba5d96057b4d0de59aa0988bfbc47616d6b1f
|
refs/heads/master
|
<file_sep>Weather Dashboard
-----------------------
This is an application that you can use to track the weather across different Cities in the United States of America

Usage
---------
Use the search bar and search for a city by name. It will be displayed at the top center of the page. Below it will show the 5 day forecast for that area. The Icons indicate weather conditions. It will also display the UV index of the area. Below the search bar your search history will be displayed. It will show the last cities you searched for. You can click back on those cities to recheck the conditions of the area.
<file_sep> var searchbar = document.getElementById("searchbar")
var searchbutton = document.getElementById("searchbtn")
var callbackarray = []
function searchvalue(){
//get searched value
var search = searchbar.value
search = search.trim()
//send request for current date
var apiUrl1 ="https://api.openweathermap.org/data/2.5/weather?q="+ search + "&units=imperial"+ "&appid=" + "43ef190af294b1e96143aa8fe5347765"
// show request and convert, or log errors
fetch(apiUrl1).then(function(response) {
if (response.ok) {
response.json().then(function(data) {
//create element to history list
var entryLi = document.createElement("li")
entryLi.textContent = search;
entryLi.setAttribute("class", "list-group-item");
entryLi.setAttribute("data",search);
document.getElementById("history").appendChild(entryLi);
//write history to storage
callbackarray.push(search);
window.localStorage.setItem("items",JSON.stringify(callbackarray))
console.log()
//get lon, lat
var lon = data.coord.lon
var lat = data.coord.lat
//convert temp and wind speed to whole number
var tempnow = Math.floor(data.main.temp);
var windnow = Math.floor(data.wind.speed);
//write data to page
document.getElementById("cityname").textContent = data.name
document.getElementById("temp").textContent = tempnow
document.getElementById("wet").textContent = data.main.humidity
document.getElementById("speed").textContent = windnow
//write values to Storage
window.localStorage.setItem("Cityname",data.name);
window.localStorage.setItem("tempnow", tempnow);
window.localStorage.setItem("wet", data.main.humidity);
window.localStorage.setItem("wet", windnow);
//display ui icon
var icon=data.weather[0]
var iconnow =icon.icon
var iconlink = ("https://openweathermap.org/img/wn/" + iconnow +"@2x.png")
document.getElementById("icon").style.display ="block"
document.getElementById("icon").style.backgroundImage = "url(" + iconlink +")"
//write to storage
window.localStorage.setItem("iconlink",iconlink);
//request UV index Data
var apiUrl2 = "https://api.openweathermap.org/data/2.5/uvi?lat=" + lat +"&lon="+lon+"&appid=43ef190af294b1e96143aa8fe5347765"
fetch(apiUrl2).then(function(response){
if (response.ok) {
response.json().then(function(data) {
//pull value from uv fetch
var uv = data.value
uv= Math.floor(data.value)
//write uv to page
document.getElementById("uvindex").style.display ="block"
document.getElementById("uvindex").textContent =uv;
//write to storage
window.localStorage.setItem("uv",uv);
// color code UV index
if(uv <= 2){
document.getElementById("uvindex").style.background = "green"
document.getElementById("uvindex").style.color = "white"
}
if(uv >= 3 && uv <= 5){
document.getElementById("uvindex").style.background = "yellow"
document.getElementById("uvindex").style.color = "black"
}
if(uv >= 6 && uv <= 7){
document.getElementById("uvindex").style.background = "orange"
document.getElementById("uvindex").style.color = "black"
}
if(uv >= 8 && uv <= 10){
document.getElementById("uvindex").style.background = "red"
document.getElementById("uvindex").style.color = "white"
}
})
}
})
//fetch 5 day forecast
var apiUrl3 = "https://api.openweathermap.org/data/2.5/forecast?q=" + search +"&units=imperial" + "&appid=43ef190af294b1e96143aa8fe5347765"
fetch(apiUrl3).then(function(response){
if (response.ok) {
response.json().then(function(data) {
//data extraction
var date1 = data.list[0].dt_txt
var date1temp = data.list[0].main.temp
var date1hum = data.list[0].main.humidity
var date1icon =data.list[0].weather[0].icon
//day2
var date2 = data.list[11].dt_txt
var date2temp = data.list[11].main.temp
var date2hum = data.list[11].main.humidity
var date2icon =data.list[11].weather[0].icon
//day3
var date3 = data.list[19].dt_txt
var date3temp = data.list[19].main.temp
var date3hum = data.list[19].main.humidity
var date3icon =data.list[19].weather[0].icon
//day4
var date4 = data.list[27].dt_txt
var date4temp = data.list[27].main.temp
var date4hum = data.list[27].main.humidity
var date4icon =data.list[27].weather[0].icon
//day5
var date5 = data.list[35].dt_txt
var date5temp = data.list[35].main.temp
var date5hum = data.list[35].main.humidity
var date5icon =data.list[35].weather[0].icon
//convert temps to whole numbers
date1temp = Math.floor(date1temp)
date2temp = Math.floor(date2temp)
date3temp = Math.floor(date3temp)
date4temp = Math.floor(date4temp)
date5temp = Math.floor(date5temp)
var day1iconlink = ("https://openweathermap.org/img/wn/" + date1icon +"@2x.png")
var day2iconlink = ("https://openweathermap.org/img/wn/" + date2icon +"@2x.png")
var day3iconlink = ("https://openweathermap.org/img/wn/" + date3icon +"@2x.png")
var day4iconlink = ("https://openweathermap.org/img/wn/" + date4icon +"@2x.png")
var day5iconlink = ("https://openweathermap.org/img/wn/" + date5icon +"@2x.png")
//write data
//day1
document.getElementById("day1").textContent = date1
document.getElementById("day1temp").textContent = date1temp
document.getElementById("day1hum").textContent =date1hum
document.getElementById("day1icon").style.display ="flex"
document.getElementById("day1icon").style.backgroundImage = "url(" + day1iconlink +")"
//day2
document.getElementById("day2").textContent = date2
document.getElementById("day2temp").textContent = date2temp
document.getElementById("day2hum").textContent =date2hum
document.getElementById("day2icon").style.display ="flex"
document.getElementById("day2icon").style.backgroundImage = "url(" + day2iconlink +")"
//day3
document.getElementById("day3").textContent = date3
document.getElementById("day3temp").textContent = date3temp
document.getElementById("day3hum").textContent =date3hum
document.getElementById("day3icon").style.display ="flex"
document.getElementById("day3icon").style.backgroundImage = "url(" + day3iconlink +")"
//day4
document.getElementById("day4").textContent = date4
document.getElementById("day4temp").textContent = date4temp
document.getElementById("day4hum").textContent =date4hum
document.getElementById("day4icon").style.display ="flex"
document.getElementById("day4icon").style.backgroundImage = "url(" + day4iconlink +")"
//day5
document.getElementById("day5").textContent = date5
document.getElementById("day5temp").textContent = date5temp
document.getElementById("day5hum").textContent =date5hum
document.getElementById("day5icon").style.display ="flex"
document.getElementById("day5icon").style.backgroundImage = "url(" + day5iconlink +")"
//write values to Storage
//date1
window.localStorage.setItem("date1",date1);
window.localStorage.setItem("date1temp",date1temp);
window.localStorage.setItem("date1hum",date1hum);
window.localStorage.setItem("date1icon", date1icon);
//date2
window.localStorage.setItem("date2",date2);
window.localStorage.setItem("date2temp",date2temp);
window.localStorage.setItem("date2hum",date2hum);
window.localStorage.setItem("date2icon", date2icon);
//date3
window.localStorage.setItem("date3",date3);
window.localStorage.setItem("date3temp",date3temp);
window.localStorage.setItem("date3hum",date3hum);
window.localStorage.setItem("date3icon", date3icon);
//date4
window.localStorage.setItem("date4",date4);
window.localStorage.setItem("date4temp",date4temp);
window.localStorage.setItem("date4hum",date4hum);
window.localStorage.setItem("date4icon", date4icon);
//date5
window.localStorage.setItem("date5",date5);
window.localStorage.setItem("date5temp",date5temp);
window.localStorage.setItem("date5hum",date5hum);
window.localStorage.setItem("date5icon", date5icon);
})
}
})
});
} else {
alert("Error: " + response.statusText);
}
})
.catch(function(error) {
alert("Unable to connect");
});
};
var historyClickHandler =function(event){
//search for <Li> name
var history = event.target.getAttribute("data")
if(history){
var search = history.trim()
//send request for current date
var apiUrl1 ="https://api.openweathermap.org/data/2.5/weather?q="+ search + "&units=imperial"+ "&appid=" + "43ef190af294b1e96143aa8fe5347765"
// show request and convert, or log errors
fetch(apiUrl1).then(function(response) {
if (response.ok) {
response.json().then(function(data) {
//get lon, lat
var lon = data.coord.lon
var lat = data.coord.lat
//convert temp and wind speed to whole number
var tempnow = Math.floor(data.main.temp);
var windnow = Math.floor(data.wind.speed);
//write data to page
document.getElementById("cityname").textContent = data.name
document.getElementById("temp").textContent = tempnow
document.getElementById("wet").textContent = data.main.humidity
document.getElementById("speed").textContent = windnow
//display ui icon
var icon=data.weather[0]
var iconnow =icon.icon
var iconlink = ("https://openweathermap.org/img/wn/" + iconnow +"@2x.png")
document.getElementById("icon").style.display ="block"
document.getElementById("icon").style.backgroundImage = "url(" + iconlink +")"
//request UV index Data
var apiUrl2 = "https://api.openweathermap.org/data/2.5/uvi?lat=" + lat +"&lon="+lon+"&appid=" +"43ef190af294b1e96143aa8fe5347765"
fetch(apiUrl2).then(function(response){
if (response.ok) {
response.json().then(function(data) {
//pull value from uv fetch
var uv = data.value
uv= Math.floor(data.value)
//write uv to page
document.getElementById("uvindex").style.display ="block"
document.getElementById("uvindex").textContent =uv;
// color code UV index
if(uv <= 2){
document.getElementById("uvindex").style.background = "green"
document.getElementById("uvindex").style.color = "white"
}
if(uv >= 3 && uv <= 5){
document.getElementById("uvindex").style.background = "yellow"
document.getElementById("uvindex").style.color = "black"
}
if(uv >= 6 && uv <= 7){
document.getElementById("uvindex").style.background = "orange"
document.getElementById("uvindex").style.color = "black"
}
if(uv >= 8 && uv <= 10){
document.getElementById("uvindex").style.background = "red"
document.getElementById("uvindex").style.color = "white"
}
})
}
})
//fetch 5 day forecast
var apiUrl3 = "https://api.openweathermap.org/data/2.5/forecast?q=" + search +"&units=imperial" + "&appid=" +"43ef190af294b1e96143aa8fe5347765"
fetch(apiUrl3).then(function(response){
if (response.ok) {
response.json().then(function(data) {
//data extraction
var date1 = data.list[0].dt_txt
var date1temp = data.list[0].main.temp
var date1hum = data.list[0].main.humidity
var date1icon =data.list[0].weather[0].icon
//day2
var date2 = data.list[11].dt_txt
var date2temp = data.list[11].main.temp
var date2hum = data.list[11].main.humidity
var date2icon =data.list[11].weather[0].icon
//day3
var date3 = data.list[19].dt_txt
var date3temp = data.list[19].main.temp
var date3hum = data.list[19].main.humidity
var date3icon =data.list[19].weather[0].icon
//day4
var date4 = data.list[27].dt_txt
var date4temp = data.list[27].main.temp
var date4hum = data.list[27].main.humidity
var date4icon =data.list[27].weather[0].icon
//day5
var date5 = data.list[35].dt_txt
var date5temp = data.list[35].main.temp
var date5hum = data.list[35].main.humidity
var date5icon =data.list[35].weather[0].icon
//convert temps to whole numbers
date1temp = Math.floor(date1temp)
date2temp = Math.floor(date2temp)
date3temp = Math.floor(date3temp)
date4temp = Math.floor(date4temp)
date5temp = Math.floor(date5temp)
var day1iconlink = ("https://openweathermap.org/img/wn/" + date1icon +"@2x.png")
var day2iconlink = ("https://openweathermap.org/img/wn/" + date2icon +"@2x.png")
var day3iconlink = ("https://openweathermap.org/img/wn/" + date3icon +"@2x.png")
var day4iconlink = ("https://openweathermap.org/img/wn/" + date4icon +"@2x.png")
var day5iconlink = ("https://openweathermap.org/img/wn/" + date5icon +"@2x.png")
//write data
//day1
document.getElementById("day1").textContent = date1
document.getElementById("day1temp").textContent = date1temp
document.getElementById("day1hum").textContent = date1hum
document.getElementById("day1icon").style.display ="flex"
document.getElementById("day1icon").style.backgroundImage = "url(" + day1iconlink +")"
//day2
document.getElementById("day2").textContent = date2
document.getElementById("day2temp").textContent = date2temp
document.getElementById("day2hum").textContent =date2hum
document.getElementById("day2icon").style.display ="flex"
document.getElementById("day2icon").style.backgroundImage = "url(" + day2iconlink +")"
//day3
document.getElementById("day3").textContent = date3
document.getElementById("day3temp").textContent = date3temp
document.getElementById("day3hum").textContent =date3hum
document.getElementById("day3icon").style.display ="flex"
document.getElementById("day3icon").style.backgroundImage = "url(" + day3iconlink +")"
//day4
document.getElementById("day4").textContent = date4
document.getElementById("day4temp").textContent = date4temp
document.getElementById("day4hum").textContent =date4hum
document.getElementById("day4icon").style.display ="flex"
document.getElementById("day4icon").style.backgroundImage = "url(" + day4iconlink +")"
//day5
document.getElementById("day5").textContent = date5
document.getElementById("day5temp").textContent = date5temp
document.getElementById("day5hum").textContent =date5hum
document.getElementById("day5icon").style.display ="flex"
document.getElementById("day5icon").style.backgroundImage = "url(" + day5iconlink +")"
})
}
})
});
} else {
alert("Error: " + response.statusText);
}
})
.catch(function(error) {
alert("Unable to connect");
});
};
}
function loaddata(){
//today
//get data
var date = window.localStorage.getItem("Cityname");
var tempnow = window.localStorage.getItem("tempnow");
var humidity = window.localStorage.getItem("wet");
var windnow = window.localStorage.getItem("wet");
var iconlink = window.localStorage.getItem("iconlink");
var uv = window.localStorage.getItem("uv");
//write data
document.getElementById("cityname").textContent = date
document.getElementById("temp").textContent = tempnow
document.getElementById("wet").textContent = humidity
document.getElementById("speed").textContent = windnow
document.getElementById("icon").style.display = "block"
document.getElementById("icon").style.backgroundImage = "url(" + iconlink +")"
document.getElementById("uvindex").style.display = "block"
document.getElementById("uvindex").textContent = uv;
// color code UV index
if(uv <= 2){
document.getElementById("uvindex").style.background = "green"
document.getElementById("uvindex").style.color = "white"
}
if(uv >= 3 && uv <= 5){
document.getElementById("uvindex").style.background = "yellow"
document.getElementById("uvindex").style.color = "black"
}
if(uv >= 6 && uv <= 7){
document.getElementById("uvindex").style.background = "orange"
document.getElementById("uvindex").style.color = "black"
}
if(uv >= 8 && uv <= 10){
document.getElementById("uvindex").style.background = "red"
document.getElementById("uvindex").style.color = "white"
}
//get 5 day forecast
//date1
var date1 = window.localStorage.getItem("date1");
var date1temp = window.localStorage.getItem("date1temp");
var date1hum = window.localStorage.getItem("date1hum");
var date1icon = window.localStorage.getItem("date1icon");
//date2
var date2 = window.localStorage.getItem("date2");
var date2temp = window.localStorage.getItem("date2temp");
var date2hum = window.localStorage.getItem("date2hum");
var date2icon = window.localStorage.getItem("date2icon");
//date3
var date3 = window.localStorage.getItem("date3");
var date3temp = window.localStorage.getItem("date3temp");
var date3hum = window.localStorage.getItem("date3hum");
var date3icon = window.localStorage.getItem("date3icon");
//date4
var date4 = window.localStorage.getItem("date4");
var date4temp = window.localStorage.getItem("date4temp");
var date4hum = window.localStorage.getItem("date4hum");
var date4icon = window.localStorage.getItem("date4icon");
//date5
var date5 = window.localStorage.getItem("date5");
var date5temp = window.localStorage.getItem("date5temp");
var date5hum = window.localStorage.getItem("date5hum");
var date5icon = window.localStorage.getItem("date5icon");
//iconlinks
var day1iconlink = ("https://openweathermap.org/img/wn/" + date1icon +"@2x.png")
var day2iconlink = ("https://openweathermap.org/img/wn/" + date2icon +"@2x.png")
var day3iconlink = ("https://openweathermap.org/img/wn/" + date3icon +"@2x.png")
var day4iconlink = ("https://openweathermap.org/img/wn/" + date4icon +"@2x.png")
var day5iconlink = ("https://openweathermap.org/img/wn/" + date5icon +"@2x.png")
document.getElementById("day1").textContent = date1
document.getElementById("day1temp").textContent = date1temp
document.getElementById("day1hum").textContent = date1hum
document.getElementById("day1icon").style.display ="flex"
document.getElementById("day1icon").style.backgroundImage = "url(" + day1iconlink +")"
//day2
document.getElementById("day2").textContent = date2
document.getElementById("day2temp").textContent = date2temp
document.getElementById("day2hum").textContent =date2hum
document.getElementById("day2icon").style.display ="flex"
document.getElementById("day2icon").style.backgroundImage = "url(" + day2iconlink +")"
//day3
document.getElementById("day3").textContent = date3
document.getElementById("day3temp").textContent = date3temp
document.getElementById("day3hum").textContent =date3hum
document.getElementById("day3icon").style.display ="flex"
document.getElementById("day3icon").style.backgroundImage = "url(" + day3iconlink +")"
//day4
document.getElementById("day4").textContent = date4
document.getElementById("day4temp").textContent = date4temp
document.getElementById("day4hum").textContent =date4hum
document.getElementById("day4icon").style.display ="flex"
document.getElementById("day4icon").style.backgroundImage = "url(" + day4iconlink +")"
//day5
document.getElementById("day5").textContent = date5
document.getElementById("day5temp").textContent = date5temp
document.getElementById("day5hum").textContent =date5hum
document.getElementById("day5icon").style.display ="flex"
document.getElementById("day5icon").style.backgroundImage = "url(" + day5iconlink +")"
//write items from list
var callback = JSON.parse(localStorage.getItem("items"));
//loop to construct list items
for(i=0; i < callback.length; i++ ){
var entryLi = document.createElement("li")
entryLi.textContent = callback[i];
entryLi.setAttribute("class", "list-group-item");
entryLi.setAttribute("data", callback[i]);
document.getElementById("history").appendChild(entryLi);
}
}
//Event Listeners
searchbutton.addEventListener("click",function(){
searchvalue();
});
document.getElementById("history").addEventListener("click", historyClickHandler);
//data load
loaddata()
|
5efb933ed60389fbdd488863a48686c2d5414d74
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
tonganknight/Weather-Dashboard
|
bc5830c681cefb1126d99ef3dd05c4cb8aa34774
|
faa01c6d030adae7d20c0d9a344263351314d221
|
refs/heads/master
|
<file_sep>import { Component } from "@angular/core";
import { ArrayLayoutWidget } from "../../widget";
@Component({
selector: "array-widget",
template: require("./array.widget.html")
})
export class ArrayWidget extends ArrayLayoutWidget {
addItem() {
this.formProperty.addItem();
}
removeItem(index: number) {
this.formProperty.removeItem(index);
}
}
<file_sep>import { Component } from "@angular/core";
import { ControlWidget } from "../../widget";
@Component({
selector: "textarea-widget",
template: require("./textarea.widget.html")
})
export class TextAreaWidget extends ControlWidget {}
<file_sep>import {
Component,
} from "@angular/core";
import { ObjectLayoutWidget } from "../../widget";
@Component({
selector: "formobject",
template: require("./object.widget.html")
})
export class ObjectWidget extends ObjectLayoutWidget { }
<file_sep>import { Component, Directive, ElementRef, NgZone, Renderer, ViewEncapsulation,ViewContainerRef,ComponentMetadata} from "@angular/core";
import { FormComponent, WidgetRegistry, Validator, DefaultWidgetRegistry} from "../src";
@Component({
selector: "schema-form-demo-app",
template: require("./app.component.html"),
styleUrls: ["demo/app.scss"],
encapsulation: ViewEncapsulation.None,
providers: [{provide: WidgetRegistry, useClass: DefaultWidgetRegistry}]
})
export class AppComponent {
private schema:any;
private model:any;
private fieldValidators : { [fieldId:string]: Validator} = {};
private actions = {}
constructor(registry: WidgetRegistry) {
this.schema = (() => {
try {
return require("./sampleschema.json");
} catch (e) {
console.log(e);
}
})();
this.model = (() => {
try {
return require("./samplemodel.json");
} catch (e) {
console.log(e);
}
})();
this.fieldValidators["/bornOn"] = (value, property, form) => {
let errors = null;
let dateArr = value.split("-");
if (dateArr.length === 3) {
let now = new Date();
let min = new Date(now.getFullYear()-100, now.getMonth(), now.getDay()).getTime();
let max = new Date().getTime();
let born = new Date(dateArr[0],dateArr[1]-1,dateArr[2]).getTime();
if (born < min || born > max ) {
errors = [{"bornOn": {"expectedValue": ">today - 100 && < today", "actualValue":value}}];
}
}
return errors;
};
this.fieldValidators["/promotion"] = (value, property, form) => {
if (value === "student") {
let bornOn = form.getProperty("/bornOn");
if (bornOn.valid) {
let date = bornOn.value.split('-');
let validYear = new Date().getFullYear() -17;
try{
let actualYear = parseInt(date[0]);
if (actualYear < validYear) {
return null;
}
return [{"promotion": {"bornOn": {"expectedValue": "year<"+validYear, "actualValue": actualYear}}}];
} catch (e) { }
}
return [{"promotion": {"bornOn": {"expectedFormat": "date","actualValue": bornOn.value}}}];
}
return null;
}
this.actions["alert"] = (property, options) => {
alert(JSON.stringify(property.value));
}
this.actions["reset"] = (form, options) => {
form.reset();
}
this.actions["addItem"] =(property, parameters) => {
property.addItem(parameters.value);
}
}
}
<file_sep>import {
inject,
} from "@angular/core/testing";
import { IntegerWidget } from "./integer.widget";
describe("IntegerWidget", () => {
let THE_VALUE = 1337;
xit("should initialize value from input", () => {});
});
<file_sep>import {
ChangeDetectorRef,
Component,
EventEmitter,
Input,
Output
} from "@angular/core";
import {
Action,
ActionRegistry,
FormPropertyFactory,
FormProperty,
SchemaPreprocessor,
ValidatorRegistry,
Validator
} from "./model";
import { SchemaValidatorFactory, ZSchemaValidatorFactory } from "./schemavalidatorfactory";
import { WidgetFactory } from "./widgetfactory";
@Component({
selector: "schema-form",
template: require("./form.component.html"),
providers: [
ActionRegistry,
ValidatorRegistry,
SchemaPreprocessor,
WidgetFactory,
{
provide: SchemaValidatorFactory,
useClass: ZSchemaValidatorFactory
}, {
provide: FormPropertyFactory,
useFactory: (schemaValidatorFactory, validatorRegistry) => {
return new FormPropertyFactory(schemaValidatorFactory, validatorRegistry);
},
deps: [SchemaValidatorFactory, ValidatorRegistry]
}
]
})
export class FormComponent {
@Input() schema: any=null;
@Input() model: any;
@Input() actions: {[actionId: string]: Action} = {};
@Input() validators: {[path: string]: Validator} = {};
@Output() onChange = new EventEmitter<{value: any}>();
rootProperty: FormProperty = null;
constructor(private formPropertyFactory: FormPropertyFactory, private actionRegistry: ActionRegistry, private validatorRegistry: ValidatorRegistry, private cdr: ChangeDetectorRef) { }
ngOnChanges(changes: any) {
if (changes.validators) {
this.setValidators();
}
if (changes.actions) {
this.setActions();
}
if (changes.schema) {
SchemaPreprocessor.preprocess(this.schema);
this.rootProperty = this.formPropertyFactory.createProperty(this.schema);
this.rootProperty.valueChanges.subscribe(value => {this.onChange.emit({value: value})});
}
if (this.schema && (changes.model || changes.schema )) {
this.rootProperty.reset(this.model, false);
this.cdr.detectChanges();
}
}
private setValidators() {
this.validatorRegistry.clear();
if (this.validators) {
for (let validatorId in this.validators) {
this.validatorRegistry.register(validatorId, this.validators[validatorId]);
}
}
}
private setActions() {
this.actionRegistry.clear();
if (this.actions) {
for (let actionId in this.actions) {
this.actionRegistry.register(actionId, this.actions[actionId]);
}
}
}
public reset() {
this.rootProperty.reset(null, true);
}
}
<file_sep>#!/bin/sh
npm install @angular/forms @angular/common @angular/compiler @angular/platform-browser @angular/platform-browser-dynamic @angular/platform-server @angular/core rxjs zone.js
<file_sep>import { TestBed } from "@angular/core/testing";
import { WidgetFactory } from "./widgetfactory";
import { WidgetChooserComponent } from "./widgetchooser.component";
describe("WidgetChooserComponent", () => {
let factory: WidgetFactory;
it("should create a widget", ()=>{
TestBed.createComponent(WidgetChooserComponent);
});
xit("should put the widget returned by the factory in the DOM", () => {
});
});
<file_sep>export function isPresent(o) {
return o !== null && o !== undefined;
}
export function isBlank(o) {
return o === null || o === undefined;
}
<file_sep>import {
Component,
ChangeDetectorRef,
EventEmitter,
Inject,
Input,
OnInit,
Output,
ViewChild,
ViewContainerRef,
} from "@angular/core";
import { WidgetFactory } from "./widgetfactory";
@Component({
selector: "ng2sf-widget-chooser",
template: "<div #target></div>",
})
export class WidgetChooserComponent implements OnInit {
@Input() widgetInfo: any;
@Output() widgetInstanciated = new EventEmitter<any>();
@ViewChild('target', {read: ViewContainerRef}) private container: ViewContainerRef;
private widgetInstance: any;
constructor(private widgetFactory: WidgetFactory = null, private cdr: ChangeDetectorRef) {}
ngOnInit() {
let ref = this.widgetFactory.createWidget(this.container, this.widgetInfo.id);
this.widgetInstanciated.emit(ref.instance);
this.widgetInstance = ref.instance;
this.cdr.detectChanges();
}
}
<file_sep>import { Component } from "@angular/core";
import { BaseWidget } from "../../base";
@Component({
selector: "default-field",
template: `<p>Cannot find valid type for {{name}}`
})
export class DefaultWidget extends BaseWidget {}
<file_sep>import { ObjectProperty } from "./objectproperty";
import { FormProperty } from "./formproperty";
import { FormPropertyFactory } from "./formpropertyfactory";
import {
SchemaValidatorFactory,
ZSchemaValidatorFactory
} from "../schemavalidatorfactory";
import { ValidatorRegistry } from "./validatorregistry";
describe("ObjectProperty", () => {
let A_VALIDATOR_REGISTRY = new ValidatorRegistry();
let A_SCHEMA_VALIDATOR_FACTORY = new ZSchemaValidatorFactory();
let A_FORM_PROPERTY_FACTORY = new FormPropertyFactory(A_SCHEMA_VALIDATOR_FACTORY, A_VALIDATOR_REGISTRY);
let THE_OBJECT_SCHEMA = {
type: "object",
properties: {
FOO: {type: "integer"},
BAR: {type: "integer"},
BAZ: {type: "object"}
}
};
let objProperty: ObjectProperty;
beforeEach(() => {
objProperty = new ObjectProperty(A_FORM_PROPERTY_FACTORY, A_SCHEMA_VALIDATOR_FACTORY, A_VALIDATOR_REGISTRY, THE_OBJECT_SCHEMA, null, "");
});
it("should create same properties as in the schema", () => {
for (let propertyId in THE_OBJECT_SCHEMA.properties) {
let property = objProperty.getProperty(propertyId);
expect(property).toBeDefined();
}
});
it("should reset all its properties on reset", () => {
let propFactory = new FormPropertyFactory(A_SCHEMA_VALIDATOR_FACTORY, A_VALIDATOR_REGISTRY);
let objProp = new ObjectProperty(propFactory, A_SCHEMA_VALIDATOR_FACTORY, A_VALIDATOR_REGISTRY, THE_OBJECT_SCHEMA, null, "");
let property = new (<any>FormProperty)(A_SCHEMA_VALIDATOR_FACTORY, {}, objProp);
for (let propertyId in THE_OBJECT_SCHEMA.properties) {
let newProperty = objProperty.getProperty(propertyId);
expect(newProperty).not.toBe(property);
}
spyOn(propFactory, "createProperty").and.returnValue(property);
objProp.reset(null);
for (let propertyId in THE_OBJECT_SCHEMA.properties) {
let newProperty = objProp.getProperty(propertyId);
expect(newProperty).toBe(property);
}
});
});
<file_sep>import { AtomicProperty } from "./atomicproperty";
export class NumberProperty extends AtomicProperty {
protected fallbackValue() {
let value;
if (this.schema.minimum !== undefined) {
value = this.schema.minimum;
} else {
value = 0;
}
return value;
}
}
<file_sep>import { FormProperty, PropertyGroup } from "./formproperty";
import {
ZSchemaValidatorFactory,
SchemaValidatorFactory
} from "../schemavalidatorfactory";
import { ValidatorRegistry } from "./validatorregistry";
class FormPropertyImpl extends FormProperty {
protected fallbackValue() {
return Symbol();
}
_updateValue() {}
setValue() {}
reset() {}
}
class PropertyGroupImpl extends PropertyGroup {
_updateValue() {}
setValue() {}
reset() {}
}
describe("FormProperty", () => {
let A_VALUE = "FOO";
let THE_VALUE = "BAR";
let A_SCHEMA_VALIDATOR_FACTORY = new ZSchemaValidatorFactory();
let A_VALIDATOR_REGISTRY = new ValidatorRegistry();
let THE_SCHEMA_VALIDATOR_FACTORY;
let A_PROPERTY_SCHEMA = {};
let THE_PROPERTY_SCHEMA = {};
let THE_PARENT_PROPERTY_SCHEMA = {};
let THE_VALIDATOR;
let formProperty: FormProperty;
let parentProperty: PropertyGroup;
beforeEach(() => {
THE_SCHEMA_VALIDATOR_FACTORY = new ZSchemaValidatorFactory();
THE_VALIDATOR = jasmine.createSpy("a_validator");
spyOn(THE_SCHEMA_VALIDATOR_FACTORY, "createValidatorFn").and.returnValue(THE_VALIDATOR);
parentProperty = new PropertyGroupImpl(THE_SCHEMA_VALIDATOR_FACTORY, A_VALIDATOR_REGISTRY, THE_PARENT_PROPERTY_SCHEMA, null, "");
spyOn(parentProperty,"updateValueAndValidity");
formProperty = new FormPropertyImpl(THE_SCHEMA_VALIDATOR_FACTORY, A_VALIDATOR_REGISTRY, THE_PROPERTY_SCHEMA, parentProperty, "");
});
it("should create a validator on construction", () => {
expect(THE_SCHEMA_VALIDATOR_FACTORY.createValidatorFn).toHaveBeenCalledWith(THE_PROPERTY_SCHEMA);
});
it("should validate using the validator created on construction", () => {
formProperty._runValidation();
expect(THE_VALIDATOR).toHaveBeenCalled();
});
it("with parent should notify parent when changed", () => {
formProperty.updateValueAndValidity();
expect(parentProperty.updateValueAndValidity).toHaveBeenCalledWith(formProperty);
});
it("with no parent should not throw when changed", () => {
let orphanFormProperty = new FormPropertyImpl(A_SCHEMA_VALIDATOR_FACTORY, A_VALIDATOR_REGISTRY, THE_PROPERTY_SCHEMA, null, "");
let updateValue = (() => {orphanFormProperty.updateValueAndValidity();})
expect(updateValue).not.toThrow();
});
});
|
f12ff2a9b99f40c71dea2d5874b6fe15729591ee
|
[
"TypeScript",
"Shell"
] | 14 |
TypeScript
|
mhegelele/angular2-schema-form
|
f461f2cd7ed604dde9b4665bbbdac032397bb0c0
|
476851888aba7d7a90e14cc2d2cb2f231317056e
|
refs/heads/master
|
<repo_name>justin0bk/socketrecv<file_sep>/README.md
# socketrecv
socketrecv.py is a program run by the Raspberry Pi to communicate with PC for the laser TTL controls.
<file_sep>/socketrecv.py
import sys
import socket
import RPi.GPIO as GPIO
from threading import Thread
import time
def get_ip_address():
ip_address = '';
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8",80))
ip_address = s.getsockname()[0]
s.close()
return ip_address
GPIO.setmode(GPIO.BOARD)
GPIO.setwarnings(False)
pin_onoff = 36
pin_ol = 37
pin_cl1 = 15
fpin_cl1 = 16
pin_cl2 = 18
fpin_cl2 = 22
pin_cl3 = 29
fpin_cl3 = 31
pin_cl4 =32
fpin_cl4 = 33
GPIO.setup(pin_onoff, GPIO.OUT, initial = 0)
GPIO.setup(pin_ol, GPIO.OUT, initial = 0)
GPIO.setup(pin_cl1, GPIO.OUT, initial = 0)
GPIO.setup(fpin_cl1, GPIO.OUT, initial = 0)
GPIO.setup(pin_cl2, GPIO.OUT, initial = 0)
GPIO.setup(fpin_cl2, GPIO.OUT, initial = 0)
GPIO.setup(pin_cl3, GPIO.OUT, initial = 0)
GPIO.setup(fpin_cl3, GPIO.OUT, initial = 0)
GPIO.setup(pin_cl4, GPIO.OUT, initial = 0)
GPIO.setup(fpin_cl4, GPIO.OUT, initial = 0)
def set_hi_lo(hi, lo):
hi = float(hi)
lo = float(lo)
freq = 1000/(hi+lo)
dutcy = (hi)/(hi+lo)*100
return freq, dutcy
def start_cycle():
global server
global client
hi = 5 #default hi
lo = 95 #default lo
freq, dutcy = set_hi_lo(hi, lo)
puldur = 120
print("by default, hi=5, lo=95, freq=10, dutcy = 5%, puldur = 120")
p_cl1 = GPIO.PWM(pin_cl1, freq)
p_cl2 = GPIO.PWM(pin_cl2, freq)
p_cl3 = GPIO.PWM(pin_cl3, freq)
p_cl4 = GPIO.PWM(pin_cl4, freq)
fp_cl1 = GPIO.PWM(fpin_cl1, freq)
fp_cl2 = GPIO.PWM(fpin_cl2, freq)
fp_cl3 = GPIO.PWM(fpin_cl3, freq)
fp_cl4 = GPIO.PWM(fpin_cl4, freq)
p_cl1 = GPIO.PWM(pin_cl1, freq)
fp_cl1 = GPIO.PWM(fpin_cl1, freq)
p_cl1.start(0)
fp_cl1.start(0)
p_cl2 = GPIO.PWM(pin_cl2, freq)
fp_cl2 = GPIO.PWM(fpin_cl2, freq)
p_cl2.start(0)
fp_cl2.start(0)
p_cl3 = GPIO.PWM(pin_cl3, freq)
fp_cl3 = GPIO.PWM(fpin_cl3, freq)
p_cl3.start(0)
fp_cl3.start(0)
p_cl4 = GPIO.PWM(pin_cl4, freq)
fp_cl4 = GPIO.PWM(fpin_cl4, freq)
p_cl4.start(0)
fp_cl4.start(0)
while True:
msg = client.recv(8)
print(msg)
if msg == 'STAT0000':
GPIO.output(pin_onoff, 0)
GPIO.output(pin_ol, 0)
p_cl1.ChangeDutyCycle(0)
fp_cl1.ChangeDutyCycle(0)
p_cl2.ChangeDutyCycle(0)
fp_cl2.ChangeDutyCycle(0)
p_cl3.ChangeDutyCycle(0)
fp_cl3.ChangeDutyCycle(0)
p_cl4.ChangeDutyCycle(0)
fp_cl4.ChangeDutyCycle(0)
elif msg == 'STAT0001':
GPIO.output(pin_onoff, 1)
elif msg == 'STAT0101':
p_cl1.ChangeFrequency(freq)
fp_cl1.ChangeFrequency(freq)
p_cl1.ChangeDutyCycle(dutcy)
fp_cl1.ChangeDutyCycle(dutcy)
p_cl2.ChangeFrequency(freq)
fp_cl2.ChangeFrequency(freq)
p_cl2.ChangeDutyCycle(dutcy)
fp_cl2.ChangeDutyCycle(dutcy)
time.sleep(puldur-1)
p_cl1.ChangeDutyCycle(0)
fp_cl1.ChangeDutyCycle(0)
p_cl2.ChangeDutyCycle(0)
fp_cl2.ChangeDutyCycle(0)
elif msg == 'STAT0201':
fp_cl1.ChangeFrequency(freq)
fp_cl1.ChangeDutyCycle(dutcy)
elif msg == 'STAT0211':
p_cl1.ChangeFrequency(freq)
fp_cl1.ChangeFrequency(freq)
p_cl1.ChangeDutyCycle(dutcy)
fp_cl1.ChangeDutyCycle(dutcy)
elif msg == 'STAT0200':
p_cl1.ChangeDutyCycle(0)
fp_cl1.ChangeDutyCycle(0)
elif msg == 'STAT0301':
fp_cl2.ChangeFrequency(freq)
fp_cl2.ChangeDutyCycle(dutcy)
elif msg == 'STAT0311':
p_cl2.ChangeFrequency(freq)
fp_cl2.ChangeFrequency(freq)
p_cl2.ChangeDutyCycle(dutcy)
fp_cl2.ChangeDutyCycle(dutcy)
elif msg == 'STAT0300':
p_cl2.ChangeDutyCycle(0)
fp_cl2.ChangeDutyCycle(0)
elif msg == 'STAT0401':
fp_cl3.ChangeFrequency(freq)
fp_cl3.ChangeDutyCycle(dutcy)
elif msg == 'STAT0411':
p_cl3.ChangeFrequency(freq)
fp_cl3.ChangeFrequency(freq)
p_cl3.ChangeDutyCycle(dutcy)
fp_cl3.ChangeDutyCycle(dutcy)
elif msg == 'STAT0400':
p_cl3.ChangeDutyCycle(0)
fp_cl3.ChangeDutyCycle(0)
elif msg == 'STAT0501':
fp_cl4.ChangeFrequency(freq)
fp_cl4.ChangeDutyCycle(dutcy)
elif msg == 'STAT0511':
p_cl4.ChangeFrequency(freq)
fp_cl4.ChangeFrequency(freq)
p_cl4.ChangeDutyCycle(dutcy)
fp_cl4.ChangeDutyCycle(dutcy)
elif msg == 'STAT0500':
p_cl4.ChangeDutyCycle(0)
fp_cl4.ChangeDutyCycle(0)
elif 'HI' in msg:
hi = int(msg[2:])
freq, dutcy = set_hi_lo(hi,lo)
elif 'LO' in msg:
lo = int(msg[2:])
freq, dutcy = set_hi_lo(hi,lo)
elif 'PD' in msg:
puldur = int(msg[2:])
elif msg == 'END_PROG':
server.close()
return
def setup_network():
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
host = get_ip_address()
print('host ip: ' + host)
port = 5010
time.sleep(1)
try:
server.bind((host,port))
except socket.error:
try:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind((host, port))
except:
sys.exit('Port' + str(port) + ' is occupied')
server.listen(5)
client, address = server.accept()
print('Client found:', address)
return server, client
recv_thread = Thread(target=start_cycle)
while True:
if not recv_thread.isAlive():
server, client = setup_network()
recv_thread = Thread(target=start_cycle)
recv_thread.start()
recv_thread.join()
server.close()
server = None
client = None
|
8809d5bb42e0373ed6543334922ac3c27db63c41
|
[
"Markdown",
"Python"
] | 2 |
Markdown
|
justin0bk/socketrecv
|
7552446c8f57b43d4dc43f35bda0ad4844c5acd4
|
0749a8f9b99f67255409e6e10365f5966d5ab373
|
refs/heads/master
|
<file_sep># frozen_string_literal: true
require 'solidus_core'
require 'solidus_support'
require 'solidus_virtual_gift_card/version'
require 'solidus_virtual_gift_card/engine'
require 'deface'
<file_sep># frozen_string_literal: true
require 'solidus_virtual_gift_card/factories'
|
6d271613a65e39afe8fc7aac721183210cb1f2ae
|
[
"Ruby"
] | 2 |
Ruby
|
octave/solidus_virtual_gift_card
|
ac37b83753fd10c1462864e5b0dca3a90e69e6d6
|
aef8dc8d9639cba7f43bd1c4da9640ad2e595cb6
|
refs/heads/master
|
<file_sep>package com.yoyo.smtpms.util;
import android.content.Context;
import android.content.SharedPreferences;
/**
* SharedPreferencesๅทฅๅ
ท็ฑป
* Created by Administrator on 2017/4/21 0021.
*/
public class SPUtil {
public static void saveString(Context context, String key, String value){
SharedPreferences config = context.getSharedPreferences("config", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = config.edit();
edit.putString(key,value);
edit.commit();
}
public static String getString(Context context, String key, String defaultVlaue){
SharedPreferences config = context.getSharedPreferences("config", Context.MODE_PRIVATE);
return config.getString(key,defaultVlaue);
}
public static void saveInt(Context context, String key, int value){
SharedPreferences config = context.getSharedPreferences("config", Context.MODE_PRIVATE);
SharedPreferences.Editor edit = config.edit();
edit.putInt(key,value);
edit.commit();
}
public static int getInt(Context context,String key, int defaultVlaue){
SharedPreferences config = context.getSharedPreferences("config", Context.MODE_PRIVATE);
return config.getInt(key,defaultVlaue);
}
}
<file_sep>package com.yoyo.smtpms.view;
import android.app.Activity;
import android.app.Dialog;
import android.inputmethodservice.KeyboardView;
import android.support.v7.app.AlertDialog;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import com.yoyo.smtpms.R;
/**
* @author Administrator
* @date 2019-10-27
*/
public class MyDialog {
private Activity mHostActivity;
private TextView txtDialog;
private EditText etDialogNum;
private Button btnComfirm;
private Button btnCancel;
private AlertDialog.Builder builder;
private KeyboardView keyboardView;
private final KeyboarBuilder keyboarBuilder;
private Dialog dialog;
public MyDialog(Activity activity){
mHostActivity = activity;
View inflate = mHostActivity.getLayoutInflater().inflate(R.layout.dialog, null);
txtDialog = inflate.findViewById(R.id.txtDialog);
btnComfirm = inflate.findViewById(R.id.btn_dialog_OK);
btnCancel = inflate.findViewById(R.id.btn_dialog_cancel);
keyboardView = inflate.findViewById(R.id.keyboardview);
etDialogNum = inflate.findViewById(R.id.et_dialog_num);
builder = new AlertDialog.Builder(mHostActivity);
builder.setView(inflate);
keyboarBuilder = new KeyboarBuilder(mHostActivity, keyboardView, R.xml.hexkbd, etDialogNum);
}
public MyDialog setText(String text){
txtDialog.setText(text);
return this;
}
public MyDialog setComfirmListener(final View.OnClickListener comfirmListener) {
btnComfirm.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(comfirmListener != null) {
comfirmListener.onClick(etDialogNum);
}
if(dialog != null){
dialog.dismiss();
}
keyboarBuilder.hideCustomKeyboard();
}
});
return this;
}
public MyDialog setCancelListener(final View.OnClickListener cancelListener){
btnCancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(cancelListener != null) {
cancelListener.onClick(etDialogNum);
}
if(dialog != null){
dialog.dismiss();
}
keyboarBuilder.hideCustomKeyboard();
}
});
return this;
}
public void show(){
dialog = builder.show();
dialog.getWindow().setGravity(Gravity.TOP | Gravity.CENTER);
dialog.setCanceledOnTouchOutside(false);
}
}
<file_sep>package com.yoyo.smtpms.util;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
/**
* Created by Administrator on 2016-06-25.
*/
public class IOUtils {
/**
* ๅๆไปถๅๅ
ฅๆฐๆฎ
*
* @param path
* @param content
* @throws IOException
*/
public static void writeToFile(String path, String content,boolean append) throws IOException {
File file = new File(path);
File parent = file.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
if (!file.exists()) {
file.createNewFile();
}
FileWriter fw = new FileWriter(file,append);
fw.write(content);
fw.flush();
fw.close();
}
/**
* ่ฏปๅๅฐๆไปถ
*
* @param path
* @return
* @throws FileNotFoundException
* @throws IOException
*/
static public String readFormFile(String path, String code)
throws FileNotFoundException, IOException {
String result = "";
File file = new File(path);
if (file.exists()) {
//FileReader fr = new FileReader(file);
FileInputStream is = new FileInputStream(file);
//char[] bb = new char[1024]; // ็จๆฅไฟๅญๆฏๆฌก่ฏปๅๅฐ็ๅญ็ฌฆ
byte[] buffer = new byte[1024];
int n;// ๆฏๆฌก่ฏปๅๅฐ็ๅญ็ฌฆ้ฟๅบฆ
while ((n = is.read(buffer)) != -1) {
result += new String(buffer, 0, n, code);
}
is.close();
}
return result;
}
/**
* ๅฎ็ฐๆไปถ็ๆท่ด
* @param srcPathStr
* ๆบๆไปถ็ๅฐๅไฟกๆฏ
* @param desPathStr
* ็ฎๆ ๆไปถ็ๅฐๅไฟกๆฏ
*/
public static void copyFile(String srcPathStr, String desPathStr) {
try{
//2.ๅๅปบ่พๅ
ฅ่พๅบๆตๅฏน่ฑก
FileInputStream fis = new FileInputStream(srcPathStr);
FileOutputStream fos = new FileOutputStream(desPathStr);
//ๅๅปบๆฌ่ฟๅทฅๅ
ท
byte datas[] = new byte[1024*8];
//ๅๅปบ้ฟๅบฆ
int len = 0;
//ๅพช็ฏ่ฏปๅๆฐๆฎ
while((len = fis.read(datas))!=-1){
fos.write(datas,0,len);
}
//3.้ๆพ่ตๆบ
fis.close();
fis.close();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* ๆ นๆฎๆๅฎ่ทฏๅพๅคๆญๆไปถๆฏๅฆๅญๅจ
*
* @param path
* @return
*/
public static Boolean fileIsExist(String path) {
File file = new File(path);
if (file.exists()) {
return true;
}
return false;
}
public static Bitmap decoderFileAsBitmap(File file){
if(file == null) return null;
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(new FileInputStream(file));
} catch (FileNotFoundException e) {
e.printStackTrace();
return null;
}
return bitmap;
}
/**
* ๅ ้คๆๅฎ่ทฏๅพไธ็ๆไปถ
*
* @param path
*/
public static boolean deleteFoder(String path) {
File file = new File(path);
boolean isSuccess = true;
// ๅคๆญๆไปถๆฏๅฆๅญๅจ
if (file.exists()) {
// ๅคๆญๆฏๅฆๆฏๆไปถ
if (file.isFile()) {
isSuccess = file.delete();
// ๅฆๅๅฆๆๅฎๆฏไธไธช็ฎๅฝ
} else if (file.isDirectory()) {
// ๅฃฐๆ็ฎๅฝไธๆๆ็ๆไปถ files[];
File files[] = file.listFiles();
if (files != null) {
if(files.length > 0) {
// ้ๅ็ฎๅฝไธๆๆ็ๆไปถ
for (int i = 0; i < files.length; i++) {
// ๆๆฏไธชๆไปถ
// ็จ่ฟไธชๆนๆณ่ฟ่ก่ฟญไปฃ
deleteFoder(files[i].getAbsolutePath());
}
}else{
file.delete();
}
}
}
if(file.exists()) {
isSuccess = file.delete();
}
if (!isSuccess) {
return false;
}
}
return true;
}
public static void saveBitmap(Bitmap bitmap,String fileName){
File file = new File(fileName);
if(!file.getParentFile().exists()){
file.getParentFile().mkdir();
}
if (!file.exists()){
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
<file_sep>apply plugin: 'com.android.application'
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.yoyo.smtpms"
minSdkVersion 16
targetSdkVersion 26
versionCode 2
versionName "2.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
multiDexEnabled true //่งฃๅณๅฏผๅ
ไธชๆฐ็้ๅถ
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.github.huangyanbin:SmartTable:2.2.0'
implementation 'com.orhanobut:dialogplus:1.7@aar'
implementation project(':SlidingMenulibrary')
implementation 'org.xutils:xutils:3.5.0'
implementation files('libs/jxl.jar')
implementation files('libs/fastjson-1.2.31.jar')
implementation files('libs/poi-3.5-FINAL/lib/commons-logging-1.1.jar')
implementation files('libs/poi-3.5-FINAL/lib/junit-3.8.1.jar')
implementation files('libs/poi-3.5-FINAL/lib/log4j-1.2.13.jar')
implementation files('libs/poi-3.5-FINAL/ooxml-lib/dom4j-1.6.1.jar')
implementation files('libs/poi-3.5-FINAL/ooxml-lib/geronimo-stax-api_1.0_spec-1.0.jar')
implementation files('libs/poi-3.5-FINAL/ooxml-lib/ooxml-schemas-1.0.jar')
implementation files('libs/poi-3.5-FINAL/ooxml-lib/xmlbeans-2.3.0.jar')
implementation files('libs/poi-3.5-FINAL/poi-3.5-FINAL-20090928.jar')
implementation files('libs/poi-3.5-FINAL/poi-contrib-3.5-FINAL-20090928.jar')
implementation files('libs/poi-3.5-FINAL/poi-ooxml-3.5-FINAL-20090928.jar')
implementation files('libs/poi-3.5-FINAL/poi-scratchpad-3.5-FINAL-20090928.jar')
}
<file_sep>package com.yoyo.smtpms;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.yoyo.smtpms.util.JsonHelper;
import com.yoyo.smtpms.util.SPUtil;
import java.util.ArrayList;
import java.util.List;
public class LoginActivity extends AppCompatActivity {
EditText etName;
EditText etIp;
Button btnLogin;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!SPUtil.getString(this,"name","").equals("")){
Intent intent = new Intent(this,MainActivity.class);
startActivity(intent);
finish();
return;
}
setContentView(R.layout.activity_login);
etName = findViewById(R.id.et_name);
etIp = findViewById(R.id.et_ip);
btnLogin = findViewById(R.id.bt_login);
btnLogin.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (!etName.getText().toString().equals("") && !etIp.getText().toString().equals("")){
List<String> userNameList = JsonHelper.getUserNameList(LoginActivity.this);
if(userNameList == null){
userNameList = new ArrayList<>();
}
userNameList.add(etName.getText().toString().trim());
JsonHelper.saveUserNameList(LoginActivity.this,userNameList);
SPUtil.saveString(LoginActivity.this,"name",etName.getText().toString().trim());
SPUtil.saveString(LoginActivity.this,"severIP",etIp.getText().toString().trim());
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
startActivity(intent);
finish();
}else {
Toast.makeText(LoginActivity.this,"็จๆทๅๅๆๅกๅจIPไธ่ฝไธบ็ฉบ๏ผ",Toast.LENGTH_LONG).show();
}
}
});
}
}
|
d4ea71450662a3eb5dc173aa822dc7e9bc1eba70
|
[
"Java",
"Gradle"
] | 5 |
Java
|
suneys/SMTPMS
|
70c8842d0081b3cfed7ab532b0ebfaf1ea320a48
|
1e2c80ed6a3f8e55df6fd22355446c07ff802689
|
refs/heads/master
|
<file_sep>$(function () {
"use strict";
// for better performance - to avoid searching in DOM
var content = $('#content');
var input = $('#input');
var status = $('#status');
var roomSelector = $('#roomSelector');
var commandMessages = $('#commandMessages');
var roomContentContainer = $('#roomContentContainer');
// my color assigned by the server
var myColor = false;
// my name sent to the server
var myName = false;
// if user is running mozilla then use it's built-in WebSocket
window.WebSocket = window.WebSocket || window.MozWebSocket;
// if browser doesn't support WebSocket, just show some notification and exit
if (!window.WebSocket) {
content.html($('<p>', { text: 'Sorry, but your browser doesn\'t '
+ 'support WebSockets.'} ));
input.hide();
$('span').hide();
return;
}
// open connection
var connection = new WebSocket('ws://localhost:1337');
connection.onopen = function () {
// first we want users to enter their names
input.removeAttr('disabled');
status.text('Choose name:');
};
connection.onerror = function (error) {
// just in there were some problems with conenction...
content.html($('<p>', { text: 'Sorry, but there\'s some problem with your '
+ 'connection or the server is down.' } ));
};
// most important part - incoming messages
connection.onmessage = function (message) {
// try to parse JSON message. Because we know that the server always returns
// JSON this should work without any problem but we should make sure that
// the massage is not chunked or otherwise damaged.
try {
var json = JSON.parse(message.data);
} catch (e) {
console.log('This doesn\'t look like a valid JSON: ', message.data);
return;
}
// NOTE: if you're not sure about the JSON structure
// check the server source code above
if (json.type === 'username_error') { // user name error message from the server
content.html($('<p>', { text: 'Error: User name ' + json.data + ' is already taken. Please try another one' } ));
input.removeAttr('disabled').val('');
myName = false;
} else if (json.type === 'roomnamenotunique_error') { // room name error message from the server
commandMessages.html($('<p>', { text: 'Error: Room name ' + json.data + ' is already taken. Please try another one' } ));
input.removeAttr('disabled').val('');
myName = false;
} else if (json.type === 'roomnamenotfound_error') { // room name error message from the server
commandMessages.html($('<p>', { text: 'Error: Room name ' + json.data + ' does\'nt exist. Please try again' } ));
input.removeAttr('disabled').val('');
myName = false;
} else if (json.type === 'color') { // first response from the server with user's color
myColor = json.data;
content.html('');
status.text(myName + ': ').css('color', myColor);
input.removeAttr('disabled').focus();
// from now user can start sending messages
} else if (json.type === 'room_created') {
var roomName = json.roomName;
roomContentContainer.append('<div id="' + roomName.toLowerCase() + 'Content"><div>');
$('#selectRoomHeader').show();
roomSelector.append('<label for="' + roomName + '"><input type="radio" name="roomSelectionOption" onchange="roomChanged(this)" id="' + roomName + '" /> ' + roomName + '</label>');
$('#' + roomName).prop('checked', true);
$('#roomContentContainer div').hide();
$('#' + roomName.toLowerCase() + 'Content').show();
input.removeAttr('disabled').focus();
} else if (json.type === 'room_joined') {
var roomName = json.roomName;
roomContentContainer.append('<div id="' + roomName.toLowerCase() + 'Content"><div>');
$('#selectRoomHeader').show();
roomSelector.append('<label for="' + roomName + '"><input type="radio" name="roomSelectionOption" onchange="roomChanged(this)" id="' + roomName + '" /> ' + roomName + '</label>');
$('#' + roomName).prop('checked', true);
var roomNameContentDiv = $('#' + roomName.toLowerCase() + 'Content');
$('#roomContentContainer div').hide();
$('#' + roomName.toLowerCase() + 'Content').show();
// insert every single message to the chat window
console.log('Received ' + json.data.length);
for (var i=0; i < json.data.length; i++) {
addMessage(roomNameContentDiv, json.data[i].author, json.data[i].text,
json.data[i].color, new Date(json.data[i].time));
}
input.removeAttr('disabled').focus();
} else if (json.type === 'room_left') {
var roomName = json.roomName;
$('#' + roomName.toLowerCase() + 'Content').remove();
$('#' + roomName).parent().remove();
$('input[name=roomSelectionOption]:first').prop('checked', true);
var roomToBeDisplayed = $('input[name=roomSelectionOption]:first').attr('id');
if (roomToBeDisplayed) {
$('#roomContentContainer div').hide();
$('#' + roomToBeDisplayed.toLowerCase() + 'Content').show();
} else {
$('#content').show();
$('#selectRoomHeader').hide();
}
input.removeAttr('disabled').focus();
} else if (json.type === 'history') { // entire message history
var roomName = json.roomName;
roomContentContainer.append('<div id="' + roomName.toLowerCase() + 'Content"><div>');
var roomNameContentDiv = $('#' + roomName.toLowerCase() + 'Content');
// insert every single message to the chat window
for (var i=0; i < json.data.length; i++) {
addMessage(roomNameContentDiv, json.data[i].author, json.data[i].text,
json.data[i].color, new Date(json.data[i].time));
}
} else if (json.type === 'message') { // it's a single message
input.removeAttr('disabled'); // let the user write another message
var roomName = json.roomName;
//roomContentContainer.append('<div id="' + roomName.toLowerCase() + 'Content"><div>');
var roomNameContentDiv = $('#' + roomName.toLowerCase() + 'Content');
addMessage(roomNameContentDiv, json.data.author, json.data.text,
json.data.color, new Date(json.data.time));
} else {
input.removeAttr('disabled');
console.log('Hmm..., I\'ve never seen JSON like this: ', json);
}
};
/**
* Send mesage when user presses Enter key
*/
input.keydown(function(e) {
if (e.keyCode === 13) {
var msg = $(this).val().trim();
if (!msg) {
return;
}
commandMessages.html('');
if (myName && !(msg.startsWith('mkgroup ') || msg.startsWith('lvgroup ') || msg.startsWith('jgroup '))) {
var roomName = $('input[name=roomSelectionOption]:checked').attr('id');
if (roomName) {
msg = roomName + ' ' + msg;
} else {
return;
}
}
// we know that the first message sent from a user their name
if (myName === false) {
myName = msg;
}
// send the message as an ordinary text
connection.send(msg);
$(this).val('');
// disable the input field to make the user wait until server
// sends back response
input.attr('disabled', 'disabled');
}
});
/**
* This method is optional. If the server wasn't able to respond to the
* in 3 seconds then show some error message to notify the user that
* something is wrong.
*/
setInterval(function() {
if (connection.readyState !== 1) {
status.text('Error');
input.attr('disabled', 'disabled').val('Unable to comminucate '
+ 'with the WebSocket server.');
}
}, 3000);
/**
* Add message to the chat window
*/
function addMessage(contentDiv, author, message, color, dt) {
contentDiv.append('<p><span style="color:' + color + '">' + author + '</span> @ ' +
+ (dt.getHours() < 10 ? '0' + dt.getHours() : dt.getHours()) + ':'
+ (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes())
+ ': ' + message + '</p>');
}
});
function roomChanged(elm) {
$('#commandMessages').html('');
var roomNameToBeDisplayed = $(elm).attr('id');
$('#roomContentContainer div').hide();
console.log(roomNameToBeDisplayed);
$('#' + roomNameToBeDisplayed.toLowerCase() + 'Content').show();
}<file_sep>"use strict";
//Optional. You will see this name in eg. 'ps' or 'top' command
process.title = 'node-chat';
//Port where we'll run the websocket server
var webSocketsServerPort = 1337;
//websocket and http servers
var webSocketServer = require('websocket').server;
var http = require('http');
/**
* Global variables
*/
//latest 100 messages
var history = [ ];
//list of currently connected clients (users)
var clients = [ ];
//list of rooms (aka group chats)
var rooms = [ ];
var roomNames = [ ];
//list of user names
var userNames = [ ];
/**
* Helper function for escaping input strings
*/
function htmlEntities(str) {
return String(str).replace(/&/g, '&').replace(/</g, '<')
.replace(/>/g, '>').replace(/"/g, '"');
}
//Array with some colors
var colors = [ 'red', 'green', 'blue', 'magenta', 'purple', 'plum', 'orange' ];
//... in random order
colors.sort(function(a,b) { return Math.random() > 0.5; } );
/**
* HTTP server
*/
var server = http.createServer(function(request, response) {
// Not important for us. We're writing WebSocket server, not HTTP server
});
server.listen(webSocketsServerPort, function() {
console.log((new Date()) + " Server is listening on port " + webSocketsServerPort);
});
/**
* WebSocket server
*/
var wsServer = new webSocketServer({
// WebSocket server is tied to a HTTP server. WebSocket request is just
// an enhanced HTTP request. For more info http://tools.ietf.org/html/rfc6455#page-6
httpServer: server
});
//This callback function is called every time someone
//tries to connect to the WebSocket server
wsServer.on('request', function(request) {
console.log((new Date()) + ' Connection from origin ' + request.origin + '.');
// accept connection - you should check 'request.origin' to make sure that
// client is connecting from your website
// (http://en.wikipedia.org/wiki/Same_origin_policy)
var connection = request.accept(null, request.origin);
// we need to know client index to remove them on 'close' event
var index = clients.push(connection) - 1;
var userName = false;
var userColor = false;
console.log((new Date()) + ' Connection accepted.');
// send back chat history
if (history.length > 0) {
//connection.sendUTF(JSON.stringify( { type: 'history', data: history} ));
}
// user sent some message
connection.on('message', function(message) {
if (message.type === 'utf8') { // accept only text
var actualMessageString = message.utf8Data;
if (userName === false) { // first message sent by user is their name
// remember user name
var testUserName = htmlEntities(message.utf8Data);
if (userNames.indexOf(testUserName.toLowerCase()) === -1) {
// it's a valid user name
userName = testUserName;
userNames.push(userName.toLowerCase());
// get random color and send it back to the user
userColor = colors.shift();
connection.sendUTF(JSON.stringify({
type : 'color',
data : userColor
}));
console.log((new Date()) + ' User is known as: ' + userName
+ ' with ' + userColor + ' color.');
} else {
// It's an invalid user name, ask user to select another one
connection.sendUTF(JSON.stringify({
type : 'username_error',
data : testUserName
}));
console.log((new Date()) + ' Username ' + testUserName + ' rejected');
}
} else if (actualMessageString.startsWith('mkgroup ')) {
var requestedRoomName = actualMessageString.split('mkgroup ')[1];
if (requestedRoomName && roomNames.indexOf(requestedRoomName.toLowerCase()) == -1) {
// it's a valid room name
roomNames.push(requestedRoomName.toLowerCase());
var roomObj = {
name: requestedRoomName,
history: [],
members: [connection]
};
rooms.push(roomObj);
connection.sendUTF(JSON.stringify({
type : 'room_created',
roomName : requestedRoomName,
data : []
}));
console.log((new Date()) + ' User ' + userName
+ ' created new room ' + requestedRoomName);
} else {
// else it's an invalid room
connection.sendUTF(JSON.stringify({
type : 'roomnamenotunique_error',
data : requestedRoomName
}));
console.log((new Date()) + ' New room ' + requestedRoomName
+ ' by ' + userName + ' rejected');
}
} else if (actualMessageString.startsWith('lvgroup ')) {
var requestedRoomName = actualMessageString.split('lvgroup ')[1];
if (requestedRoomName && roomNames.indexOf(requestedRoomName.toLowerCase()) != -1) {
// it's a valid room name
var roomIndex = -1;
for (i = 0; i < rooms.length; i++) {
if (rooms[i].name === requestedRoomName) {
rooms[i].members.splice(rooms[i].members.indexOf(connection), 1);
roomIndex = i;
break;
}
}
if (rooms[roomIndex].members.length < 1) {
roomNames.splice(roomNames.indexOf(requestedRoomName.toLowerCase()), 1);
}
connection.sendUTF(JSON.stringify({
type : 'room_left',
roomName : requestedRoomName,
data : []
}));
console.log((new Date()) + ' User ' + userName
+ ' left room ' + requestedRoomName);
} else {
// else it's an invalid room
connection.sendUTF(JSON.stringify({
type : 'roomnamenotfound_error',
data : requestedRoomName
}));
console.log((new Date()) + ' New room ' + requestedRoomName
+ ' by ' + userName + ' rejected');
}
} else if (actualMessageString.startsWith('jgroup ')) {
var requestedRoomName = actualMessageString.split('jgroup ')[1];
if (requestedRoomName && roomNames.indexOf(requestedRoomName.toLowerCase()) != -1) {
// it's a valid room name
var roomIndex = -1;
for (i = 0; i < rooms.length; i++) {
if (rooms[i].name === requestedRoomName) {
if (rooms[i].members.indexOf(connection) === -1) {
rooms[i].members.push(connection);
}
roomIndex = i;
break;
}
}
connection.sendUTF(JSON.stringify({
type : 'room_joined',
roomName : requestedRoomName,
data : rooms[roomIndex].history
}));
console.log((new Date()) + ' User ' + userName
+ ' joined room ' + requestedRoomName);
} else {
// else it's an invalid room
connection.sendUTF(JSON.stringify({
type : 'roomnamenotfound_error',
data : requestedRoomName
}));
console.log((new Date()) + ' Room join request for ' + requestedRoomName
+ ' by ' + testUserName + ' rejected');
}
} else { // log and broadcast the message
var roomForBroadcast = actualMessageString.split(/ (.+)?/)[0],
actualMessage = actualMessageString.split(/ (.+)?/)[1];
console.log((new Date()) + ' Received Message for ' + roomForBroadcast + ' from '
+ userName + ': ' + actualMessage);
// we want to keep history of all sent messages
var obj = {
time: (new Date()).getTime(),
text: htmlEntities(actualMessage),
author: userName,
color: userColor
};
var roomIndex = -1;
for (i = 0; i < rooms.length; i++) {
if (rooms[i].name === roomForBroadcast) {
rooms[i].history.push(obj);
//rooms[i].history.push(obj);
roomIndex = i;
break;
}
}
// broadcast message to all connected clients
var json = JSON.stringify({ type:'message', roomName: roomForBroadcast, data: obj });
for (var i=0; i < rooms[roomIndex].members.length; i++) {
rooms[roomIndex].members[i].sendUTF(json);
}
}
}
});
// user disconnected
connection.on('close', function(connection) {
if (userName !== false && userColor !== false) {
console.log((new Date()) + " Peer "
+ connection.remoteAddress + " disconnected.");
// remove user from the list of connected clients
clients.splice(index, 1);
// push back user's color to be reused by another user
colors.push(userColor);
}
});
});
<file_sep>
# ChatApp
A very simple multi-user multi-room chat application using JavaScript and Node.js
## Usage
Install Node.js
Run "node chat-app-server.js" on the terminal
Open /html/main.html in a browser
## Rules
You need to first set your name (which is globally unique)
You have to join a chat room in order to begin chatting
You will get the last 100 messages in any chat room
User state is not stored i.e. if you refresh the page, you start from scratch
## Commands
mkgroup <group name>: Creates a new group named <group name>
jgroup <group name>: Join the group named <group name>
lvgroup <group name>: Leave the group named <group name><file_sep># ChatApp
A simple multi-user multi-room chat application using Node.js and JavaScript
|
93b9727e319116294641af218dcf9788873c8053
|
[
"JavaScript",
"Markdown"
] | 4 |
JavaScript
|
yashtc/ChatApp
|
ecad29e368e820f4eb1a09c66ac2a3700a321756
|
80bc57153606f0f28694e4298c1d79c794d229a9
|
refs/heads/main
|
<repo_name>ice-world/Gomoku<file_sep>/README.md
# Gomoku
็ฎๅ็ไบๅญๆฃๆธธๆ
ๅผๅ็ฎ็ไป
ไธบๅฏน่ชๅทฑ่ฝๅ็่ฎญ็ป
ๆฐดๅนณไธ้ซ๏ผๅคๅคๅ
ๆถต
# ็ฏๅขไพ่ต
ๅบไบ20.08็ๆฌ็EGEๅพๅฝขๅบๅผๅ๏ผ่ฅ่ฆ็ผ่ฏๆบไปฃ็ ๏ผ่ฏทๅจEGEๅฎๆน็ฝ็ซไธ่ฝฝๅนถ้
็ฝฎEGEๅพๅฝขๅบ
https://xege.org/
# AIไธ็จๅบ็ไบคไบๆนๅผ
1.AI้ป่ฎคๆง็ฝ(ๅๆ)(้ๆฉๅ
ๅๆ็ๅ่ฝ้ข่ฎกๅจๅ็ปญ็ๆฌไธญๅขๅ )
2.็ฉๅฎถ่ฝๅญๅ๏ผไบคไบ็้ขๅฐ่ฐ็จๅฝๅ็ฎๅฝไธๅไธบ"GomokuAI.exe"็็จๅบ
3.ๅๆถ๏ผไธป็จๅบๅฐ็ๆไธไธชๆไปถ"chessboard.dat",ๅฐๆฃ็็้ข่พๅบ.็ฉบไฝไธบ0,็ฝๆฃไธบ1,้ปๆฃไธบ-1.
4."GomokuAI.exe"้่ฆๆ นๆฎๆฃ็ไฟกๆฏ,็ๆ"input.in"ๆไปถ,ไปฅ"x y"็ๆ ผๅผ,่พๅบ่ฝๅญ็น,็ถๅ็ปๆ็จๅบ.
5.ไธๆญๅพช็ฏ,ๅฎ็ฐไบบๆบๅฏนๆ.<file_sep>/Gomoku/Gomokubasic.h
#define SIZE 16 // ็ฑไบๅๅจ็็ฉบ ๆฃ็ๅฎ้
ๅคงๅฐไธบSIZE-2
#define WINDOW_HIGHT 640
#define WINDOW_WIDTH 640
#define BLACK -1
#define WHITE 1
int dir[8][2] = { {1,0},{1,1},{0,1},{-1,1},
{-1,0},{-1,-1},{0,-1},{1,-1} };<file_sep>/Gomoku/GomokuUI/GomokuUI.cpp
#include <graphics.h> //ๅ
ๅซEGE็ๅคดๆไปถ
#include <math.h>
#include<windows.h>
#include <stdio.h>
#include<Gomokubasic.h>
void Play();
void Init();
bool Click(int& x, int& y);
void AI_Click();
int Winning_check();
bool Winning_check_onedir(int t, int x, int y,int color);
void AI_input(int &x_i,int &y_i);
int chessboard[SIZE][SIZE];
int color = BLACK;
bool again = false;
FILE* fp;
int game_mode = 3;
double unit_width;
double unit_hight;
int main()
{
AGAIN:
Init();
Play();
if (again == true)
goto AGAIN;
closegraph();
return 0;
}
void Init()
{
memset(chessboard, 0, sizeof(chessboard));
initgraph(WINDOW_WIDTH, WINDOW_HIGHT); //ๅๅงๅๅพๅฝข็้ข
cleardevice();
setbkcolor(EGERGB(245, 222, 179));
setcaption("ไบๅญๆฃ");
fp = fopen("chessboard.dat", "w");
again = false;
unit_width = WINDOW_WIDTH / (SIZE);
unit_hight = WINDOW_HIGHT / (SIZE);
double start_x = unit_width;
double end_x = WINDOW_WIDTH - unit_width;
double start_y = unit_hight;
double end_y = WINDOW_HIGHT - unit_hight;
line((int)start_x, (int)start_y, (int)start_x, (int)end_y); //็ปๅถ่พนๆก
line((int)start_x, (int)start_y, (int)end_x, (int)start_y);
line((int)start_x, (int)end_y, (int)end_x, (int)end_y);
line((int)end_x, (int)start_y, (int)end_x, (int)end_y);
for (double i = start_x; i < end_x; i += unit_width) //็ปๅถ็ซ็บฟ
line((int)i, (int)start_y, (int)i, (int)end_y);
for (double i = start_y; i < end_y; i += unit_hight) //็ปๅถๆจช็บฟ
line((int)start_x, (int)i, (int)end_x, (int)i);
if (MessageBox(NULL, TEXT("AIๅฏนๆ๏ผๆฏ๏ผ่ฟๆฏๅฏนๆAI(ๅฆ)"), TEXT("ๆธธๆ้ๆฉ"), MB_SYSTEMMODAL | MB_YESNO) == IDYES)
game_mode = 3;
else
game_mode = 2;
color = BLACK;
}
void Play()
{
int x, y;
bool click = false;
for (; is_run(); delay_fps(60))
{
if (game_mode == 1) //PVP
{
Click(x, y);
Click(x, y);
int win_check = Winning_check();
if (win_check != 0)
{
Sleep(500);
if (win_check == 1)
MessageBox(NULL, TEXT("็ฝๆฃ่ท่"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL);
if (win_check == -1)
MessageBox(NULL, TEXT("้ปๆฃ่ท่"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL);
if (MessageBox(NULL, TEXT("ๆฏๅฆๅๆฅไธๅฑ"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL | MB_YESNO) == IDYES)
{
again = true;
return;
}
else
return;
}
}
if (game_mode == 2) //PVE
{
click = Click(x, y);
if (click)
{
AI_Click();
int win_check = Winning_check();
if (win_check != 0)
{
Sleep(500);
if (win_check == 1)
MessageBox(NULL, TEXT("็ฝๆฃ่ท่"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL);
if (win_check == -1)
MessageBox(NULL, TEXT("้ปๆฃ่ท่"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL);
if (MessageBox(NULL, TEXT("ๆฏๅฆๅๆฅไธๅฑ"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL | MB_YESNO) == IDYES)
{
again = true;
return;
}
else
return;
}
}
}
if (game_mode == 3)
{
AI_Click();
Sleep(100);
AI_Click();
Sleep(100);
int win_check = Winning_check();
if (win_check != 0)
{
Sleep(500);
if (win_check == 1)
MessageBox(NULL, TEXT("็ฝๆฃ่ท่"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL);
if (win_check == -1)
MessageBox(NULL, TEXT("้ปๆฃ่ท่"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL);
if (MessageBox(NULL, TEXT("ๆฏๅฆๅๆฅไธๅฑ"), TEXT("ๆธธๆ็ปๆ"), MB_SYSTEMMODAL | MB_YESNO) == IDYES)
{
again = true;
return;
}
else
return;
}
}
}
}
void AI_Click()
{
int x_i, y_i;
AI_input(x_i, y_i);
chessboard[x_i][y_i] = color; //ไธบไบๅจๆพ็คบไธๅฐๆฃๅญๆพ็คบ็ไฝ็ฝฎไบๆฐ็ปไธญ็ไฝ็ฝฎ็ธๅฏน๏ผๅฐxyไฝ็ฝฎๅฏนๆข
fillellipse((int)(y_i * unit_width), (int)(x_i * unit_hight), (int)(unit_width / 2), (int)(unit_hight / 2));
if (color == BLACK)
{
setfillcolor(EGERGB(255, 255, 255));
color = -color;
}
else if (color == WHITE)
{
setfillcolor(EGERGB(0, 0, 0));
color = -color;
}
return;
}
bool Click(int& x, int& y)
{
mouse_msg Mouse_msg = { 0 };
bool click = false;
click = false;
while (mousemsg())
{
Mouse_msg = getmouse();
if (Mouse_msg.is_left() && Mouse_msg.is_down())
{
click = true;
}
}
if (click == true)
{
click = false;
x = Mouse_msg.x;
y = Mouse_msg.y;
y = (int)round(y / unit_hight);
x = (int)round(x / unit_width);
if (chessboard[y][x] != 0)
{
MessageBox(NULL, TEXT("่ฏทๅจๆ็ฉบไฝ็ไฝ็ฝฎไธ่ฝๅญ"), TEXT(""), MB_SYSTEMMODAL| MB_ICONWARNING);
}
else if (x < 1 || x >= SIZE || y < 1 || y >= SIZE)
{
MessageBox(NULL, TEXT("่ฏทๅจๆฃ็ๅ
่ฝๅญ"), TEXT(""), MB_SYSTEMMODAL | MB_ICONWARNING);
}
else
{
chessboard[y][x] = color; //ไธบไบๅจๆพ็คบไธๅฐๆฃๅญๆพ็คบ็ไฝ็ฝฎไบๆฐ็ปไธญ็ไฝ็ฝฎ็ธๅฏน๏ผๅฐxyไฝ็ฝฎๅฏนๆข
fillellipse((int)(x * unit_width), (int)(y * unit_hight), (int)(unit_width / 2), (int)(unit_hight / 2));
if (color == BLACK)
{
setfillcolor(EGERGB(255, 255, 255));
color = -color;
}
else if (color == WHITE)
{
setfillcolor(EGERGB(0, 0, 0));
color = -color;
}
return true;
}
}
return false;
}
int Winning_check()
{
for (int t = 0; t < 8; t++)
{
for (int i = 1; i < SIZE; i++)
for (int j = 1; j < SIZE; j++)
{
if(chessboard[i][j]!=0)
if(Winning_check_onedir(t,i,j,chessboard[i][j]))
return chessboard[i][j];
}
}
return 0;
}
bool Winning_check_onedir(int d,int x,int y,int c)
{
for (int i = 1; i < 5; i++)
{
if (x + i * dir[d][0] >= SIZE || x + i * dir[d][0] < 1 || y + i * dir[d][1] >= SIZE || y + i * dir[d][1] < 1)
return false;
if (chessboard[x + i * dir[d][0]][y + i * dir[d][1]] != c)
return false;
}
return true;
}
void AI_input(int &x_i,int &y_i)
{
fp = fopen("chessboard.dat", "w");
for (int i = 1; i < SIZE; i++)
{
for (int j = 1; j < SIZE; j++)
fprintf(fp, "%d ", chessboard[i][j]);
fprintf(fp, "\n");
}
fclose(fp);
if(color == BLACK)
ShellExecute(NULL, TEXT("open"), TEXT("GomokuAIB.exe"), TEXT("BLACK"), TEXT(""), SW_HIDE);
else
ShellExecute(NULL, TEXT("open"), TEXT("GomokuAIW.exe"), TEXT("WHITE"), TEXT(""), SW_HIDE);
Sleep(200);
FILE* in;
in = fopen("input.in", "r");
fscanf(in, "%d%d", &x_i, &y_i);
fclose(in);
}<file_sep>/Gomoku/GomokuAI/GomokuAI.cpp
#include<stdio.h>
#include<string.h>
#include "Gomokubasic.h"
FILE* fp;
FILE* in;
FILE* test;
void init();
void input();
void Judge(int x,int y);
int num_count(int x, int y, int d, int color);
int chessboard[SIZE][SIZE];
int score[SIZE][SIZE];
int color = WHITE;
int main(int argc, char* argv[])
{
if (argv[0] == "BLACK")
color = BLACK;
else
color = WHITE;
init();
for (int i = 1; i < SIZE; i++)
for (int j = 1; j < SIZE; j++)
Judge(i,j);
input();
fclose(in);
fclose(test);
return 0;
}
void init()
{
fp = fopen("chessboard.dat", "r");
for (int i = 1; i < SIZE; i++)
{
for (int j = 1; j < SIZE; j++)
fscanf(fp, "%d", &chessboard[i][j]);
}
fclose(fp);
memset(score, -1, sizeof(score));
}
void input()
{
in = fopen("input.in", "w");
test = fopen("test.in", "w");
int x = 0, y = 1;
for (int i = 5; i < SIZE; i++)
{
for (int j = 5; j < SIZE; j++)
if (chessboard[i][j] == 0)
{
x = i;
y = j;
break;
}
if (x!=0)
break;
}
int max = 0;
for (int i = 1; i < SIZE; i++)
{
for (int j = 1; j < SIZE; j++)
{
if (score[i][j] > max)
{
x = i;
y = j;
max = score[i][j];
}
if (chessboard[i][j] == 0)
fprintf(test, "%5d", score[i][j]);
else
fprintf(test, " 5");
}
fprintf(test, "\n");
}
fprintf(in, "%d %d", x, y);
}
void Judge(int x,int y)
{
int n = 0;
if (chessboard[x][y] != 0)
{
score[x][y] = -1000;
return;
}
int my_score = 0;
int opp_score = 0;
int my[8] = {0};
int opp[8] = { 0 };
int f;//ๆต่ฏๅ้๏ผไธดๆถไฝฟ็จ
for (int i = 0; i < 4; i++)
{
my_score = num_count(x, y, i,color)+ num_count(x, y, i+4, color) ;
opp_score = num_count(x, y, i, -color)+ num_count(x, y, i + 4, -color);
f = my_score;
if (f >= 3)
score[x][y] += f*1000;
else
f = opp_score;
if (f >= 3)
score[x][y] += f*1000;
}
score[x][y] += (my_score + opp_score) * 10;
}
int num_count(int x, int y, int d, int color) //ๅบๅๆซๆ
{
int count = 0;
if (chessboard[x + dir[d][0]][y + dir[d][1]] == -color)
return 0;
for (int i = 1; i < 5; i++)
{
if (x + i * dir[d][0] >= SIZE || x + i * dir[d][0] < 1 || y + i * dir[d][1] >= SIZE || y + i * dir[d][1] < 1)
return count;
if (chessboard[x + i * dir[d][0]][y + i * dir[d][1]] == -color)
return -count;
else if(chessboard[x + i * dir[d][0]][y + i * dir[d][1]] == 0)
return count;
count++;
}
return count;
}
|
ccfd2d7b839d9df87054287f6f3884280266d52c
|
[
"Markdown",
"C",
"C++"
] | 4 |
Markdown
|
ice-world/Gomoku
|
7d4c53323ac7ae74db4d76c2f9da42790dbd1b14
|
da7ae354f6923104ae3fe085347bdcfb3b649d2e
|
refs/heads/master
|
<file_sep>๏ปฟusing UnityEngine;
using System.Collections;
public class PrezPhase : Phase
{
public override void BeginPhase ()
{
throw new System.NotImplementedException ();
}
}
<file_sep>๏ปฟusing UnityEngine;
using System.Collections;
public abstract class Phase
{
delegate void PhaseEnd();
PhaseEnd ePhaseEnd;
public abstract void BeginPhase ();
void EndPhase()
{
ePhaseEnd ();
}
}
|
90642958772ead42f64f06648b73d798a538d17f
|
[
"C#"
] | 2 |
C#
|
MrMesk/SuppaDaisuSaimuleitaaa
|
237e402a9f13c9296608f066ec75e5dbcbb1a211
|
bd656ee170cf169b62d3a1a7594e68b94354c0e8
|
refs/heads/main
|
<repo_name>shemuelx/TotiAngularexercicio02<file_sep>/src/app/personaje/personaje.component.ts
import { Component, OnInit } from '@angular/core';
import { BuscaService } from './busca.service';
@Component({
selector: 'app-personaje',
templateUrl: './personaje.component.html',
styleUrls: ['./personaje.component.css']
})
export class PersonajeComponent implements OnInit {
personajes: any = [];
constructor(buscaServ: BuscaService) {
buscaServ.getTodos()
.subscribe(
users => this.personajes = users)
}
ngOnInit(): void {
}
}
<file_sep>/src/app/personaje/busca.service.ts
import { getLocaleExtraDayPeriods } from '@angular/common';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Url } from 'url';
const JASONURL: string = 'https://jsonplaceholder.typicode.com/users';
@Injectable({
providedIn: 'root'
})
export class BuscaService {
personajes: any = [];
constructor(private http: HttpClient) { }
getTodos() { return this.http.get(JASONURL) }
}
|
e2f43bbd4c660372f7c35addf1b835385541dbbf
|
[
"TypeScript"
] | 2 |
TypeScript
|
shemuelx/TotiAngularexercicio02
|
dbe8cd8d91492690c8dc32000c851faa253e48ef
|
58a0eefe151df470abf56767aaa8244d9f94505b
|
refs/heads/master
|
<file_sep># ไธๅญ้ฟๆๆต
ๆๅพฎๆๅกRibbon่ด่ฝฝๅ่กกๆบ็
# ๅ่จ
## ็ๆฌ
> ไฝ่
๏ผ้ฉๆฐ
>
> Github๏ผhttps://github.com/hanshuaikang
>
> ๅฎๆๆฅๆ๏ผ2019-06-16ๆฅ
>
> jdk๏ผ1.8
>
> springboot็ๆฌ๏ผ2.1.3.RELEASE
>
> SpringCould็ๆฌ๏ผGreenwich.SR1
## ๅฃฐๆ๏ผ
่บซไธบไธไธชๅๅ
ฅ้จ็่ฎก็ฎๆบ่ไฝฌ๏ผ้
่ฏปๆบ็ ่ช็ถ็ฆปไธๅผไผ็งๅ่ไนฆ็ฑๅ่ง้ข็ๅผๅฏผ๏ผๆฌ็ฏๆ็ซ ็ๅๆ่ฟ็จไธญ"ไธฅ้"ๅ้ดไบ **็ฟๆฐธ่ถ
** ๅ่พ็ใSpringCloudๅพฎๆๅกๅฎๆใ่ฟๆฌไนฆ็ฑ๏ผๅจ่ฟ้ไนๅๅๅคๅญฆไน ๅพฎๆๅก็ๅฐไผไผดไปฌๅผบ็ๆจ่่ฟๆฌไนฆ๏ผๅคงๅฎถๅฏไปฅๆ่ฟ็ฏๆ็ซ ็่งฃไธบใSpringCloudๅพฎๆๅกๅฎๆใRibbon้จๅ็็ฒพ็ฎ็ๅ็ตๅญ็๏ผๅ ไธบไธชไบบๆฐดๅนณ็ๅๅ ๏ผๅพๅค้ฎ้ขไธๆขๅฆไธๅฎ่ฎบ๏ผไปฅๅ
่ฏฏไบบๅญๅผ๏ผๆๆไนฆไธๅพๅคๅ
ๅฎน้ฝๆฏ็ฒพ็ฎ่ฟๅ็ดๆฅๆพไธๅป็๏ผ็ฑไบSpringCloudๅทฒ็ป่ฟญไปฃๅฐไบGreenwich.SR1็ๆฌ๏ผRibbonไนๅไนฆไธๆไบ็ฅๅพฎ็ๅทฎๅซ๏ผๆฌ็ฏๆ็ซ ็ๆบ็ ้็จ็ๆฏRibbonๆๆฐ็ๆฌ๏ผๅๆถ๏ผๅ ไธบๆถ้ดๅๅ ๏ผๆๅพๅค้ขๅค็ๅญ็ฑปๅฎ็ฐๅนถๆฒกๆๅฎๅ
จ้กพไธ๏ผไพๅฆPredicateBasedRule็ฑป็ZoneAvoidanceRuleๅAvailabilityFilteringRule ๆๅ
ด่ถฃ็่ฏป่
ๅฏไปฅไนฐใSpringCloudๅพฎๆๅกๅฎๆใ่ฟๆฌไนฆ็ป็๏ผๅๆถๅผบ็ๆจ่ๅฐ้ฉฌๅฅ็ๅพฎๆๅก็ดๆญ่ฏพ็ณปๅใๅฐ้ฉฌๅฅๅพฎๆๅกๅฎๆใใ
## ่ด่ฐข
**็ฟๆฐธ่ถ
**๏ผๅๅฎขๅฐๅ๏ผ
http://blog.didispace.com/aboutme/
**ๅฐ้ฉฌๅฅ๏ผ Java ๅพฎๆๅกๅฎ่ทต - Spring Boot / Spring Cloud่ดญไนฐ้พๆฅ๏ผ**
https://segmentfault.com/ls/1650000011387052
## ็ตๅญ็ๅ็ธๅ
ณไปฃ็ ไธ่ฝฝ๏ผๆฌข่ฟStar๏ผ
Github๏ผhttps://github.com/hanshuaikang/Spring-Note
ๅพฎไฟกๅ
ฌไผๅท๏ผ็ ไธmarson
# ๅฟซ้ไธๆ๏ผ
## ้
็ฝฎ่ด่ฝฝๅ่กก
ๅฝไฝฟ็จEurekaๆถ๏ผ้กปๅๅฆไธ้
็ฝฎ
```properties
## ๆๅกๆไพๆน
spring.application.name = spring-cloud-ribbon-client
### ๆๅก็ซฏๅฃ
server.port = 8080
### ็ฎก็ๅฎๅ
จๅคฑๆ
management.endpoints.web.exposure.include=*
### ๆๆถๆงๅ
ณ้ญ Eureka ๆณจๅ
## ๅฝไฝฟ็จ Eureka ๆๅกๅ็ฐๆถ๏ผ่ฏทๆณจ้ๆไธไธ้
็ฝฎ
# eureka.client.enabled = false
## ่ฟๆฅ Eureka Sever
eureka.client.serviceUrl.defaultZone = http://localhost:10000/eureka/
eureka.client.registryFetchIntervalSeconds = 5
### ๆๅกๆไพๆนไธปๆบ
serivce-provider.host = localhost
### ๆๅกๆไพๆน็ซฏๅฃ
serivce-provider.port = 9090
serivce-provider.name = spring-cloud-service-provider
```
ๅฝไธ้็จEureka็ๆถๅ๏ผ้่ฆ้
็ฝฎๅฆไธ
```properties
### ้
็ฝฎribbon ๆๅกๅฐๆไพๆน
## ๅฝไฝฟ็จ Eureka ๆๅกๅ็ฐๆถ๏ผ่ฏทๆณจ้ๆไธไธ้
็ฝฎ
# spring-cloud-service-provider.ribbon.listOfServers = \
#http://${serivce-provider.host}:${serivce-provider.port}
```
## ๆฟๆดป่ด่ฝฝๅ่กก
```java
@SpringBootApplication
@RibbonClients({
@RibbonClient(name = "spring-cloud-service-provider")
})
@EnableDiscoveryClient
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
//ๅฃฐๆ RestTemplate
@LoadBalanced // RestTemplate ็่กไธบๅๅ
@Bean
public RestTemplate restTemplate(){
return new RestTemplate();
}
}
```
## ๆต่ฏๅ้่ฏทๆฑ
```java
return restTemplate.postForObject("http://" +
serviceProviderName +
"/greeting",
user, String.class);
```
# ๅๆขRibbonๆบ็
## LoadBalancerClient ็ฑป
ๅจSpring ไธญ ๏ผๅฝๆๅกๆถ่ดน็ซฏๅป่ฐ็จๆๅกๆไพ่
็ๆๅก็ๆถๅ๏ผๅทฒ็ปๅฐ่ฃ
ไบไธไธชๆจกๆฟ็ฑป๏ผๅซๅRestTemplate.้ฃไนRibbon ๅๆฏๅฆไฝ้่ฟRestTemplateๆฅๅฎ็ฐ่ด่ฝฝๅ่กก็ๅข๏ผ
**็บฟ็ดข**๏ผ **@LoadBalanced** ๆณจ่งฃ:
```java
# Annotation to mark a RestTemplate bean to be configured to use a LoadBalancerClient.
ๆณจ้๏ผ็จไบๆ ่ฎฐ่ฆ้
็ฝฎไธบไฝฟ็จLoadBalancerClient็RestTemplate beanใ
```
### ServiceInstanceChooserๆฅๅฃ
```java
public interface ServiceInstanceChooser {
/**
* ไปLoadBalancerไธญไธบๆๅฎ็ๆๅก้ๆฉไธไธชServiceInstanceใ
* @param serviceIdๆฏๆฅๆพLoadBalancer็ๆๅกIDใ
* @return ไธไธชไธserviceIdๅน้
็ServiceInstanceใ
*/
ServiceInstance choose(String serviceId);
}
```
**ServiceInstance choose(String serviceId)** ๏ผๆ นๆฎserviceId ๅป้ๆฉไธไธชๅฏนๅบๆๅก็ๅฎไพ
### **LoadBalancerClient** **็ฑป**๏ผ
LoadBalancerClient ไปฃ็ ๏ผ
```java
package org.springframework.cloud.client.loadbalancer;
import java.io.IOException;
import java.net.URI;
import org.springframework.cloud.client.ServiceInstance;
public interface LoadBalancerClient extends ServiceInstanceChooser {
<T> T execute(String serviceId, LoadBalancerRequest<T> request) throws IOException;
<T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request) throws IOException;
URI reconstructURI(ServiceInstance instance, URI original);
}
```
**<T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request)**
ไฝฟ็จๆๅฎ็LoadBalancerไธญ็ServiceInstanceๆง่ก่ฏทๆฑ
**serviceInstance ** ๏ผ ่ฆๆง่ก่ฏทๆฑ็ๆๅก
**<T> T execute(String serviceId, LoadBalancerRequest<T> request)** :
ไฝฟ็จไป่ด่ฝฝๅ่กกๅจไธญๆ้ๅบๆฅ็ๆๅกๅฎไพๆฅๆง่ก่ฏทๆฑๅ
ๅฎนใ
**URI reconstructURI(ServiceInstance instance, URI original);**
่ฟๅไธไธช ไธ ไธช host:port ๅฝขๅผ็URLๅฏน่ฑก็จไบๆไปฌๆๅๅๆๅก็ซฏๅ้่ฏทๆฑ็ๅฐๅใ่ๅ
ทไฝ็host,port็ญไฟกๆฏ
ๅไป instanceๅๆฐไธญ่ทๅใ
### ServiceInstance ็ฑป
```java
public interface ServiceInstance {
default String getInstanceId() {
return null;
}
String getServiceId();
String getHost();
int getPort();
boolean isSecure();
URI getUri();
Map<String, String> getMetadata();
default String getScheme() {
return null;
}
}
```
## LoadBalancerAutoConfiguration็ฑป
ไฝ็จ๏ผRibbon ็่ชๅจๅ้
็ฝฎ็ฑปไปฃ็ ๏ผ้จๅ๏ผ๏ผ
```java
@Configuration
@ConditionalOnClass({RestTemplate.class})
@ConditionalOnBean({LoadBalancerClient.class})
@EnableConfigurationProperties({LoadBalancerRetryProperties.class})
public class LoadBalancerAutoConfiguration {
@LoadBalanced
@Autowired(
required = false
)
private List<RestTemplate> restTemplates = Collections.emptyList();
@Autowired(
required = false
)
private List<LoadBalancerRequestTransformer> transformers = Collections.emptyList();
public LoadBalancerAutoConfiguration() {
}
@Bean
public SmartInitializingSingleton loadBalancedRestTemplateInitializerDeprecated(final ObjectProvider<List<RestTemplateCustomizer>> restTemplateCustomizers) {
return () -> {
restTemplateCustomizers.ifAvailable((customizers) -> {
Iterator var2 = this.restTemplates.iterator();
while(var2.hasNext()) {
RestTemplate restTemplate = (RestTemplate)var2.next();
Iterator var4 = customizers.iterator();
while(var4.hasNext()) {
RestTemplateCustomizer cutomizer = (RestTemplateCustomizer)var4.next();
customizer.customize(restTemplate);
}
}
});
};
}
#ไธญ้ดไธๅคงๆฎตไปฃ็ ็ฅ
@Bean
public LoadBalancerInterceptor ribbonInterceptor(LoadBalancerClient loadBalancerClient, LoadBalancerRequestFactory requestFactory) {
return new LoadBalancerInterceptor(loadBalancerClient, requestFactory);
}
@Bean
@ConditionalOnMissingBean
public RestTemplateCustomizer restTemplateCustomizer(final LoadBalancerInterceptor loadBalancerInterceptor) {
return (restTemplate) -> {
List<ClientHttpRequestInterceptor> list = new ArrayList(restTemplate.getInterceptors());
list.add(loadBalancerInterceptor);
restTemplate.setInterceptors(list);
};
}
}
}
```
**@ConditionalOnClass({RestTemplate.class})** ๏ผ RestTemplateๅฟ
้กปไฝไบๅฝๅ็ๅทฅ็จ็ฏๅขไธญ
**@ConditionalOnBean({LoadBalancerClient.class})** ๏ผๅทฅ็จไธญๅฟ
้กปๅญๅจๅฎ็ฐLoadBalancerClient็**Bean**
```java
@LoadBalanced
@Autowired(
required = false
)
private List<RestTemplate> restTemplates = Collections.emptyList();
```
**private List<RestTemplate> restTemplates = Collections.emptyList();**
็ปดๆคไธไธช่ขซ@LoadBalanced็ไฟฎ้ฅฐ็RestTemplateๅฎไพๅ่กจใ
```java
@Bean
public LoadBalancerInterceptor ribbonInterceptor(LoadBalancerClient loadBalancerClient, LoadBalancerRequestFactory requestFactory) {
return new LoadBalancerInterceptor(loadBalancerClient, requestFactory);
}
```
ๅๅปบไธไธชๆฆๆชๅจ LoadBalancerInterceptor๏ผ็จไบๅจๅ่ตท่ฏทๆฑ็ๆถๅ่ฟ่กๆฆๆชใ
```java
@Bean
@ConditionalOnMissingBean
public RestTemplateCustomizer restTemplateCustomizer(final LoadBalancerInterceptor loadBalancerInterceptor) {
return (restTemplate) -> {
List<ClientHttpRequestInterceptor> list = new ArrayList(restTemplate.getInterceptors());
list.add(loadBalancerInterceptor);
restTemplate.setInterceptors(list);
};
}
}
}
```
ไธบRestTemplateๅฎไพๅ่กจ็่ฏทๆฑrestTemplateๆทปๅ ไธไธชLoadBalancerInterceptorๆฆๆชๅจใ
## LoadBalancerInterceptor ็ฑป
ไฝ็จ:ๆฆๆชRestTemplate่ฏทๆฑ๏ผๅฎ็ฐ่ด่ฝฝๅ่กก
```java
public class LoadBalancerInterceptor implements ClientHttpRequestInterceptor {
private LoadBalancerClient loadBalancer;
private LoadBalancerRequestFactory requestFactory;
public LoadBalancerInterceptor(LoadBalancerClient loadBalancer,
LoadBalancerRequestFactory requestFactory) {
this.loadBalancer = loadBalancer;
this.requestFactory = requestFactory;
}
public LoadBalancerInterceptor(LoadBalancerClient loadBalancer) {
// for backwards compatibility
this(loadBalancer, new LoadBalancerRequestFactory(loadBalancer));
}
@Override
public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
final ClientHttpRequestExecution execution) throws IOException {
final URI originalUri = request.getURI();
String serviceName = originalUri.getHost();
Assert.state(serviceName != null,
"Request URI does not contain a valid hostname: " + originalUri);
return this.loadBalancer.execute(serviceName,
this.requestFactory.createRequest(request, body, execution));
}
}
```
#ๅฝไธไธช่ขซ@LoadBalancedไฟฎ้ฅฐ่ฟ็RestTemplateๅฏน่ฑกๅ้่ฏทๆฑๆถ๏ผไผ่ขซ LoadBalancerInterceptorๆฆๆช๏ผ้่ฟrequestๆฟๅฐURL๏ผ้่ฟURLๆฟๅฐๆๅกๅ๏ผๆๅๅ้ๆฉๅฏนๅบ็ๅฎไพๅ่ตท่ฏทๆฑใ
## RibbonLoadBalancerClient ็ฑป
ไฝ็จ:LoadBalancerClient ๆฅๅฃ็ๅ
ทไฝๅฎ็ฐ
```java
public class RibbonLoadBalancerClient implements LoadBalancerClient {
private SpringClientFactory clientFactory;
@Override
public <T> T execute(String serviceId, LoadBalancerRequest<T> request)
throws IOException {
return execute(serviceId, request, null);
}
public <T> T execute(String serviceId, LoadBalancerRequest<T> request, Object hint)
throws IOException {
ILoadBalancer loadBalancer = getLoadBalancer(serviceId);
Server server = getServer(loadBalancer, hint);
if (server == null) {
throw new IllegalStateException("No instances available for " + serviceId);
}
RibbonServer ribbonServer = new RibbonServer(serviceId, server,
isSecure(server, serviceId),
serverIntrospector(serviceId).getMetadata(server));
return execute(serviceId, ribbonServer, request);
}
public <T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request) throws IOException {
Server server = null;
if (serviceInstance instanceof RibbonLoadBalancerClient.RibbonServer) {
server = ((RibbonLoadBalancerClient.RibbonServer)serviceInstance).getServer();
}
if (server == null) {
throw new IllegalStateException("No instances available for " + serviceId);
} else {
RibbonLoadBalancerContext context = this.clientFactory.getLoadBalancerContext(serviceId);
RibbonStatsRecorder statsRecorder = new RibbonStatsRecorder(context, server);
try {
T returnVal = request.apply(serviceInstance);
statsRecorder.recordStats(returnVal);
return returnVal;
} catch (IOException var8) {
statsRecorder.recordStats(var8);
throw var8;
} catch (Exception var9) {
statsRecorder.recordStats(var9);
ReflectionUtils.rethrowRuntimeException(var9);
return null;
}
}
}
protected Server getServer(ILoadBalancer loadBalancer) {
return this.getServer(loadBalancer, (Object)null);
}
protected Server getServer(ILoadBalancer loadBalancer, Object hint) {
return loadBalancer == null ? null : loadBalancer.chooseServer(hint != null ? hint : "default");
}
}
```
ๆณจ:
> ๅฐๆญคๅคไปฃ็ ๅSpringCloudๅพฎๆๅกๅฎๆไนฆไธญ็ๆฌ็ๆบ็ ๅทฒ็ปๆไบไบ่ฎธไธๅ๏ผๅฎ็ฐไธๆดๅ ้ซๆไบใ
้ฆๅ
้่ฟ้ป่ฎค็executeๅฎ็ฐๅฐๅๆฐไผ ้ๅฐ็ฌฌไบไธช
**public <T> T execute(String serviceId, LoadBalancerRequest<T> request, Object hint)**
ๅจ็ฌฌไบไธชๆนๆณๆไปฌๅ็ฐๆ นๆฎserviceId่ทๅไบๅฏนๅบ็ๆๅกๅฎไพ๏ผๅนถไธๅฐ่ฃ
ๅฐไบRibbonServerๅฏน่ฑกไธญใ
ๆ็ปไบคไปๅฐ็ฌฌไธไธชๆนๆณ
**public <T> T execute(String serviceId, ServiceInstance serviceInstance, LoadBalancerRequest<T> request)**
ๅฎๆๅ
ทไฝ็ๆง่กๆไฝใ
ๅๆถๅฏไปฅๅ็ฐgetServer็ๅๆฐๅนถไธๆฏๆ นๆฎไนๅ็LoadBalancerClient็chooseๆนๆณ๏ผ่ๆฏไฝฟ็จไบRibbonๆฌ่บซILoadBalancerๆฅๅฃๅฎไน็ๅฝๆฐใ
```java
protected Server getServer(ILoadBalancer loadBalancer, Object hint) {
if (loadBalancer == null) {
return null;
}
// Use 'default' on a null hint, or just pass it on?
return loadBalancer.chooseServer(hint != null ? hint : "default");
}
```
**ไธๆข็ฉถ็ซ:**
## ILoadBalancer : ๆฅๅฃ
```java
public interface ILoadBalancer {
//ๅ่ด่ฝฝๅ่กกๅจไธญ็ปดๆค็ๆๅกๅ่กจไธญๆทปๅ ๆฐ็ๆๅกๅฎไพ
public void addServers(List<Server> newServers);
//้่ฟๆ็ง็ญ็ฅ๏ผ้ๆฉไธไธชๆๅกๅฎไพ
public Server chooseServer(Object key);
//็จๆฅๆ ่ฏๆไธชๆๅกๅทฒ็ปๅๆญขๆๅก
public void markServerDown(Server server);
//่ทๅๅฝๅๆๅกๅจๅ่กจใๅฆๆavailableOnlyไธบtrue็่ฏ๏ผๅฐไผ่ฟๅๆดป่ท็ๆๅกๅ่กจ
@Deprecated
public List<Server> getServerList(boolean availableOnly);
//ๅช่ฟๅๆญฃๅจๅฏๅจ็ๅฏ่ฟๅ็ๆๅกๅ่กจ
public List<Server> getReachableServers();
//่ฟๅๆๆๅทฒ็ฅ็ๆๅกๅ่กจ
public List<Server> getAllServers();
}
```
้่ฟๆฅ็ILoadBalancer ็ๅ
ทไฝๅฎ็ฐๅพ็ฅ
ILoadBalancer -> **BaseLoadBalancer**(ๅบ็กๅฎ็ฐ) ->**DynamicServerListLoadBalancer**๏ผๆฉๅฑๅฎ็ฐ๏ผ
->**ZoneAwareLoadBalancer**(ๆฉๅฑๅฎ็ฐ)
้ฃRibbon้ป่ฎคไฝฟ็จ็ๅช็งๅฎ็ฐๅข๏ผ
```java
@Configuration
@EnableConfigurationProperties
// Order is important here, last should be the default, first should be optional
// see
// https://github.com/spring-cloud/spring-cloud-netflix/issues/2086#issuecomment-316281653
@Import({ HttpClientConfiguration.class, OkHttpRibbonConfiguration.class,
RestClientRibbonConfiguration.class, HttpClientRibbonConfiguration.class })
public class RibbonClientConfiguration {
@Bean
@ConditionalOnMissingBean
public ILoadBalancer ribbonLoadBalancer(IClientConfig config,
ServerList<Server> serverList, ServerListFilter<Server> serverListFilter,
IRule rule, IPing ping, ServerListUpdater serverListUpdater) {
if (this.propertiesFactory.isSet(ILoadBalancer.class, name)) {
return this.propertiesFactory.get(ILoadBalancer.class, config, name);
}
return new ZoneAwareLoadBalancer<>(config, rule, ping, serverList,
serverListFilter, serverListUpdater);
}
}
```
้่ฟๆฅ็Ribbon็้
็ฝฎ็ฑป๏ผๆไปฌๅ็ฐRibbon้ป่ฎค้็จ็ๆฏZoneAwareLoadBalancerๅฎ็ฐ
็ฐๅจๅๅฐๅ
ทไฝ็RibbonLoadBalancerClient ็ฑป็executeๆนๆณไธญ๏ผๅฏไปฅๅคงๆฆ็ฅ้Ribbon่ด่ฝฝๅ่กก็ไธไธช็ฎๅ็ๆต็จ๏ผๅณ
getServerๆนๆณ**->**ZoneAwareLoadBalancer็chooseServerๆนๆณ่ทๅไธไธชๅ
ทไฝ็ๆๅกๅฎไพ
->ๅ
่ฃ
ๆไธไธชRibbonServerๅฏน่ฑก
->LoadBalancerRequest็applyๅไธไธชๅ
ทไฝ็ๅฎไพๅ้ไธไธช่ฏทๆฑใ
## ServiceInstance ๆฅๅฃ
```java
public interface ServiceInstance {
default String getInstanceId() {
return null;
}
String getServiceId();
String getHost();
int getPort();
boolean isSecure();
URI getUri();
Map<String, String> getMetadata();
default String getScheme() {
return null;
}
}
```
## ServiceInstance ็ๅ
ทไฝๅฎ็ฐRibbonServer็ฑป
ๅ
ๅซไบserverๅฏน่ฑก๏ผๆๅกๅ๏ผๆฏๅฆไฝฟ็จhttps็ญๆ ่ฏใ
```java
public static class RibbonServer implements ServiceInstance {
private final String serviceId;
private final Server server;
private final boolean secure;
private Map<String, String> metadata;
public RibbonServer(String serviceId, Server server) {
this(serviceId, server, false, Collections.emptyMap());
}
public RibbonServer(String serviceId, Server server, boolean secure,
Map<String, String> metadata) {
this.serviceId = serviceId;
this.server = server;
this.secure = secure;
this.metadata = metadata;
}
@Override
public String getInstanceId() {
return this.server.getId();
}
@Override
public String getServiceId() {
return this.serviceId;
}
@Override
public String getHost() {
return this.server.getHost();
}
@Override
public int getPort() {
return this.server.getPort();
}
@Override
public boolean isSecure() {
return this.secure;
}
@Override
public URI getUri() {
return DefaultServiceInstance.getUri(this);
}
@Override
public Map<String, String> getMetadata() {
return this.metadata;
}
public Server getServer() {
return this.server;
}
@Override
public String getScheme() {
return this.server.getScheme();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("RibbonServer{");
sb.append("serviceId='").append(serviceId).append('\'');
sb.append(", server=").append(server);
sb.append(", secure=").append(secure);
sb.append(", metadata=").append(metadata);
sb.append('}');
return sb.toString();
}
}
}
```
ๆๆ่ทฏๅๅฐLoadBalancerClientๆฅๅฃ็applyๆนๆณไธ๏ผ็ถๅ็ช็ถๅ็ฐ๏ผไนๅSpringCloudๅพฎๆๅกไนฆไธ็ๅฎ็ฐๆฉๅทฒไธๅ๏ผ้่ฟๆฅ็ๆฅๅฃ็ๅฎ็ฐๅ
ณ็ณป๏ผๅ็ฐๆ็ปapplyๆนๆณๆฏ AsyncLoadBalancerInterceptor็ฑปๆฅๅฎๆๅ
ทไฝ็ๅฎ็ฐ็ใ
## AsyncLoadBalancerInterceptor็ฑป
```java
public class AsyncLoadBalancerInterceptor implements AsyncClientHttpRequestInterceptor {
private LoadBalancerClient loadBalancer;
public AsyncLoadBalancerInterceptor(LoadBalancerClient loadBalancer) {
this.loadBalancer = loadBalancer;
}
public ListenableFuture<ClientHttpResponse> intercept(final HttpRequest request, final byte[] body, final AsyncClientHttpRequestExecution execution) throws IOException {
URI originalUri = request.getURI();
String serviceName = originalUri.getHost();
return (ListenableFuture)this.loadBalancer.execute(serviceName, new LoadBalancerRequest<ListenableFuture<ClientHttpResponse>>() {
public ListenableFuture<ClientHttpResponse> apply(final ServiceInstance instance) throws Exception {
HttpRequest serviceRequest = new ServiceRequestWrapper(request, instance, AsyncLoadBalancerInterceptor.this.loadBalancer);
return execution.executeAsync(serviceRequest, body);
}
});
}
}
```
็ฑไบๅฎๆนไปฃ็ ๅนถๆฒกๆๆไพๆณจ้่ฏดๆ่ฟไธช็ฑป็ๅ
ทไฝไฝ็จ๏ผ้่ฟ็ฑปๅ็งฐๅคงๆฆๅฏไปฅ็ๅบไธบไธไธชๅผๆญฅ็่ด่ฝฝๅ่กกๆฆๆชๅจ๏ผๆฆๆชRestplate่ฏทๆฑ๏ผๅนถๅฎ็ฐapplyๆนๆณๅไธไธชๅ
ทไฝ็ๅฎไพๅ้่ฏทๆฑใ
ๅ
ทไฝๆง่ก็ไปฃ็
```java
HttpRequest serviceRequest = new ServiceRequestWrapper(request,
instance, AsyncLoadBalancerInterceptor.this.loadBalancer);
return execution.executeAsync(serviceRequest, body);
```
ๅ็ฐๅ
ทไฝๅฎ็ฐ็ๆถๅ๏ผ่ฟไผ ๅ
ฅไบไธไธชServiceRequestWrapperๅฏน่ฑกใ
## ServiceRequestWrapper็ฑป
```java
public class ServiceRequestWrapper extends HttpRequestWrapper {
private final ServiceInstance instance;
private final LoadBalancerClient loadBalancer;
public ServiceRequestWrapper(HttpRequest request, ServiceInstance instance,
LoadBalancerClient loadBalancer) {
super(request);
this.instance = instance;
this.loadBalancer = loadBalancer;
}
@Override
public URI getURI() {
URI uri = this.loadBalancer.reconstructURI(this.instance, getRequest().getURI());
return uri;
}
```
ๅฏไปฅๅ็ฐ่ฟไธช็ฑป็ปงๆฟไบHttpRequestWrapper ็ฑป๏ผๅนถไธ้ๅไบgetURI()ๆนๆณ๏ผๅๆถๅจ getURI() ๆนๆณไธญ๏ผๅ
ทไฝ้็บณไบRibbonLoadBalancerClient ็reconstructURIๆนๆณๆฅ็ป็ปๅ
ทไฝ่ฏทๆฑ็URLๅฎไพๅฐๅใ
```java
@Override
public URI reconstructURI(ServiceInstance instance, URI original) {
Assert.notNull(instance, "instance can not be null");
String serviceId = instance.getServiceId();
RibbonLoadBalancerContext context = this.clientFactory
.getLoadBalancerContext(serviceId);
URI uri;
Server server;
if (instance instanceof RibbonServer) {
RibbonServer ribbonServer = (RibbonServer) instance;
server = ribbonServer.getServer();
uri = updateToSecureConnectionIfNeeded(original, ribbonServer);
}
else {
server = new Server(instance.getScheme(), instance.getHost(),
instance.getPort());
IClientConfig clientConfig = clientFactory.getClientConfig(serviceId);
ServerIntrospector serverIntrospector = serverIntrospector(serviceId);
uri = updateToSecureConnectionIfNeeded(original, clientConfig,
serverIntrospector, server);
}
return context.reconstructURIWithServer(server, uri);
}
```
่ๅจ**reconstructURIWithServer**ๆนๆณไธญ๏ผๆไปฌๅฏไปฅๅ็ฐ่ฟๆ ทไธไธชๆง่ก้ป่พ๏ผ้ฆๅ
ไปServerๅฏน่ฑกไธญ่ทๅพHostๅportไฟกๆฏ๏ผ็ถๅไปURI originalๅฏน่ฑกไธญ๏ผ่ทๅๅ
ถไป็่ฏทๆฑไฟกๆฏ๏ผๆ็ปๆผๆฅๆ่ฆ่ฎฟ้ฎ็ๅ
ทไฝ็ๅฎไพๅฐๅใ
```java
public URI reconstructURIWithServer(Server server, URI original) {
String host = server.getHost();
int port = server.getPort();
String scheme = server.getScheme();
if (host.equals(original.getHost())
&& port == original.getPort()
&& scheme == original.getScheme()) {
return original;
}
if (scheme == null) {
scheme = original.getScheme();
}
if (scheme == null) {
scheme = deriveSchemeAndPortFromPartialUri(original).first();
}
try {
StringBuilder sb = new StringBuilder();
sb.append(scheme).append("://");
if (!Strings.isNullOrEmpty(original.getRawUserInfo())) {
sb.append(original.getRawUserInfo()).append("@");
}
sb.append(host);
if (port >= 0) {
sb.append(":").append(port);
}
sb.append(original.getRawPath());
if (!Strings.isNullOrEmpty(original.getRawQuery())) {
sb.append("?").append(original.getRawQuery());
}
if (!Strings.isNullOrEmpty(original.getRawFragment())) {
sb.append("#").append(original.getRawFragment());
}
URI newURI = new URI(sb.toString());
return newURI;
} catch (URISyntaxException e) {
throw new RuntimeException(e);
}
}
```
# ่ด่ฝฝๅ่กกๅจ
## AbstractLoadBalancer ็ฑป
```java
import java.util.List;
public abstract class AbstractLoadBalancer implements ILoadBalancer {
//ไธไธชๅ
ณไบๆๅกๅฎไพ็ๅ็ปๆไธพ็ฑป๏ผๅฎไนไบไธ็งไธๅ็็บงๅซ
public enum ServerGroup{
ALL,
STATUS_UP,
STATUS_NOT_UP
}
/**
* ้ๆฉไธไธชๆๅกๅฎไพ๏ผkeyไธบnull๏ผๅฟฝ็ฅkey็ๆกไปถๅคๆญ
*/
public Server chooseServer() {
return chooseServer(null);
}
/**
* ๆ นๆฎไธๅ็ๅ็ป็ฑปๅๆฅ้ๆฉ่ฟๅไธๅ็ๆๅกๅฎไพ็ๅ่กจ
*/
public abstract List<Server> getServerList(ServerGroup serverGroup);
/**
* ่ทๅไธ่ด่ฝฝๅ่กกๅจ็ธๅ
ณ็็ป่ฎกไฟกๆฏ
*/
public abstract LoadBalancerStats getLoadBalancerStats();
}
```
AbstractLoadBalancerๆฏ ILoadBalancer็ไธไธชๆฝ่ฑกๅฎ็ฐ๏ผๅๆถไน็ปดๆคไบไธไธชๅ
ณไบๆๅกๅฎไพ็ๅ็ปๆไธพ็ฑป๏ผServerGroup ๅๆถๅข๏ผๅฎไนไบไธ็ง็ฑปๅ๏ผ็จๆฅ้ๅฏนไธๅ็ๆ
ๅตใ
- **ALL** ๏ผๆๆๆๅกๅฎไพ
- **STATUS_UP** ๏ผๆญฃๅธธๆๅก็ๅฎไพ
- **STATUS_NOT_UP** ๏ผๅๆญขๆๅก็ๅฎไพ
## BaseLoadBalancer็ฑป
ไฝ็จ๏ผ่ด่ฝฝๅ่กก็ๅบ็ก่ด่ฝฝๅ่กกๅจ๏ผๅฎไนไบๅพๅค่ด่ฝฝๅ่กกๅจ็ๅบๆฌๅ
ๅฎน
ๆฅไธๆฅ็BaseLoadBalancer้ๅฏน่ด่ฝฝๅ่กก้ฝๅไบๅชไบๅทฅไฝๅข๏ผ
- ็ปดๆคไบไธคไธชๆๅกๅฎไพๅ่กจ๏ผๅ
ถไธญไธไธช็จไบๅญๆพๆๆ็ๅฎไพ๏ผไธไธช็จไบๅญๆพๆญฃๅธธๆๅก็ๅฎไพ
```java
@Monitor(name = PREFIX + "AllServerList", type = DataSourceType.INFORMATIONAL)
protected volatile List<Server> allServerList = Collections
.synchronizedList(new ArrayList<Server>());
@Monitor(name = PREFIX + "UpServerList", type = DataSourceType.INFORMATIONAL)
protected volatile List<Server> upServerList = Collections
.synchronizedList(new ArrayList<Server>());
```
- ๅฎไนไบๆๅกๆฃๆฅ็IPingๅฏน่ฑก๏ผ้ป่ฎคไธบnull
```java
protected IPing ping = null;
```
- ๅฎไนไบๅฎๆฝๆๅกๆฃๆฅ็ๆง่ก็ญ็ฅๅฏน่ฑก๏ผ้็จ้ป่ฎค็ญ็ฅๅฎ็ฐใ
```java
protected IPingStrategy pingStrategy = DEFAULT_PING_STRATEGY
```
ๆบ็ ้จๅ๏ผ
```java
/**
* Default implementation for <c>IPingStrategy</c>, performs ping
* serially, which may not be desirable, if your <c>IPing</c>
* implementation is slow, or you have large number of servers.
*/
private static class SerialPingStrategy implements IPingStrategy {
@Override
public boolean[] pingServers(IPing ping, Server[] servers) {
int numCandidates = servers.length;
boolean[] results = new boolean[numCandidates];
logger.debug("LoadBalancer: PingTask executing [{}] servers configured", numCandidates);
for (int i = 0; i < numCandidates; i++) {
results[i] = false; /* Default answer is DEAD. */
try {
// NOTE: IFF we were doing a real ping
// assuming we had a large set of servers (say 15)
// the logic below will run them serially
// hence taking 15 times the amount of time it takes
// to ping each server
// A better method would be to put this in an executor
// pool
// But, at the time of this writing, we dont REALLY
// use a Real Ping (its mostly in memory eureka call)
// hence we can afford to simplify this design and run
// this
// serially
if (ping != null) {
results[i] = ping.isAlive(servers[i]);
}
} catch (Exception e) {
logger.error("Exception while pinging Server: '{}'", servers[i], e);
}
}
return results;
}
}
```
ๆ นๆฎๆณจ้็ๆๆๆไปฌๅคงๆฆ็ฅ้๏ผๅฆๆServerๅ่กจ่ฟๅคงๆถ๏ผ้็จ้ป่ฎค็บฟๆง้ๅ็ๆนๅผๅฏ่ฝไผๅฝฑๅ็ณป็ป็ๆง่ฝ๏ผ
่ฟไธชๆถๅๅฐฑ้่ฆ ๅฎ็ฐ IPingStrategy ๅนถ้ๅ pingServers ้็จๆดไธบ็ตๆดป็ๆนๅผใ
- ๅฎไนไบๆๅก้ๆฉๅจIRuleๅฏน่ฑก๏ผ่ฟ้้ป่ฎค้็จ**RoundRobinRule**ๅฎ็ฐ
RoundRobinRuleไปฃ็ ้จๅ๏ผ
```java
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
List<Server> reachableServers = lb.getReachableServers();
List<Server> allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
int nextServerIndex = incrementAndGetModulo(serverCount);
server = allServers.get(nextServerIndex);
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
```
่ฟ้ๅฏไปฅ็ๅบRibbon้ป่ฎค็ๆๅก้ๆฉ็ญ็ฅๆฏ็บฟๆง้ๆฉ็ญ็ฅใ
ไธพไธชไพๅญ:็ฌฌไธๆฌก่ฏทๆฑๅๅๅฐไบ 9090 ็ซฏๅฃ ็ฌฌไบๆฌกๅไผๅๅๅฐ 9091 ็ถๅ 9092่ฟๆ ทๆฅ
- ๅฏๅจPingๆๅก๏ผๅฎๆถๆฃๆฅๅฝๅServerๆฏๅฆๅฅๅบท๏ผ้ป่ฎค10็ง
```java
protected int pingIntervalSeconds = 10;
```
- ๅฎ็ฐไบILoadBalancer็ไธ็ณปๅๆไฝ
```java
//ๅๆๅกๅ่กจไธญๆทปๅ ไธไธชๆฐ็ๆๅก
@Override
public void addServers(List<Server> newServers) {
if (newServers != null && newServers.size() > 0) {
try {
ArrayList<Server> newList = new ArrayList<Server>();
newList.addAll(allServerList);
newList.addAll(newServers);
setServersList(newList);
} catch (Exception e) {
logger.error("LoadBalancer [{}]: Exception while adding Servers", name, e);
}
}
}
//ๆ นๆฎ็นๅฎ็key้ๆฉไธไธชๆๅกๅฎไพ
public Server chooseServer(Object key) {
if (counter == null) {
counter = createCounter();
}
counter.increment();
if (rule == null) {
return null;
} else {
try {
return rule.choose(key);
} catch (Exception e) {
logger.warn("LoadBalancer [{}]: Error choosing server for key {}", name, key, e);
return null;
}
}
}
//่ฟๅไธไธชๆๅกๅ่กจ
@Override
public List<Server> getServerList(boolean availableOnly) {
return (availableOnly ? getReachableServers() : getAllServers());
}
//่ฟๅๅฏ็จ็ๅฎไพๅ่กจ
@Override
public List<Server> getReachableServers() {
return Collections.unmodifiableList(upServerList);
}
//่ฟๅๆๆ็ๅฎไพๅ่กจ
@Override
public List<Server> getAllServers() {
return Collections.unmodifiableList(allServerList);
}
//ๆ ่ฎฐไธไธชๆๅกๆๅๆๅก
public void markServerDown(Server server) {
if (server == null || !server.isAlive()) {
return;
}
logger.error("LoadBalancer [{}]: markServerDown called on [{}]", name, server.getId());
server.setAlive(false);
// forceQuickPing();
notifyServerStatusChangeListener(singleton(server));
}
```
## DynamicServerListLoadBalancer็ฑป
ไฝ็จ๏ผๅฏนๅบ็ก็่ด่ฝฝๅ่กกๅจBaseLoadBalancerๅไบๆฉๅฑ๏ผไฝฟๅ
ถๆฅๆๆๅกๅฎไพๆธ
ๅๅจ่ฟ่กๆ็ๅจๆๆดๆฐ็่ฝๅใๅๆถไนๅ
ทๅคไบๅฏนๆๅกๅฎไพๆธ
ๅ็่ฟๆปคๅ่ฝใ
ๅจDynamicServerListLoadBalancer็ฑป็ๆๅๅฎไนไธญ๏ผๆไปฌๅ็ฐๆฐๅขไบไธไธชๆๅ
ServerList<T> serverListImpl ๅฏน่ฑก๏ผๆบ็ ๅฆไธ๏ผ
```java
public interface ServerList<T extends Server> {
//่ทๅๅๅงๅๆถ็ๆๅกๅ่กจ
public List<T> getInitialListOfServers();
/**
*่ทๅๆดๆฐๆถ็ๆๅกๅ่กจ
*/
public List<T> getUpdatedListOfServers();
}
```
้่ฟๆฅ็ServerList็็ปงๆฟๅ
ณ็ณปๅพ๏ผๆไปฌๅ็ฐServerListๆฅๅฃ็ๅฎ็ฐไธๆญขไธไธช๏ผ้ฃ ๅ
ทไฝๆฏไฝฟ็จไบๅชไธไธชๅฎ็ฐๅข๏ผ
ๅฏไปฅไปๅฆไธๆ่ทฏๅ
ฅๆ๏ผๆข็ถDynamicServerListLoadBalancer็ฑปๅฎ็ฐไบๆๅกๅฎไพๆธ
ๅ็ๅจๆๆดๆฐ๏ผ้ฃRibbonๅฟๅฟ
่ฆๅEurekaๆดๅ๏ผๆไปฅๆไปฌไปEurekaๅฏนRibbon็ๆฏๆไธๆใ
### EurekaRibbonClientConfiguration็ฑป:
```java
@Bean
@ConditionalOnMissingBean
public ServerList<?> ribbonServerList(IClientConfig config,
Provider<EurekaClient> eurekaClientProvider) {
if (this.propertiesFactory.isSet(ServerList.class, serviceId)) {
return this.propertiesFactory.get(ServerList.class, config, serviceId);
}
DiscoveryEnabledNIWSServerList discoveryServerList = new DiscoveryEnabledNIWSServerList(
config, eurekaClientProvider);
DomainExtractingServerList serverList = new DomainExtractingServerList(
discoveryServerList, config, this.approximateZoneFromHostname);
return serverList;
}
```
ๅฏไปฅ็ๅฐ้ป่ฎค้็จ็DiscoveryEnabledNIWSServerList ๅฎ็ฐใ
#### DomainExtractingServerList็ฑป๏ผ
```java
public class DomainExtractingServerList implements ServerList<DiscoveryEnabledServer> {
private ServerList<DiscoveryEnabledServer> list;
private final RibbonProperties ribbon;
private boolean approximateZoneFromHostname;
public DomainExtractingServerList(ServerList<DiscoveryEnabledServer> list,
IClientConfig clientConfig, boolean approximateZoneFromHostname) {
this.list = list;
this.ribbon = RibbonProperties.from(clientConfig);
this.approximateZoneFromHostname = approximateZoneFromHostname;
}
@Override
public List<DiscoveryEnabledServer> getInitialListOfServers() {
List<DiscoveryEnabledServer> servers = setZones(
this.list.getInitialListOfServers());
return servers;
}
@Override
public List<DiscoveryEnabledServer> getUpdatedListOfServers() {
List<DiscoveryEnabledServer> servers = setZones(
this.list.getUpdatedListOfServers());
return servers;
}
private List<DiscoveryEnabledServer> setZones(List<DiscoveryEnabledServer> servers) {
List<DiscoveryEnabledServer> result = new ArrayList<>();
boolean isSecure = this.ribbon.isSecure(true);
boolean shouldUseIpAddr = this.ribbon.isUseIPAddrForServer();
for (DiscoveryEnabledServer server : servers) {
result.add(new DomainExtractingServer(server, isSecure, shouldUseIpAddr,
this.approximateZoneFromHostname));
}
return result;
}
}
...็ฅ
}
```
ๅฏไปฅ็ๅฐDomainExtractingServerList็ๅ
ทไฝๅฎ็ฐๆฏๅงๆไบๅ
ถๅ
้จlistๆฅๅฎ็ฐ็๏ผๅ
้จlist้่ฟDomainExtractingServerListๆ้ ๅจไผ ๅ
ฅ็DiscoveryEnabledNIWSServerList่ทๅพใ
## DiscoveryEnabledNIWSServerList ็ฑป๏ผ
ๆบ็ ้จๅ:(้จๅไปฃ็ ็ฅ)
```java
public class DiscoveryEnabledNIWSServerList extends AbstractServerList<DiscoveryEnabledServer> {
public List<DiscoveryEnabledServer> getInitialListOfServers() {
return this.obtainServersViaDiscovery();
}
public List<DiscoveryEnabledServer> getUpdatedListOfServers() {
return this.obtainServersViaDiscovery();
}
rivate List<DiscoveryEnabledServer> obtainServersViaDiscovery() {
List<DiscoveryEnabledServer> serverList = new ArrayList();
if (this.eurekaClientProvider != null && this.eurekaClientProvider.get() != null) {
EurekaClient eurekaClient = (EurekaClient)this.eurekaClientProvider.get();
if (this.vipAddresses != null) {
String[] var3 = this.vipAddresses.split(",");
int var4 = var3.length;
for(int var5 = 0; var5 < var4; ++var5) {
String vipAddress = var3[var5];
List<InstanceInfo> listOfInstanceInfo = eurekaClient.getInstancesByVipAddress(vipAddress, this.isSecure, this.targetRegion);
Iterator var8 = listOfInstanceInfo.iterator();
while(var8.hasNext()) {
InstanceInfo ii = (InstanceInfo)var8.next();
if (ii.getStatus().equals(InstanceStatus.UP)) {
if (this.shouldUseOverridePort) {
if (logger.isDebugEnabled()) {
logger.debug("Overriding port on client name: " + this.clientName + " to " + this.overridePort);
}
InstanceInfo copy = new InstanceInfo(ii);
if (this.isSecure) {
ii = (new Builder(copy)).setSecurePort(this.overridePort).build();
} else {
ii = (new Builder(copy)).setPort(this.overridePort).build();
}
}
DiscoveryEnabledServer des = this.createServer(ii, this.isSecure, this.shouldUseIpAddr);
serverList.add(des);
}
}
if (serverList.size() > 0 && this.prioritizeVipAddressBasedServers) {
break;
}
}
}
return serverList;
} else {
logger.warn("EurekaClient has not been initialized yet, returning an empty list");
return new ArrayList();
}
}
}
```
- ็ฌฌไธๆญฅ,้่ฟeureka่ทๅๆๅกๅฎไพlistOfInstanceInfoๅ่กจ
```java
List<InstanceInfo> listOfInstanceInfo = eurekaClient.getInstancesByVipAddress(vipAddress, isSecure, targetRegion)
```
- ็ฌฌไบๆญฅ๏ผ้ๅlistOfInstanceInfoๅ่กจ๏ผๅฆๆ่ฏฅๆๅกๅฎไพ็ถๆไธบUP๏ผๅ่ฝฌๅๆDiscoveryEnabledServerๅฏน่ฑก๏ผ็ถๅๆทปๅ ๅฐserverList้้ขใ
- ่ฟๅserverListๆๅกๅฎไพๅ่กจใ
้่ฟๆฅ็ไธ้ข็ไปฃ็ ๅคงๆฆ็ฅ้ไบRibbonๆฏๅฆไฝไปEurekaๆณจๅไธญๅฟ่ทๅๆๆฐ็ๆๅกๅ่กจ็๏ผ้ฃRibbonๅๆฏๅฆไฝๅฐ่ทๅๅฐ็ๆๅกๅ่กจๆดๆฐๅฐๆฌๅฐ็ๅข๏ผ่ฟไธๅ็ๅ
ณ้ฎๆฏๅจDynamicServerListLoadBalancer็ฑปไธ๏ผๅ ไธบๆไปฌ็ฅ้DynamicServerListLoadBalancer็ฑปๅ
ทไฝๅฎ็ฐไบๅจๆๆดๆฐๆๅกๅ่กจ็ๅ่ฝใ
้่ฟๆฅ็ๆบ็ ๏ผ
```java
protected final ServerListUpdater.UpdateAction updateAction = new ServerListUpdater.UpdateAction() {
//ๆดๆฐ็ๅ
ทไฝๅฎ็ฐ
@Override
public void doUpdate() {
updateListOfServers();
}
};
```
```java
public interface ServerListUpdater {
/**
* an interface for the updateAction that actually executes a server list update
*/
public interface UpdateAction {
void doUpdate();
}
/**
* start the serverList updater with the given update action
* This call should be idempotent.
* ๅฏๅจๆๅกๆดๆฐๅจ
*
* @param updateAction
*/
void start(UpdateAction updateAction);
/**
* stop the serverList updater. This call should be idempotent
*ๅๆญขๆๅกๆดๆฐๅจ
*/
void stop();
/**
* @return the last update timestamp as a {@link java.util.Date} string
*่ทๅๆ่ฟไธๆฌกๆดๆฐ็ๆถ้ด
*/
String getLastUpdate();
/**
* @return the number of ms that has elapsed since last update
* ่ทๅไธไธๆฌกๆดๆฐๅฐ็ฐๅจ็ๆถ้ด้ด้๏ผๅไฝไธบMsๆฏซ็ง
*/
long getDurationSinceLastUpdateMs();
/**
* @return the number of update cycles missed, if valid
*/
int getNumberMissedCycles();
/**
* @return the number of threads used, if vaid
* ่ทๅๆ ธๅฟ็บฟ็จๆฐ
*/
int getCoreThreads();
}
```
้่ฟๆฅ็ServerListUpdater ๆฅๅฃๅฎ็ฐๅ
ณ็ณปๅพ๏ผๆไปฌๅคงๆฆๅ็ฐRibbonๅ
็ฝฎไบไธคไธชๅฎ็ฐใ
- PollingServerListUpdater ๏ผ้ป่ฎค้็จ็ๆดๆฐ็ญ็ฅ๏ผ้็จๅฎๆถไปปๅก็ๆนๅผๅจๆๆดๆฐๆๅกๅ่กจ
```java
// msecs; ๅปถ่ฟไธ็งๅผๅงๆง่ก
private static long LISTOFSERVERS_CACHE_UPDATE_DELAY = 1000;
// msecs;ไปฅ30็งไธบๅจๆ้ๅคๆง่ก
private static int LISTOFSERVERS_CACHE_REPEAT_INTERVAL = 30 * 1000;
```
- EurekaNotificationServerListUpdater :ๅบไบEurekaไบไปถๆบๅถๆฅ้ฉฑๅจๆๅกๅ่กจๆดๆฐ็ๅฎ็ฐใ
้ฃไน๏ผๆไปฌRibbon้ป่ฎคๅ
ทไฝ้็จไบๅชไธ็งๆดๆฐ็ญ็ฅๅข๏ผ้่ฟๆฅ็DynamicServerListLoadBalancer็ฑป็ไปฃ็ ๏ผๆไปฌๅ็ฐRibbon้็จ็้ป่ฎคๆๅกๆดๆฐๅจๆฏPollingServerListUpdater
```java
@Deprecated
public DynamicServerListLoadBalancer(IClientConfig clientConfig, IRule rule, IPing ping,
ServerList<T> serverList, ServerListFilter<T> filter) {
this(
clientConfig,
rule,
ping,
serverList,
filter,
new PollingServerListUpdater()
);
}
```
ๆข็ถไบ่งฃไบ้ป่ฎคๆดๆฐ็ญ็ฅ๏ผ้ฃไนๆไปฌๅๆฌกๅๅฐๆไปฌ็ไธป่งDynamicServerListLoadBalancer็ฑปไธใ
```java
protected final ServerListUpdater.UpdateAction updateAction = new ServerListUpdater.UpdateAction() {
@Override
public void doUpdate() {
updateListOfServers();
}
};
```
้่ฟไปฃ็ ๆไปฌๅ็ฐๅฎ้
ๅฑฅ่กๆดๆฐ่่ดฃ็ๆนๆณๆฏ updateListOfServers() ๏ผไธๅบ่ฏ๏ผไธไปฃ็ :
```java
@VisibleForTesting
public void updateListOfServers() {
List<T> servers = new ArrayList<T>();
if (serverListImpl != null) {
servers = serverListImpl.getUpdatedListOfServers();
LOGGER.debug("List of Servers for {} obtained from Discovery client: {}",
getIdentifier(), servers);
if (filter != null) {
servers = filter.getFilteredListOfServers(servers);
LOGGER.debug("Filtered List of Servers for {} obtained from Discovery client: {}",
getIdentifier(), servers);
}
}
updateAllServerList(servers);
}
```
้่ฟๆฅ็ไปฃ็ ๏ผๆไปฌๅ็ฐๆต็จๅคง่ดๅฆไธ๏ผ
- ้่ฟ ServerList็getUpdatedListOfServers() ๆนๆณ่ทๅๅฐๆๆฐ็ๆๅกๅฎไพๅ่กจ
- ๅฆๆไนๅๅฎไนไบ่ฟๆปคๅจ๏ผๅๆ็
งๆ็ง่งๅๅฎๆฝ่ฟๆปค๏ผๆๅ่ฟๅ
- updateAllServerList(servers); ๅฎๆๆๅ็ๆดๆฐๆไฝใ
```java
public interface ServerListFilter<T extends Server> {
public List<T> getFilteredListOfServers(List<T> servers);
}
```
้่ฟๆฅ็็ปงๆฟๅฎ็ฐๅ
ณ็ณปๅพ๏ผๅ็ฐServerListFilter็็ดๆฅๅฎ็ฐ็ฑปไธบ๏ผAbstractServerListFilter
ๅ
ถไธญZoneAffinityServerListFilter ็ปงๆฟไบ AbstractServerListFilter ๏ผ็ถๅๅพZoneAffinityServerListFilter ็ไผ ็ๅญ็ฑปๅๆๅฅฝๅค๏ผ่ฟ้็้ไป็ป**AbstractServerListFilter** ๅ **ZoneAffinityServerListFilter** ๅฎ็ฐ
- AbstractServerListFilter ๏ผๆฝ่ฑก่ฟๆปคๅจ๏ผไพ่ตLoadBalancerStatsๅฏน่ฑกๅฎ็ฐ่ฟๆปคใLoadBalancerStatsๅญๅจไบ่ด่ฝฝๅ่กกๅจ็ไธไบๅฑๆงๅ็ป่ฎกไฟกๆฏใ
- ZoneAffinityServerListFilter๏ผๆญคๆๅกๅจๅ่กจ็ญ้ๅจๅค็ๅบไบๅบๅๅ
ณ่ๆง็ญ้ๆๅกๅจใๅฎไผ่ฟๆปคๆไธไบๆๅกๅฎไพๅๆถ่ดน่
ไธๅจไธไธชZone๏ผๅบๅ๏ผ็ๅฎไพใ
## ZoneAwareLoadBalancer็ฑป
**ๅ่ฝ๏ผ**ZoneAwareLoadBalancer่ด่ฝฝๅ่กกๅจๆฏๅฏนDynamicServerListLoadBalancer็ฑป็ๆฉๅฑๅ่กฅๅ
๏ผ่ฏฅ่ด่ฝฝๆททๅๅจๅฎ็ฐไบZone(ๅบๅ)็ๆฆๅฟต๏ผ้ฟๅ
ไบๅ ไธบ่ทจๅบๅ่ๅฏผ่ด็ๅบๅๆงๆ
้๏ผไป่ๅฎ็ฐไบๆๅก็้ซๅฏ็จใ
้ฃไนZoneAwareLoadBalancerๅ
ทไฝๅไบๅชไบๅทฅไฝๆฅๅฎ็ฐ่ฟไบๅ่ฝ็ๅข๏ผ
็ฌฌไธ๏ผ้ๅไบDynamicServerListLoadBalancer็setServerListForZonesๆนๆณ๏ผ
**ๅ็๏ผ**
```java
protected void setServerListForZones(
Map<String, List<Server>> zoneServersMap) {
LOGGER.debug("Setting server list for zones: {}", zoneServersMap);
getLoadBalancerStats().updateZoneServerMapping(zoneServersMap);
}
```
**ZoneAwareLoadBalancer็ฑป็:**
```java
@Override
protected void setServerListForZones(Map<String, List<Server>> zoneServersMap) {
super.setServerListForZones(zoneServersMap);
if (balancers == null) {
//balancers ็จๆฅๅญๅจๆฏไธชStringๅฏนๅบ็Zone
balancers = new ConcurrentHashMap<String, BaseLoadBalancer>();
}
//่ฎพ็ฝฎๅฏนๅบzoneไธ้ข็ๅฎไพๆธ
ๅ
for (Map.Entry<String, List<Server>> entry: zoneServersMap.entrySet()) {
String zone = entry.getKey().toLowerCase();
getLoadBalancer(zone).setServersList(entry.getValue());
}
//ๆฃๆฅๆฏๅฆๆไธๅๆฅๆๆๅกๅจ็ๅบๅ
//ๅนถๅฐๅ่กจ่ฎพ็ฝฎไธบ็ฉบ๏ผไปฅไพฟไธๅบๅ็ธๅ
ณ็ๅบฆ้ไธไธบ็ฉบ
//ๅ
ๅซ่ฟๆถ็ๆฐๆฎ
// ้ฒๆญขๅ ไธบZone็ไฟกๆฏ่ฟๆถ่ๅนฒๆฐๅ
ทไฝๅฎไพ็้ๆฉ็ฎๆณใ
for (Map.Entry<String, BaseLoadBalancer> existingLBEntry: balancers.entrySet()) {
if (!zoneServersMap.keySet().contains(existingLBEntry.getKey())) {
existingLBEntry.getValue().setServersList(Collections.emptyList());
}
}
}
```
้ฃZoneAwareLoadBalancer็ฑปๆฏๅ
ทไฝๅฆไฝๆฅ้ๆฉๅ
ทไฝ็ๆๅกๅฎไพๅข๏ผ
```java
@Override
public Server chooseServer(Object key) {
if (!ENABLED.get() || getLoadBalancerStats().getAvailableZones().size() <= 1) {
logger.debug("Zone aware logic disabled or there is only one zone");
return super.chooseServer(key);
}
Server server = null;
try {
LoadBalancerStats lbStats = getLoadBalancerStats();
//ไธบๆๆZone้ฝๅๅปบไธไธชๅฟซ็
ง
Map<String, ZoneSnapshot> zoneSnapshot = ZoneAvoidanceRule.createSnapshot(lbStats);
logger.debug("Zone snapshots: {}", zoneSnapshot);
if (triggeringLoad == null) {
triggeringLoad = DynamicPropertyFactory.getInstance().getDoubleProperty(
"ZoneAwareNIWSDiscoveryLoadBalancer." + this.getName() + ".triggeringLoadPerServerThreshold", 0.2d);
}
if (triggeringBlackoutPercentage == null) {
triggeringBlackoutPercentage = DynamicPropertyFactory.getInstance().getDoubleProperty(
"ZoneAwareNIWSDiscoveryLoadBalancer." + this.getName() + ".avoidZoneWithBlackoutPercetage", 0.99999d);
}
Set<String> availableZones = ZoneAvoidanceRule.getAvailableZones(zoneSnapshot, triggeringLoad.get(), triggeringBlackoutPercentage.get());
logger.debug("Available zones: {}", availableZones);
if (availableZones != null && availableZones.size() < zoneSnapshot.keySet().size()) {
String zone = ZoneAvoidanceRule.randomChooseZone(zoneSnapshot, availableZones);
logger.debug("Zone chosen: {}", zone);
if (zone != null) {
BaseLoadBalancer zoneLoadBalancer = getLoadBalancer(zone);
server = zoneLoadBalancer.chooseServer(key);
}
}
} catch (Exception e) {
logger.error("Error choosing server using zone aware logic for load balancer={}", name, e);
}
if (server != null) {
return server;
} else {
logger.debug("Zone avoidance logic is not invoked.");
return super.chooseServer(key);
}
}
```
ไปๆบ็ ไธญๅฏไปฅ็ๅบๆฅ๏ผ getLoadBalancerStats().getAvailableZones().size() <= 1 ๅชๆๅจๅฝๅ็Zoneๅบๅ็ๆฐ้ๅคงไบ1็ๆถๅๆไผ้็จๅบๅ้ๆฉ็ญ็ฅ๏ผๅฆๅ็่ฏ๏ผๅ'**return super.chooseServer(key)**' ไปไนไนไธๅ๏ผ้็จ็ถ็ฑป็ๅฎ็ฐใ
ๅจ้ๆฉๅ
ทไฝ็ๆๅกๅฎไพไธญ๏ผZoneAwareLoadBalancerไธป่ฆๅไบไปฅไธๅ ไปถไบ๏ผ
- ไธบๆๆZoneๅบๅๅๅซๅๅปบไธไธชๅฟซ็
ง๏ผๅญๅจๅจzoneSnapshot ้้ข
- ้่ฟZoneๅฟซ็
งไธญ็ไฟกๆฏ๏ผๆ็
งๆ็ง็ญ็ฅไพๅฆZone็ๆๅกๅฎไพๆฐ้๏ผๆ
้็็ญ็ญๆฅ็ญ้ๆไธ็ฌฆๅๆกไปถ็Zoneๅบๅใ
- ๅฆๆๅ็ฐๆฒกๆ็ฌฆๅๅ้ค่ฆๆฑ็ๅบๅ๏ผๅๆถๅฎไพๆๅคงๅนณๅ่ด่ฝฝๅฐไบ้ๅผ๏ผ้ป่ฎค็พๅไน20๏ผ๏ผๅฐฑ็ดๆฅ่ฟๅๆๆๅฏไปฅ็Zoneๅบๅ๏ผๅฆๅ๏ผ้ๆบๅ้คไธไธชๆๅ็Zoneใ
- ่ทๅพ็ๅฏ็จ็Zoneๅ่กจไธไธบ็ฉบ๏ผๅนถไธๆฐ้ๅฐไบไนๅๅฟซ็
งไธญ็ๆปๆฐ้๏ผๅๆ นๆฎIRule่งๅ้ๆบ้ไธไธชZoneๅบๅ
```java
if (availableZones != null && availableZones.size() < zoneSnapshot.keySet().size()) {
String zone = ZoneAvoidanceRule.randomChooseZone(zoneSnapshot, availableZones);
logger.debug("Zone chosen: {}", zone);
if (zone != null) {
BaseLoadBalancer zoneLoadBalancer = getLoadBalancer(zone);
server = zoneLoadBalancer.chooseServer(key);
}
}
```
- ็กฎๅฎไบๆ็ป็Zoneไนๅ๏ผๆ็ป่ฐ็จ BaseLoadBalancer็chooseServerๆฅ้ๆฉไธไธชๅ้็ๆๅกๅฎไพใ
# ่ด่ฝฝๅ่กก็ญ็ฅ
้่ฟไธ้ข็ๅๆ๏ผๆไปฌๅ็ฐๅฝไธไธช่ฏทๆฑ่ฟๆฅๆถ๏ผไผ่ขซๆฆๆชไบค็ป็ธๅบ็่ด่ฝฝๅ่กกๅจ๏ผ็ถๅไธๅ็่ด่ฝฝๅ่กกๅจๆ นๆฎไธๅ็็ญ็ฅๆฅ้ๆฉๅ้็ๆๅกๅฎไพใๅจ่ฟ้ๆไปฌๆฏ็ฅ้Ribbonๆฏๆ นๆฎไธๅ็Ruleๆฅๅฎ็ฐๅฏนๅฎไพ็ไธไธช้ๆฉ็๏ผ้ฃไนRibbonๅ
ทไฝๆไพไบๅชไบ่งๅไพๆไปฌไฝฟ็จๅข๏ผ้่ฟๆฅ็Ribbon็IRuleๆฅๅฃ็ๅฎ็ฐ้ๆๅ
ณ็ณปๅพ๏ผๆไปฌๆ็ปๅฏไปฅๅ็ฐ๏ผRibbonไธป่ฆๆไพไบไปฅไธๅ ไธช่งๅๅฎ็ฐ็ใ
- RandomRule ็ฑป๏ผ่ฏฅ็ญ็ฅๅฎ็ฐไบไปๆๅกๅฎไพๆธ
ๅไธญ้ๆบ้ๆฉไธไธชๆๅกๅฎไพ็ๅ่ฝ
- RoundRobinRule็ฑป๏ผ่ฏฅ็ญ็ฅๅฎ็ฐไบ่ฝฎ่ฏข็ๆนๅผไปๆๅกๅฎไพๆธ
ๅไธญไพๆฌก้ๆฉๆๅกๅฎไพ็ๅ่ฝRetryRule
- RetryRule็ฑป๏ผ่ฏฅ็ญ็ฅๅฎ็ฐไบๅ
ทๅค้่ฏๆบๅถ็ๅฎไพ้ๆฉๅ่ฝ
- WeightedResponseTimeRule็ฑป๏ผๆ นๆฎๆ้ๆฅ้ๆฉๅฎไพ
- BestAvailableRule็ฑป๏ผ้ๆฉไธไธชๆ็ฉบ้ฒ็ๅฎไพ
- PredicateBasedRule ็ฑป๏ผๅ
่ฟๆปค๏ผ็ถๅๅไปฅ่ฝฎ่ฏข็ๆนๅผ้ๆฉๅฎไพ
...
## IRuleๆฅๅฃ:
```java
public interface IRule{
public Server choose(Object key);
public void setLoadBalancer(ILoadBalancer lb);
public ILoadBalancer getLoadBalancer();
}
```
## AbstractLoadBalancerRuleๆฝ่ฑก็ฑป:
```java
public abstract class AbstractLoadBalancerRule implements IRule, IClientConfigAware {
private ILoadBalancer lb;
@Override
public void setLoadBalancer(ILoadBalancer lb){
this.lb = lb;
}
@Override
public ILoadBalancer getLoadBalancer(){
return lb;
}
}
```
## RandomRule็ฑป
ๅ่ฝ๏ผ่ฏฅ็ญ็ฅๅฎ็ฐไบไปๆๅกๅฎไพๆธ
ๅไธญ้ๆบ้ๆฉไธไธชๆๅกๅฎไพ็ๅ่ฝใ
ๆฅ็ไปฃ็ ๅ็ฐๅ
ทไฝ็ๅฎไพ้ๆฉๅนถๆฒกๆ็ฑ้ป่ฎค็choose(Object key)ๆฅๅฎ็ฐ๏ผ่ๆฏๅงๆ็ปไบๅ็ฑปไธ็choose(ILoadBalancer lb, Object key)ๆนๆณๆฅๅฎๆๅฎ้
็ๅฎไพ้ๆฉๅทฅไฝใ
```java
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
if (Thread.interrupted()) {
return null;
}
List<Server> upList = lb.getReachableServers();
List<Server> allList = lb.getAllServers();
int serverCount = allList.size();
if (serverCount == 0) {
/*
* No servers. End regardless of pass, because subsequent passes
* only get more restrictive.
*/
return null;
}
int index = chooseRandomInt(serverCount);
server = upList.get(index);
if (server == null) {
/*
* The only time this should happen is if the server list were
* somehow trimmed. This is a transient condition. Retry after
* yielding.
*/
Thread.yield();
continue;
}
if (server.isAlive()) {
return (server);
}
// Shouldn't actually happen.. but must be transient or a bug.
server = null;
Thread.yield();
}
return server;
}
```
> ๆณจ๏ผๅฆๆ่ทๅไธๅฐๆๅกๅฎไพ๏ผๅๅฏ่ฝๅญๅจๅนถๅ็bug
## RoundRobinRule็ฑป
ๅ่ฝ๏ผ่ฏฅ็ญ็ฅๅฎ็ฐไบ่ฝฎ่ฏข็ๆนๅผไปๆๅกๅฎไพๆธ
ๅไธญไพๆฌก้ๆฉๆๅกๅฎไพ็ๅ่ฝ
```java
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
log.warn("no load balancer");
return null;
}
Server server = null;
int count = 0;
while (server == null && count++ < 10) {
//reachableServers ๅฏ็จ็ๆๅกๅฎไพๆธ
ๅ
List<Server> reachableServers = lb.getReachableServers();
//allServers ่ทๅๆๆๅฏ็จ็ๆๅกๅ่กจ
List<Server> allServers = lb.getAllServers();
int upCount = reachableServers.size();
int serverCount = allServers.size();
if ((upCount == 0) || (serverCount == 0)) {
log.warn("No up servers available from load balancer: " + lb);
return null;
}
int nextServerIndex = incrementAndGetModulo(serverCount);
server = allServers.get(nextServerIndex);
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive() && (server.isReadyToServe())) {
return (server);
}
// Next.
server = null;
}
if (count >= 10) {
log.warn("No available alive servers after 10 tries from load balancer: "
+ lb);
}
return server;
}
private int incrementAndGetModulo(int modulo) {
for (;;) {
int current = nextServerCyclicCounter.get();
int next = (current + 1) % modulo;
if (nextServerCyclicCounter.compareAndSet(current, next))
return next;
}
}
```
ๆบ็ ๅๆ๏ผๅฏไปฅๅ็ฐRoundRobinRule็ๅฎ็ฐ้ป่พๅRandomRule้ๅธธ็ฑปไผผ๏ผๆไปฌๅฏไปฅ็ๅบๆฅ๏ผRoundRobinRuleๅฎไนไบไธไธช่ฎกๆฐๅจๅ้count๏ผ่ฏฅ่ฎกๆฐๅจไผๅจๆฏๆฌกๅพช็ฏๅ่ชๅจๅ ๅ ๏ผๅฝ่ทๅไธๅฐServer็ๆฌกๆฐ่ถ
่ฟๅๆฌกๆถ๏ผไผ็ปๆๅฐ่ฏ๏ผๅนถๅๅบ่ญฆๅ๏ผNo available alive servers after 10 tries from load balancerใ
่็บฟๆง่ฝฎ่ฏข็ๅฎ็ฐๅๆฏ้่ฟ incrementAndGetModulo(int modulo)ๆฅๅฎ็ฐ็.
## RetryRule็ฑป:
ๅ่ฝ๏ผ่ฏฅ็ญ็ฅๅฎ็ฐไบๅ
ทๅค้่ฏๆบๅถ็ๅฎไพ้ๆฉๅ่ฝ
```java
public Server choose(ILoadBalancer lb, Object key) {
//่ฏทๆฑๆถ้ด
long requestTime = System.currentTimeMillis();
//deadline ๆชๆญขๆ้
long deadline = requestTime + maxRetryMillis;
Server answer = null;
answer = subRule.choose(key);
if (((answer == null) || (!answer.isAlive()))
&& (System.currentTimeMillis() < deadline)) {
InterruptTask task = new InterruptTask(deadline
- System.currentTimeMillis());
while (!Thread.interrupted()) {
answer = subRule.choose(key);
if (((answer == null) || (!answer.isAlive()))
&& (System.currentTimeMillis() < deadline)) {
/* pause and retry hoping it's transient */
Thread.yield();
} else {
break;
}
}
task.cancel();
}
if ((answer == null) || (!answer.isAlive())) {
return null;
} else {
return answer;
}
}
```
้ป่ฎคไฝฟ็จ็ๆฏRoundRobinRule็ญ็ฅใๆ้ดๅฆๆ่ฝ้ๆฉๅฐๅฎไพๅฐฑ่ฟๅ๏ผๅฆๆ้ๆฉไธๅฐๅฐฑๆ นๆฎ่ฎพ็ฝฎ็ๅฐ่ฏ็ปๆๆถ้ดไธบ้ๅผ๏ผๅฆๆ่ถ
่ฟๆชๆญขๆ้ๅ็ดๆฅ่ฟๅnullใ
## WeightedResponseTimeRule็ฑป
ๅ่ฝ๏ผๆ นๆฎๆ้ๆฅ้ๆฉๅฎไพ
ไธป่ฆๆไปฅไธไธไธชๆ ธๅฟๅ
ๅฎน๏ผ
- ๅฎๆถไปปๅก
- ๆ้่ฎก็ฎ
- ๅฎไพ้ๆฉ
### 1. ๅฎๆถไปปๅก
```java
void initialize(ILoadBalancer lb) {
if (serverWeightTimer != null) {
serverWeightTimer.cancel();
}
serverWeightTimer = new Timer("NFLoadBalancer-serverWeightTimer-"
+ name, true);
//ๅฏๅจๅฎๆถไปปๅก
serverWeightTimer.schedule(new DynamicServerWeightTask(), 0,
serverWeightTaskTimerInterval);
// do a initial run
ServerWeight sw = new ServerWeight();
sw.maintainWeights();
Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
public void run() {
logger
.info("Stopping NFLoadBalancer-serverWeightTimer-"
+ name);
serverWeightTimer.cancel();
}
}));
}
```
WeightedResponseTimeRule็ฑปๅจๅๅงๅ็ๆถๅไผๅ
ๅฎไนไธไธช่ฎกๆถๅจ๏ผ็ถๅไผๅฏๅจไธไธชๅฎๆถไปปๅก๏ผ็จๆฅไธบๆฏไธชๆๅกๅฎไพ่ฎก็ฎๆ้๏ผ่ฏฅไปปๅก้ป่ฎคๆฏ30็งๆง่กไธๆฌกใ
```java
class DynamicServerWeightTask extends TimerTask {
public void run() {
ServerWeight serverWeight = new ServerWeight();
try {
serverWeight.maintainWeights();
} catch (Exception e) {
logger.error("Error running DynamicServerWeightTask for {}", name, e);
}
}
}
```
### 2.ๆ้่ฎก็ฎ
้่ฟไธ้ข็DynamicServerWeightTask็ไปฃ็ ๅข๏ผๆไปฌๅฏไปฅๅคง่ดไบ่งฃๅฐ๏ผๆ้่ฎก็ฎ็ๅ่ฝๅขๅฎ้
ๆฏ็ฑServerWeight็maintainWeights()ๆฅๆง่ก็ใๅฐๅบ่ฏ๏ผไธไปฃ็ ใ
```java
public void maintainWeights() {
ILoadBalancer lb = getLoadBalancer();
if (lb == null) {
return;
}
if (!serverWeightAssignmentInProgress.compareAndSet(false, true)) {
return;
}
try {
logger.info("Weight adjusting job started");
AbstractLoadBalancer nlb = (AbstractLoadBalancer) lb;
LoadBalancerStats stats = nlb.getLoadBalancerStats();
if (stats == null) {
// no statistics, nothing to do
return;
}
double totalResponseTime = 0;
// find maximal 95% response time
for (Server server : nlb.getAllServers()) {
// this will automatically load the stats if not in cache
ServerStats ss = stats.getSingleServerStat(server);
totalResponseTime += ss.getResponseTimeAvg();
}
// weight for each server is (sum of responseTime of all servers - responseTime)
// so that the longer the response time, the less the weight and the less likely to be chosen
Double weightSoFar = 0.0;
// create new list and hot swap the reference
List<Double> finalWeights = new ArrayList<Double>();
for (Server server : nlb.getAllServers()) {
ServerStats ss = stats.getSingleServerStat(server);
double weight = totalResponseTime - ss.getResponseTimeAvg();
weightSoFar += weight;
finalWeights.add(weightSoFar);
}
setWeights(finalWeights);
} catch (Exception e) {
logger.error("Error calculating server weights", e);
} finally {
serverWeightAssignmentInProgress.set(false);
}
}
}
```
้ฃWeightedResponseTimeRuleๆฏๅฆไฝ่ฎก็ฎๆ้็ๅข๏ผไธป่ฆๅไธบไปฅไธไธคๆญฅ๏ผ
1. ๅ
้ๅๆๅกๅจๅ่กจ๏ผๅนถๅพๅฐๆฏไธชๆๅกๅจ็ๅนณๅๅๅบๆถ้ด๏ผ้ๅ่ฟ็จไธญๅฏนๅ
ถๆฑๅ๏ผ้ๅ็ปๆๅๅพๅฐๆปๅๅบๆถ้ดtotalResponseTimeใ
2. ๅไธๆฌก้ๅๆๅกๅจๅ่กจ๏ผๅนถๅฐๆปๅๅบๆถ้ดtotalResponseTimeๅๅปๆฏไธชๆๅกๅจ็ๅนณๅๅๅบๆถ้ดไฝไธบๆ้weight๏ผๅๅฐ่ฟไนๅ็ๆไปฅๆ้็ดฏๅ ๅฐweightSoFar ๅ้ไธญ๏ผๅนถไธไฟๅญๅฐfinalWeightsไพchooseไฝฟ็จใ
### 3.ๅฎไพ้ๆฉ
```java
public Server choose(ILoadBalancer lb, Object key) {
if (lb == null) {
return null;
}
Server server = null;
while (server == null) {
//่ทๅๅฝๅๅผ็จ๏ผไปฅ้ฒๅฎ่ขซๅ
ถไป็บฟ็จๆดๆน
List<Double> currentWeights = accumulatedWeights;
if (Thread.interrupted()) {
return null;
}
List<Server> allList = lb.getAllServers();
int serverCount = allList.size();
if (serverCount == 0) {
return null;
}
int serverIndex = 0;
// ๅ่กจไธญ็ๆๅไธไธชๆฏๆๆๆ้็ๅ
double maxTotalWeight = currentWeights.size() == 0 ? 0 : currentWeights.get(currentWeights.size() - 1);
//ๅฐๆชๅฝไธญไปปไฝๆๅกๅจ๏ผไธๆชๅๅงๅๆป้้
//ไฝฟ็จๅพช็ฏๆไฝ
if (maxTotalWeight < 0.001d || serverCount != currentWeights.size()) {
server = super.choose(getLoadBalancer(), key);
if(server == null) {
return server;
}
} else {
//็ๆไธไธชไป0(ๅซ)ๅฐmaxTotalWeight(ไธๅซ)ไน้ด็้ๆบๆ้
double randomWeight = random.nextDouble() * maxTotalWeight;
//ๆ นๆฎ้ๆบ็ดขๅผ้ๆฉๆๅกๅจ็ดขๅผ
int n = 0;
for (Double d : currentWeights) {
if (d >= randomWeight) {
serverIndex = n;
break;
} else {
n++;
}
}
server = allList.get(serverIndex);
}
if (server == null) {
/* Transient. */
Thread.yield();
continue;
}
if (server.isAlive()) {
return (server);
}
// Next.
server = null;
}
return server;
}
```
ๆง่กๆญฅ้ชค๏ผ
- ็ๆไธไธชไป0(ๅซ)ๅฐmaxTotalWeight(ไธๅซ)ไน้ด็้ๆบๆ้
- ้ๅๆ้ๅ่กจ๏ผๆฏ่พๆ้ๅผไธ้ๆบๆฐ็ๅคงๅฐ๏ผๅฆๆๆ้ๅผๅคงไบ็ญไบ้ๆบๆฐ๏ผๅฐฑๅฝๅๆ้ๅ่กจ็็ดขๅผๅผๅปๆๅกๅฎไพๅ่กจไธญๅ่กจไธญ่ทๅๅ
ทไฝ็ๅฎไพใ
## BestAvailableRule็ฑป
ๅ่ฝ๏ผ้ๆฉไธไธชๆ็ฉบ้ฒ็ๅฎไพ
```java
@Override
public Server choose(Object key) {
if (loadBalancerStats == null) {
return super.choose(key);
}
List<Server> serverList = getLoadBalancer().getAllServers();
//minimalConcurrentConnections๏ผๆๅฐๅนถๅ่ฟๆฅๆฐ
int minimalConcurrentConnections = Integer.MAX_VALUE;
long currentTime = System.currentTimeMillis();
Server chosen = null;
for (Server server: serverList) {
ServerStats serverStats = loadBalancerStats.getSingleServerStat(server);
if (!serverStats.isCircuitBreakerTripped(currentTime)) {
//concurrentConnections:ๅนถๅ่ฟๆฅๆฐ
int concurrentConnections = serverStats.getActiveRequestsCount(currentTime);
if (concurrentConnections < minimalConcurrentConnections) {
minimalConcurrentConnections = concurrentConnections;
chosen = server;
}
}
}
if (chosen == null) {
return super.choose(key);
} else {
return chosen;
}
}
```
้่ฟๆฅ็ๆบ็ ๅฏไปฅๅพ็ฅBestAvailableRuleๅคง่ด้็จไบๅฆไธ็ญ็ฅๆฅ้ๆฉๆๅกๅฎไพ๏ผๆ นๆฎloadBalancerStatsไธญ็็ป่ฎกไฟกๆฏ้่ฟ้ๅ่ด่ฝฝๅ่กกๅจ็ปดๆค็ๆๆๆๅกๅฎไพ ้ๅบๅนถๅ่ฟๆฅๆฐๆๅฐ็้ฃไธไธช๏ผๅณๆ็ฉบ้ฒ็ๅฎไพใ
ๅฆๆloadBalancerStatsไธบ็ฉบ็่ฏ๏ผๅ็ดๆฅ่ฐ็จ็ถ็ฑปClientConfigEnabledRoundRobinRule็ๅฎ็ฐ๏ผๅณRoundRobinRule๏ผ็บฟๆง่ฝฎ่ฏข็ๆนๅผใ
## PredicateBasedRule ็ฑป
ๅ่ฝ๏ผๅ
่ฟๆปค๏ผ็ถๅๅไปฅ่ฝฎ่ฏข็ๆนๅผ้ๆฉๅฎไพ
```java
@Override
public Server choose(Object key) {
ILoadBalancer lb = getLoadBalancer();
Optional<Server> server = getPredicate().chooseRoundRobinAfterFiltering(lb.getAllServers(), key);
if (server.isPresent()) {
return server.get();
} else {
return null;
}
}
```
ๅฎ็ฐ้ป่พ๏ผ้่ฟๅญ็ฑปไธญๅฎ็ฐ็predicate้ป่พๆฅ่ฟๆปคไธ้จๅๆๅกๅฎไพ๏ผ็ถๅๅไปฅ็บฟๆง่ฝฎ่ฏข็ๆนๅผไป่ฟๆปคไนๅ็ๆๅกๅฎไพๆธ
ๅไธญ้ๆฉไธไธชใ
ๅฝ็ถ๏ผPredicateBasedRuleๆฌ่บซๆฏไธไธชๆฝ่ฑก็ฑป๏ผๅฟ
็ถRibbonๆไพไบ็ธๅบ็ๅญ็ฑปๅฎ็ฐ๏ผๆไปฌ็ๅฐๆZoneAvoidanceRuleๅAvailabilityFilteringRule๏ผๅๅซๅฏนPredicateBasedRuleๅไบ็ธๅบ็ๆฉๅฑ๏ผๆๅ
ด่ถฃ็ๅฐไผไผดๅฏไปฅไธๅป่ช่ก็ ็ฉถใ
# ้
็ฝฎ่ฏฆ่งฃ๏ผ
## ่ชๅจๅ้
็ฝฎ๏ผ
ๅๆ ท๏ผๅพ็ไบSpringboot็่ชๅจๅ้
็ฝฎ๏ผๅคงๅคง้ไฝไบๅผๅ่
ไธๆ็้พๅบฆ๏ผๅจๅผๅ
ฅSpring-Clould-Ribbonไพ่ตไนๅ๏ผไพฟ่ฝๅค่ชๅจๆๅปบไธ้ข่ฟไบๆฅๅฃ็ๅฎ็ฐใ
- IClientConfig๏ผRibbonๅฎขๆท็ซฏ้
็ฝฎๆฅๅฃ็ฑป๏ผ้ป่ฎคๅฎ็ฐ๏ผcom.netflix.client.config.DefaultClientConfigImpl
- IRule: Ribbon๏ผๆๅกๅฎไพ้ๆฉ็ญ็ฅๆฅๅฃ็ฑป๏ผ้ป่ฎค้็จ็ๅฎ็ฐ๏ผcom.netflix.loadbalancer.ZoneAvoidanceRule
- IPing:Ribbon๏ผๅฎไพๆฃๆฅ็ญ็ฅๆฅๅฃ็ฑป,้ป่ฎคๅฎ็ฐ๏ผNoOpPing ๅณไธๆฃๆฅ
- ServerList<T extends Server>๏ผๆๅกๅฎไพๆธ
ๅ็ปดๆคๆบๅถๆฅๅฃ็ฑป๏ผ้ป่ฎคๅฎ็ฐConfigurationBasedServerList ๅฝๆดๅEureka็ๆ
ๅตไธ๏ผๅไฝฟ็จDiscoveryEnabledNIWSServerList็ฑป
- ServerListFilter<T extends Server>๏ผๆๅกๅฎไพ่ฟๆปค็ญ็ฅๆฅๅฃ็ฑป๏ผ้ป่ฎคๅฎ็ฐ๏ผZoneAffinityServerListFilter ๆ นๆฎๅบๅ่ฟๆปค๏ผ
- ILoadBalancer๏ผ่ด่ฝฝๅ่กกๅจๆฅๅฃ็ฑป๏ผ้ป่ฎคๅฎ็ฐ๏ผZoneAwareLoadBalancer ๅ
ทๅคๅบๅๆ็ฅ
## ๆฟๆข้ป่ฎค้
็ฝฎ
Ribbonๅๆถๆฏๆ้จๅ้ป่ฎค้
็ฝฎ็ๆฟๆข๏ผ่ฟไธบไฝฟ็จ้ๅฏนไธๅๅบๆฏ็ๅฎๅถๅๆนๆกๆไพไบๅฏ่ฝใ็ฎๅ็่ฏๆฏๆไธค็งๆนๅผ็ๆฟๆข๏ผๆๅช็ฅ้่ฟไธค็ง๏ผใ
- ๅๅปบๅฎไพ่ฆ็้ป่ฎคๅฎ็ฐ
- ้
็ฝฎๆไปถ้
็ฝฎ
### ๅๅปบๅฎไพ่ฆ็้ป่ฎคๅฎ็ฐ
ไพ๏ผๅฐ้ป่ฎค็่ด่ฝฝๅ่กก็ญ็ฅๆฟๆขๆ่ชๅทฑ่ชๅฎไน็็ญ็ฅใ
```java
@Bean
public IRule myRule() {
return new MyRule();
}
```
### ้
็ฝฎๆไปถ้
็ฝฎ
้่ฟไฝฟ็จ<service-name>.ribbon.<key> = value ๆนๅผ
ๅจapplication.propertiesไธญๆทปๅ ๅฆไธไปฃ็ ๏ผๅณๅฏไปฅๅฐ้ป่ฎค็IPing็ญ็ฅๆฟๆขๆ่ชๅทฑ่ชๅฎไน็็ญ็ฅใ
```properties
### ๆฉๅฑ IPing ๅฎ็ฐ
user-service-provider.ribbon.NFLoadBalancerPingClassName = \
com.xxxx.demo.user.ribbon.client.ping.MyPing
```
MyPingไปฃ็ ๏ผๅฐ้ฉฌๅฅๅพฎๆๅกๅฎๆ็๏ผ๏ผ
```java
public class MyPing implements IPing {
@Override
public boolean isAlive(Server server) {
String host = server.getHost();
int port = server.getPort();
// /health endpoint
// ้่ฟ Spring ็ปไปถๆฅๅฎ็ฐURL ๆผ่ฃ
UriComponentsBuilder builder = UriComponentsBuilder.newInstance();
builder.scheme("http");
builder.host(host);
builder.port(port);
builder.path("/actuator/health");
URI uri = builder.build().toUri();
RestTemplate restTemplate = new RestTemplate();
ResponseEntity responseEntity = restTemplate.getForEntity(uri, String.class);
// ๅฝๅๅบ็ถๆ็ญไบ 200 ๆถ๏ผ่ฟๅ true ๏ผๅฆๅ false
return HttpStatus.OK.equals(responseEntity.getStatusCode());
}
}
```
MyRuleไปฃ็ ๏ผๅฐ้ฉฌๅฅๅพฎๆๅกๅฎๆ็๏ผ๏ผ
```java
public class MyRule extends AbstractLoadBalancerRule {
@Override
public void initWithNiwsConfig(IClientConfig clientConfig) {
}
@Override
public Server choose(Object key) {
ILoadBalancer loadBalancer = getLoadBalancer();
//่ทๅๆๆๅฏ่พพๆๅกๅจๅ่กจ
List<Server> servers = loadBalancer.getReachableServers();
if (servers.isEmpty()) {
return null;
}
// ๆฐธ่ฟ้ๆฉๆๅไธๅฐๅฏ่พพๆๅกๅจ
Server targetServer = servers.get(servers.size() - 1);
return targetServer;
}
}
```
# ๆป็ป๏ผ
้่ฟๆฌๆฌกๅฏนRibbonๆบ็ ็ไธไธช็ฎๅๅๆข๏ผๆ
ขๆ
ขๆ็ฝไธไธชไผ็ง็ๆกๆถ็ไผ็งไนๅคไบ๏ผๅ็็่ชๅทฑไนๅๅ็ไปฃ็ ๅฐฑๆไบ้พไปฅ็ด่งไบ๏ผไธไธชๆกๆถ็่ฎพ่ฎกๅพๅพไธไป
ไป
ๆฏๅฎ็ฐไบๆไบๅ่ฝ๏ผไนๅๆถ่่ๅฐไบๅ็งไธๅ็ไฝฟ็จๅบๆฏ๏ผ่ฟๆ ทๅฏไปฅไฟ่ฏๆกๆถๅฏไปฅ่ไปปๅคงๅคๆฐ็ฎๅ็้กน็ฎๅๅคงๅ้กน็ฎใๅๆถๆกๆถๅ
้จๆๅพๅคๅฎ็ฐ้ฝๅพ้ซๆ๏ผๅพๅฐๅบ็ฐๆไปไนๆๅบฆไธๅ็็ๅฐๆน๏ผๅๆถไปฃ็ ๅค็จๆงไนๅพ้ซ๏ผ็ไผผๅ ๅไธ็พไธช็ฑปๅฎๅ่่ดฃๅๆ๏ผไบไบๆๆก๏ผๅจไฟ่ฏๅ่ฝ็ๆ
ๅตไธๅๆถๅๆ่ฏๅฅฝ็ๆฉๅฑๆงใๅ ไธบๅนณๅธธๅญฆไธ็นๅฟ๏ผไธป่ฆๆฏๆ่ฟ็ฑ็ฉๅฟ๏ผ๏ผๅป่ฆๅญฆไน ๏ผๆๆซๅ
จ้ ๆฐด่ฟๅป๏ผ๏ผๆไปฅRibbon่ฟ็ฏ็ฃ็ฃ็ป็ปๅไบๆๅไธชๅคๆ็ๆถ้ดใๅฅฝๅจ่ชๅทฑ็ปไบๅๆๆๅฎ็ป็ๅฎไบใๅ้ข็ๆ็ฎๅข๏ผๅฐไผ้็ปญๆ่ชๅทฑๅญฆไน javaๅพฎๆๅก็็ฌ่ฎฐๆด็ๅฅฝๅผๆบ่ณๆฌไบบ็githubไธ๏ผๅธๆๅฏไปฅๅธฎๅฉๅฐไธไบๅๅผๅงๅ
ฅ้จ็ๅฐไผไผดไปฌ๏ผไน้ชไธไบstar๏ผๆป็จฝ๏ผ๏ผๆๅ๏ผๆๆฏ้ฉๆฐ๏ผ่ฎก็ฎๆบๅฐ็ฝ๏ผๆฌ็งๅจ่ฏป๏ผๆๅๆฌขๅฑ๏ผ่ทณ...
<file_sep># ไธไธชJavaๅฏน่ฑก็ๆญปไบก่ฏๆ
## ๅ่จ:
**็็ๅฏน็ซ้ขไธๆฏๆญปไบก๏ผ่ๆฏ้ๅฟใ**
**็็ๅฏน็ซ้ขไธๆฏๆญปไบก๏ผ่ๆฏ้ๅฟใ**
**็็ๅฏน็ซ้ขไธๆฏๆญปไบก๏ผ่ๆฏ้ๅฟใ**
้่ฆ็ไบๆ
่ฏดไธ้๏ผๅคงๅฎถ่ฏทไธๅฎ่ฆๅฅฝๅฅฝ่ฎฐไฝ่ฟๅฅ่ฏ๏ผ่ฟๅฅ่ฏๆฏๆไปฌๆด็ฏๆ็ซ ็็ฒพ้ซๆๅจใ
ๆไฟกไฝ ไธช้ฌผ๏ผไฝ ไธชไธ็ไธๆๅธ
ๆๆบๆบๅๆข็ๆ ไธด้ฃ้ฃๆตๅๅฅ็ๅธ
ๅฅๅๅพๅพใ
ไธไฟก๏ผ่ตฐ็็ง๏ผๆฏไธไธๅป็ฎๆ่พใ
## ๆฆๅฟตๅๅค:
VM ๆดๆๅ
จ็งฐไธบVirtual Machine ๏ผไธญๆไธ่ฌ่ขซ่ฏไธบ่ๆๆบ๏ผ่ๆๆบไธ่ฌ็จๆฅๆ้่ฟ่ฝฏไปถๆจกๆ็ๅ
ทๆๅฎๆด็กฌไปถ็ณป็ปๅ่ฝ็ใ่ฟ่กๅจไธไธชๅฎๅ
จ้็ฆป็ฏๅขไธญ็ๅฎๆด่ฎก็ฎๆบ็ณป็ปใ
่ JVMๅๆฏไปฃ่กจjava่ฏญ่จ็่ๆๆบ๏ผๆดๆๅ
จ็งฐ:Java Virtual Machineใ
ไธ็ไธ็ฌฌไธๆฌพๅ็จjava่ๆๆบๆฏSunๅ
ฌๅธ1996ๅนดๅจjdk1.0ไธญๅๅธ็Sun Classic VM๏ผๅพๆฉไนๅSun Classic VMๅฐฑๅทฒ็ป่ขซๅบๅผๆไบ๏ผ็ฑHotSot VM่ๆๆบๆฅไปฃๆฟใ
## ๆฏ่็ฏ่:
ๆข็ถไฝ ๆฏ่ฆๅjvmๅ
ๅญๅๆถ็ณปๅ็ๅญฆไน ็ฌ่ฎฐ๏ผ้ฃๅ
ณjavaๅฏน่ฑกๆญปไบกๆไปไนๅ
ณ็ณป๏ผ
่ฏถ๏ผ่ฟไฝ ๅฐฑไธๅฏนไบ๏ผๆไน่ฝๆฒกๆๅ
ณ็ณปๅข๏ผjvmๅๆถ็ๆฏไปไน๏ผๆฏๅ
ๅญ๏ผๅ
ๅญ่ขซ่ฐๅ ็ๅข๏ผjavaๅฏน่ฑก(ไธป่ฆ)๏ผ้ฃๅฏน่ฑกไธๆญปๆไนๅๆถไปๅข๏ผ
ๅฏน่ฑกไธๆญปๆไนๅฐฑไธ่ฝๅๆถไบ๏ผ
ๆ ๆฏๅง๏ผๆๆฏๅง๏ผๆๆฏๅง๏ผๆไปฌๆjvm่ๆๆบๅจๅๅพๅๆถ่ฟ็จไธญ็่ง่ฒ็่งฃไธบๆไปฌ็ฅ่ฏไผ ่ฏดไธญ็้็็ท๏ผๆ็
งๅค่็ไผ ่ฏด๏ผไบบๅชๆๆญปไบไนๅ็ต้ญๆไผ่ขซๅๆถ็ปง็ปญๆ่๏ผไบบๆดป็ๅฐฑ็ฎๅๅบ็ฉไนไธ่ฝ็ดๆฅ่ฎฉไปๆ่ไบ๏ผๅฟ
้กป่ฆ็ญไปๆญปไบๆ่ก๏ผ่ไธ๏ผๅจไบบๆฒกๆญปไนๅ็ดๆฅๅๆถ่ฟไธชไบบ็็ต้ญๅฏ่ฝไผๅฏผ่ดไธไบๅพไธฅ้็้ฎ้ข๏ผๆฏๅฆไฝ ๅๆถไธช็พๅฝ็ๆไบบ็ฏ็็ต้ญ๏ผ้ฃ่ฏๅฎๅฏน่ฟไธชไธ็ไธไผไบง็ไปไน็นๅซๅคง็ๅฝฑๅ๏ผไฝๆฏไธไธไฝ ่ฆไธๅฐๅฟๆฝๅฐ็นๆๆฎไบ๏ผ้ฃๅฏ่ฝๅฐฑไผๅผ่ตทๅคงไนฑๅญใ
jvmไนๆฏ่ฟไน่่็๏ผไธไธไฝ ่ฟไธชๅฏน่ฑกๅซ็ๅฐๆนๆญฃ็จ็ๅข๏ผjvm็ดๆฅ็ปไปๅๆถไบ๏ผๅฐฑๆๅฏ่ฝ็ดๆฅๅฏผ่ดๆดไธชๅบ็จ็ๅดฉๆบใ
## ๅพฎๅงๅบ๏ผ
ๅคงๅฎถๅฅฝ๏ผๆๆฏไธไธชjavaๅฏน่ฑก๏ผๆๅซ้ฟๅใไธไธๆฒกๆณๅฐ็ๆฏ๏ผๆ็ฐๅจ็ซ็ถ่ฆ่ฏๆ่ชๅทฑๆญปไบใ
ไบๆ
ๆฏ่ฟๆ ท็๏ผๆๆฏไธไธชๅบๆๅฏน่ฑก๏ผๅฝไธปไบบๆๆๅ้ ๅบๆฅๆถ๏ผๆๆปกไปฅไธบ่ชๅทฑไผๅ
่ไธไธๅคงๆไฝไธบๆไธบjavaๅฏน่ฑกไน็๏ผๅฏๆฏ่ฟ่ดงๆๆnewๅบๆฅไนๅไปๅจ็็ซ็ถๆๆ็ปๅฟไบ๏ผไปๅๅ
ถไป็ๅฏน่ฑกๅฌๆๆ้น๏ผๆๅดๅช่ฝๅจ่ง่ฝ้ไผคๅฟๅ็ฌ๏ผๆๆ่งๆดไธช่ฟ่ก็ฏๅข็ๅคฉ็ฉบ้ฝๅๆไบ็ฐ่ฒ๏ผๆไธๆณๆดปไบ๏ผๆๅคช้พไบ๏ผไบๆฏๆ่ทๅฐ**java่ๆๆบๅ
ๅญๅๆถๅฑ**ๆณ่ฏทๅฏไปฅๅฐๆๅๆถๆ๏ผๅๆ่ฟ็งๅบๆๆฒกไบบๅจไน็ๅฏน่ฑก็็ๅฐฑๆฏๆดป็ๆตช่ดนๅ
ๅญไบใ
ๅฏๆฏjava่ๆๆบๅ
ๅญๅๆถๅฑๆฎๅฟๅฐๆ็ปไบๆ๏ผ่ฟ่ฎฉๆๅชๅๅฟซๅชๅ็ๅป๏ผๅฝ็ถๆๅนถไธๆ็ฎไธบๆญค้็ผฉ๏ผๅจๆ็ๅจ้ผๅฉ่ฏฑ(่ฆ่ฆๅๆฑ)ไธ๏ผjava่ๆๆบๅ
ๅญๅๆถๅฑ็ปไบๅ่ฏไบๆไบๆ
็็็ธใ
ๅพ้ๆพ๏ผ้ฟๅๅ
็๏ผ่ฟไธชไธ็ไธ่ฟๆไบบไป็ถ่ฎฐๅพไฝ ๏ผๆไปฅๆไปฌไธ่ฝๆไฝ ๅๆถๆใ
่ฟๆไบบ่ฎฐๅพ..่ฎฐๅพๆ๏ผ๏ผๅ็ผ้ช็็ๆณช่ฑ๏ผ
ๅฌๅฎ้ฟๅๅฑ้ข ๅฑ้ข ่ฟ็ๆญ็งงๆญ็้ญ้ฌผ็ๆญฅไผๅๅปไบใ๏ผๅฐผ็๏ผๅๆ่ฟๆณ่ชๆๅข๏ผ่ๆๅข๏ผๅ่ฟไนๅฟซ๏ผ
ๅฝ็ถ๏ผjava่ๆๆบๅ
ๅญๅๆถๅฑ่ฏๅฎไธๆฏ้้ไพฟไพฟๅฐฑๆ้ฟๅ่ฎคๅฎๆญปไบก็๏ผ็ปๅ่ฟๅ ๅๅนด็ๅๅฑ๏ผ่ฏฅๆบๆ็ ๅไบไธๆฌพ**javaๅฏน่ฑก้ชๆญปไปช**๏ผๅ็ไธป่ฆๆฏๅบไบ**ๅผ็จ่ฎกๆฐ**ๅ**ๅฏ่พพๆงๅๆ็ฎๆณ**่ฟไธคไธช็ฎๆณ๏ผ้ฃไนไธ้ขๆไปฌๅฐฑไพๆฌกๆฅไป็ป่ฟไธค็ง็ฎๆณใ
## ๅผ็จ่ฎกๆฐ็ฎๆณ๏ผ
ๅฎๆนๆฆๅฟต:ๅผ็จ่ฎกๆฐ็ฎๆณๆฏ้่ฟๅคๆญๅฏน่ฑก็**ๅผ็จๆฐ้**ๆฅๅณๅฎๅฏน่ฑกๆฏๅฆๅฏไปฅ่ขซๅๆถใ
Hello h = new Hello(); ๅ
ถไธญhๅฐฑ็งฐไนไธบHelloๅฏน่ฑก็ๅผ็จ๏ผๅณๆไปฌๅฏไปฅ้่ฟhๆฅ่ฎฟ้ฎๅฐๆไปฌ็Helloๅฏน่ฑกใ
ๅจ่ฟ้ๆไปฌๅฏไปฅ็่งฃไธบ๏ผๅๅฆBๅฏน่ฑกไธญๅ
ๅซAๅฏน่ฑก็ๅผ็จ๏ผๅฐฑๆๅณ็Bๅฏน่ฑกๅAๅฏน่ฑกๆๆ่็ณป๏ผๅณBๅฏน่ฑก่ฎฐๅพAๅฏน่ฑกใๅฝBๅฏน่ฑกๅ ไธบไธไบๅๅ ๆฏๅฆๆๅคๆญปไบก๏ผ่ๅนด็ดๅ๏ผ้ฉๅฝๅถๅๅง็ญ๏ผไธ่ฎฐๅพAๅฏน่ฑก็ๅญๅจไบ๏ผๅๆไปฌ็งฐไนไธบB้ๅฟไบA๏ผๆ่ฏดๅ๏ผๆ่ฏๅฎๅฏไปฅๆฏๅฐ่ฟ้็ใ
ๆฏๅฝๆไธไธชๆฐ็ๅฏน่ฑกๅAๅฏน่ฑกไบง็่็ณปๆถ๏ผๅณๅผ็จAๅฏน่ฑก๏ผ้ฃไนAๅฏน่ฑก็ๅผ็จ่ฎกๆฐๅจๅฐฑ+1๏ผๅฆๆ่ฐไธๅฐๅฟๆAๅฏน่ฑก็ปๅฟไบ๏ผ ๅๆๅณ็ๅผ็จๅคฑๆไบ๏ผ้ฃไนAๅฏน่ฑก็ๅผ็จ่ฎกๆฐๅจๅฐฑ-1๏ผๅฝAๅฏน่ฑก็ๅผ็จ่ฎกๆฐๅจๅๆ0็ๆถๅ๏ผๆๅณ็่ๆๆบไธญๅทฒ็ปๆฒกๆไปปไฝๅฏน่ฑก่ฟไฟ็็Aๅฏน่ฑก็ๅผ็จไบ๏ผๅณ้คไบAๅฏน่ฑก่ชๅทฑ๏ผๆฒกๆๅฏน่ฑก่ฎฐๅพAๅฏน่ฑก็ๅญๅจไบ๏ผ่ฟไธชๆถๅAๅฏน่ฑกๅฐฑไผ่ขซๅคๅฎไธบๆญปไบก๏ผ่ขซๅ
ๅญๅๆถๆใ
่ฟไธชๆถๅๅฏ่ฝๆๅ่ฏ็ๅฐไผไผด้ฎไบ๏ผAๅฏน่ฑก้ฃไนๅฏ็ฑ๏ผไธบไปไน่ฆๅๆถๆๅฎๅข๏ผ็็ๅฎไธๅฅฝๅใ
็ฐๅจๆไปฌๅๅฝๅผ็จ็ๆฆๅฟต๏ผAๅฏน่ฑกๅผ็จ่ฎกๆฐๅจไธบ0ๆๅณ็ๅไนๆฒกๆไปปไฝไธไธชๅฏน่ฑกๅฏไปฅ่ฎฟ้ฎๅฐAๅฏน่ฑกไบ๏ผไพง้ขๅฐฑ่ฏดๆไบAๅฏน่ฑกๅไนไธ่ฝ่ขซไฝฟ็จ๏ผๅๆไบไธไธชๅฝปๅฝปๅบๅบ็ๅบๅฏน่ฑกใ
ๆไปฅ๏ผ**็็ๅฏน็ซ้ขไธๆฏๆญปไบก๏ผ่ๆฏ้ๅฟใ**
่ฟไนไธๆณ๏ผๅผ็จ่ฎกๆฐ็ฎๆณ็็กฎ่ฟไธ้๏ผ่ฟๆ ทๆญปไบก็ๅฏน่ฑก้ฝไผ่ขซๆญฃ็กฎ่ฏๅซๅบๆฅ๏ผไป่ๅๆถๆใ
ๅนด่ฝปไบบ๏ผไฝ ่ฟๆฏๆณ็ๅคช็ฎๅไบใไฝ ๅฟไบ่ฟไธชไธ็ไธๆๅฅ่ฉ็ๅญๅจไบๅ๏ผไธ็ไธ้ข่ฟๆฎตๅฏน่ฏ๏ผ
A๏ผๆ่ฏ
ๅไฝ ไปๅนด็งๅคด๏ผ
B๏ผ่ฏ
ๅๅ่ดช
A๏ผๆไนๅๅผน
B๏ผๆๅๅๅผน
ๆญคๅค็็ฅNไธชๅญใ
ๆฒกๅฎๆฒกไบ๏ผๆพๅจๅฏน่ฑกไนๆฏ่ฟๆ ท๏ผๅ ๅ
ฅAๅฏน่ฑกๅ
ๅซไบBๅฏน่ฑก็ๅผ็จ๏ผBๅฏน่ฑกๅๅ
ๅซไบAๅฏน่ฑก็ๅผ็จ๏ผๅ ไธบ็ธไบๅผ็จ๏ผไปไปฌ็ๅผ็จ่ฎกๆฐๅจ้ฝๆ ๆณไธบ0๏ผไนๅฐฑไธไผ่ขซๅๆถๆไบใ
**ๆไปฅๅผ็จ่ฎกๆฐๅจ็ฎๅไธปๆต็java่ๆๆบไธญ่ขซๅบๅผๆไบใ**
## ๅฏ่พพๆงๅๆ็ฎๆณ:
ๅฎๆนๆฆๅฟต๏ผๅฏ่พพๆงๅๆ็ฎๆณๆฏ้่ฟๅคๆญๅฏน่ฑก็ๅผ็จ้พๆฏๅฆๅฏ่พพๆฅๅณๅฎๅฏน่ฑกๆฏๅฆๅฏไปฅ่ขซๅๆถใ
ไปGC Rootsไฝไธบ่ตท็น๏ผๅไธๆ็ดขๅฎไปฌๅผ็จ็ๅฏน่ฑก๏ผๅฏไปฅ็ๆไธๆฃตๅผ็จๆ ๏ผๆ ็่็น่งไธบๅฏ่พพๅฏน่ฑก๏ผๅไน่งไธบไธๅฏ่พพใๅพ้ฟ่ฟๆ ท๏ผ

่ฟไธช็ฎๆณๅฐฑๅฅฝ็ฉๅคไบ๏ผๆไปฌๅฏไปฅๆ่ฟไธช็ฎๆณ็ไฝๆฏไธไธชๅทจๅคง็ไผ ้้ๅข๏ผ่GC Rootsๅฐฑๆฏ่ฟไธช้ๅข็ไผ ้ๅคดๅญ ๏ผ้ฃๅฎๆฏๆไนๅคๆญๅฏน่ฑกๆฏๅฆๆญปไบก็ๅข๏ผ
ๅฝ้่ฆๅ
ๅญๅๆถ็ๆถๅ๏ผ่ๆๆบไผๆฒฟ็ไผ ้ๅคดๅญๅพไธไพๆฌกๆ็ดขๅฎ็ไธ็บฟ๏ผๅฆๆ่ฟไธชๅฏน่ฑก่ฝ่ขซๆ็ดขๅฐ๏ผ้ฃไนๅฐฑๆๅณ็่ฟไธชๅฏน่ฑกๆฏๅจไผ ้็ป็ป้้ข็๏ผๆฏๅฆObject2 3 4 ้ฝๅจไผ ้้ๅข้้ข๏ผ่Object 5 6 7 ๅขใ
Object 5 6 7ๅฐฑๆฏ้ฃไบๆฒกๆ็ป็ป็้ไผ ้๏ผไผ ้้ๅขๆไนไผๅฎนๅฟ่ฟไบ้ไผ ้ๅญๅจๅข๏ผไบๆฏไปไปฌ้ฝ่ขซๅคๆญไธบๆญปไบกใ
ๆไปฅ๏ผ**็็ๅฏน็ซ้ขไธๆฏๆญปไบก๏ผ่ๆฏ้ๅฟใ**
่ Object 5 6 7 ่ฟไธไธชๅฏน่ฑก้ฝ่ขซ้ๅฟๆไบ๏ผๅ ไธบไปไปฌๆฒกๆ็ป็ป๏ผๅ ไธบๅคฑๅปไบๅ็ป็ป็่็ณป๏ผๆไปฅ็ป็ปไนๆฒกๆๅๆณๅทฎ้ฃไปไปฌ๏ผๅๆฅไปไปฌ็ไปทๅผ๏ผไบๆฏๅฎไปฌๅๆๅบๅฏน่ฑก่ขซๅๆถๆไบใ
ไนๅฐฑๆฏ่ฏดๅข๏ผๅจๅฏ่พพๆงๅๆ็ฎๆณไธญ๏ผๅฆๆไธไธชๅฏน่ฑกๆ ๆณ่ขซ่ๆๆบๆฒฟ็GC Rootsไพๆฌกๅไธๆ็ดขๅฐ๏ผ้ฃไน่ฟไธชๅฏน่ฑกๅฐฑๆฏไธๅฏ่พพ็๏ผๅ ไธบๆฒกๆไปปไฝไธๆก่ทฏ้ๅพ่ฟไธชๅฏน่ฑก๏ผ่ฟไธชๅฏน่ฑกๅฐฑๅๆฏๆตทไธ็ๅญคๅฒไธๆ ท๏ผๆๅๅช่ฝ่ขซjava่ๆๆบๅๆถใ
็็กฎไผๅฟๆๆพ๏ผ้ไพฟไฝ ไปฌๅๅผน๏ผๆฒกๆ็ป็ปไฝ ไปฌ้ฝ่ฆๅฎ่ใ
่GC Rootsไนไธๆฏ่ฐ้ฝ่ฝๅฝ็๏ผๅจ้ฟๆ็ๅฎ่ทตไธญ๏ผๅ็ฐๆๅ็ฑปๅฏน่ฑกๆฅๆๆไธบไผ ้ๅคดๅญ๏ผๅธ๏ผGc Roots็ๆฝ่ดจ๏ผไปไปฌๅๅซๆฏ๏ผ
- ่ๆๆบๆ ๏ผๆ ๅธงไธญ็ๆฌๅฐๅ้่กจ๏ผไธญ็ๅผ็จๅฏน่ฑกใ
- ๆนๆณๅบไธญ็็ฑป้ๆๅฑๆงๅผ็จ็ๅฏน่ฑกใ
- ๆนๆณๅบไธญ็ๅธธ้ๅผ็จ็ๅฏน่ฑกใ
- ๆฌๅฐๆนๆณๆ ไธญJNI๏ผNativeๆนๆณ๏ผ็ๅผ็จๅฏน่ฑก
**ๆญฃๅ ไธบๅฏ่พพๆงๅๆๅจๅฎ้
ไฝฟ็จไธญ็ไผๅผ่กจ็ฐ๏ผๆไปฅๅพๅค็ฐไปฃ่ๆๆบ้ฝ้็จไบ่ฟไธๅฎ็ฐใ**
**็็ฑ็ๅฝ๏ผ่ฟ็ฆปไผ ้๏ผ็็ฑ็ๅฝ๏ผ่ฟ็ฆปไผ ้๏ผ็็ฑ็ๅฝ๏ผ่ฟ็ฆปไผ ้๏ผ**
ไธ้ขๅฐๆๆฏๆป็ป็ฏ่๏ผ
## ๆป็ป๏ผ
ๆฌ็ฏๆ็ซ ๆไปฌๅฏ่ฐๆฏ็จๅฐฝไบๅบ่ฏๆฅๅธฎๅฉๅๅผๅงๅญฆไน javaๆ่
jvm็ๆๅไปฌๅฝปๅบ็่งฃjvmๅคๆญjavaๅฏน่ฑกๆญปไบก็ไธค็ง็ฎๆณ๏ผๅๅญฆไน jvm็่ฟ็จไธญ๏ผๅ็ฐๅพๅคjvmไนฆ็ฑ๏ผๅๅฎข้ฝๅ็ๆฏ่พๅญฆๆฏ๏ผ่ฎฉๆฐๆไปฌๆ่ๅดๆญฅ๏ผๅฏผ่ดๅพๅคไบบ็ไบไธ้ไปฅไธบ่ชๅทฑๆไบ๏ผไฝๆฏ่ฟไบๅ ๅคฉไนๅๅๆณๅดๆฒกๆๅๆณๆณ่ตทๆฅ๏ผๆ นๆฌๅๅ ่ฟๆฏๅจไบๅนถๆฒกๆๅฝปๅบ็็่งฃ่ฟไบ็ฅ่ฏ๏ผไธบไบๅธฎๅฉไธไบๆๅๆดๅฅฝ็็่งฃjvm่ๆๆบ๏ผๆไปฅๆๆไบjvmๅญฆไน ็ฌ่ฎฐ็ณปๅ๏ผๅๆ ท็๏ผๆฌ็ณปๅ็ฌ่ฎฐไผๅผๆบ่ณgithub๏ผๅนถไฟๆๆดๆฐใ
ๆๆฏ้ฉๆฐ๏ผๆฌข่ฟๅคงๅฎถๅ
ณๆณจๆใๆไปฌไธ็ฏๆ็ซ ๅ่งใ
<file_sep>
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/testdatasource1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.primary.username=root
spring.datasource.primary.password=<PASSWORD>
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/testdatasource2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.secondary.username=root
spring.datasource.secondary.password=<PASSWORD>
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
<file_sep># ๅ็ปๅ็ซฏ็Nginxๅ็บงๅ
ฅ้จๆ็จ:ๅฎๆ็ฏ
ๅจไธไธ็ฏ็ๆ็ซ [ๅ็ปๅ็ซฏ็Nginxๅ็บงๅ
ฅ้จๆ็จ:ๅบ็ก็ฏ](https://juejin.im/post/5da41d41f265da5bb86ac720)ไธญ๏ผๆไปฌไธป่ฆ่ฏดไบNginxๆฏไปไน๏ผ่ฝๅไปไน๏ผไปฅๅNginxๆ้่ฆ็ๅไธชๅบๆฌๆฆๅฟต๏ผๅๅซๆฏ **ๆญฃๅไปฃ็**, **ๅๅไปฃ็๏ผ่ด่ฝฝๅ่กก๏ผไปฅๅๅจ้ๅ็ฆป** ใ
ๆฌ็ซ ไฝไธบๅฎๆ็ฏ๏ผๅฐไปๅฎ้
็ๅฝไปค่กๅบๅ๏ผ้่ฟๅฎ่ฃ
๏ผๅฏๅจ๏ผ้
็ฝฎNginxๆฅ้ๆธ่ฎค่ฏๅไฝฟ็จNginx๏ผๅนถ่ฝๅค่ชๅทฑๅฎ็ฐไธไบ็ฎๅ็ๅๅไปฃ็๏ผ่ด่ฝฝๅ่กก็้
็ฝฎใ
ไธๅบ่ฏ๏ผ็ดๆฅไธๅนฒ่ดงใ
## Nginxๅฎ่ฃ
๏ผ
Nginx็ๅฎ่ฃ
่ฟๆฏๆฏ่พๅฎนๆ็๏ผๆ็ฆป็บฟๅฎ่ฃ
๏ผๅจ็บฟๅฎ่ฃ
ๅค็งๅฎ่ฃ
ๆนๅผ๏ผ่ฟ้ๆๅช่ฏดๆ็ฎๅ็ไธ็ง๏ผๆๅผๆไปฌ็ๅฝไปค่ก็ป็ซฏ๏ผ็ดๆฅ่พๅ
ฅyumๅฝไปค่ฟ่กๅฎ่ฃ
```shell
yum install -y nginx
```
ๅฝ็ป็ซฏๆพ็คบๅบComplete!ๅญๆ ทๆถ๏ผๅไปฃ่กจๆไปฌ็Nginxๅทฒ็ปๅฎ่ฃ
ๆๅไบใ
ๆฅ็Nginx็ๆฌ๏ผ
```shell
nginx -v
#ๅจ่ฟ้ๆๅฎ่ฃ
็ๆฏ1.16.1็ๆฌ็nginx
```
## Nginxๅบๆฌๆไฝ:
ๅๆไปฌไนๅ็dockerไธๆ ท๏ผnginxไนๆไธไบๅ
ๆฌๆๅก็ๅฏๅจ๏ผๅๆญข๏ผ้่ฝฝ็ญๅบๆฌๆไฝใ
ๅฏๅจnginx๏ผ
```shell
##ๅจcentos7+ ๅฏๅจnginxๆๅก
systemctl start nginx.service
#centos6+ ไธๅฏๅจnginxๆๅก
service nginx start
#ๆ๏ผ็ฎๅ็ฒๆดไธๅฅ
nginx
```
ๅๆญขnginx:
```shell
##ๅจcentos7+ ๅๆญขnginxๆๅก
systemctl stop nginx.service
#centos6+ ไธๅๆญขnginxๆๅก
service nginx stop
#็ฒ้ฒ็ๅๆญข๏ผไธ็ญไบ๏ผไธๅนฒไบ๏ผๅฐฑ็ฎ่ฏทๆฑๆฅไบๆไนไธๆฅไบใ
nginx -s stop
##ไผ้
็ๅๆญข๏ผNginxๅจ้ๅบๅๅฎๆๅทฒ็ปๆฅๅ็่ฟๆฅ่ฏทๆฑใ
nginx -s quit
```
้ๅฏnginx๏ผ
ๅฝๆไปฌไฟฎๆนไบnginx็ๆไบ้
็ฝฎ๏ผไธบไบไฝฟ้
็ฝฎ็ๆ๏ผๆไปฌๅพๅพ้่ฆ้ๅฏnginx๏ผๅๆ ท็๏ผlinuxไธไพ็ถๆไธค็งๆนๅผๆฅ้ๅฏๆไปฌ็nginxๆๅก:
```shell
##ๅจcentos7+ ้ๅฏnginxๆๅก
systemctl restart nginx.service
#centos6+ ไธ้ๅฏnginxๆๅก
service nginx restart
#ไฝฟ็จnginxๅฝไปคๅๆญข๏ผๆจ่่ฟไธช
nginx -s reload
```
่ๅ
ทไฝไฝฟ็จnginxๅ็็nginx -s ๆไฝ่ฟๆฏlinuxๆไพ็systemctl ๏ผ่ฟไธชไธป่ฆ็ไธชไบบๅๅฅฝ๏ผๅฎ้
ไธค่
็ๅ่ฝๆฏๅทฎไธๅค็๏ผๅนถๆฒกๆไปไนๆๆพ็ไธๅใ
ๅ
ถไปๅฝไปค๏ผ
ๆฅ็้
็ฝฎๆไปถๆฏๅฆok๏ผ
```shell
#ๅฆๆ้
็ฝฎๆไปถๆ้ฎ้ข็่ฏไผๆพ็คบfailed๏ผๅฆๆๆฒกๅพ้ฎ้ข็่ฏ๏ผไผๆพ็คบsuccessful
nginx -t
```
ๆพ็คบๅธฎๅฉไฟกๆฏ:
```shell
nginx -h
#ๆ่
nginx -?
```
## Nginx้
็ฝฎ๏ผ
nginxๆฌ่บซไฝไธบไธไธชๅฎๆๅบฆ้ๅธธ้ซ็่ด่ฝฝๅ่กกๆกๆถ๏ผๅๅพๅคๆ็็ๅผๆบๆกๆถไธๆ ท๏ผๅคงๅคๆฐๅ่ฝ้ฝๅฏไปฅ้่ฟไฟฎๆน้
็ฝฎๆไปถๆฅๅฎๆ๏ผไฝฟ็จ่
ๅช้่ฆ็ฎๅไฟฎๆนไธไธnginx้
็ฝฎๆไปถ๏ผไพฟๅฏไปฅ้ๅธธ่ฝปๆพ็ๅฎ็ฐๆฏๅฆๅๅไปฃ็๏ผ่ด่ฝฝๅ่กก่ฟไบๅธธ็จ็ๅ่ฝ๏ผๅๆ ท็๏ผๅๅ
ถไปๅผๆบๆกๆถๆฏๅฆtomcatไธๆ ท๏ผnginx้
็ฝฎๆไปถไน้ตๅพช็็ธๅบ็ๆ ผๅผ่ง่๏ผๅนถไธ่ฝไธ้กฟไนฑ้
๏ผๅจ่ฎฒ่งฃๅฆไฝไฝฟ็จnginxๅฎ็ฐๅๅไปฃ็๏ผ่ด่ฝฝๅ่กก็ญ่ฟไบๅ่ฝ็้
็ฝฎๅ๏ผๆไปฌ้่ฆๅ
ไบ่งฃไธไธnginx้
็ฝฎๆไปถ็็ปๆใ
ๆข็ถ่ฆไบ่งฃnginx็้
็ฝฎๆไปถ๏ผ้ฃๆๆปๅพ็ฅ้nginx้
็ฝฎๆไปถๅจๅชๅ๏ผnginx้
็ฝฎๆไปถ้ป่ฎค้ฝๆพๅจnginxๅฎ่ฃ
่ทฏๅพไธ็conf็ฎๅฝ๏ผ่ไธป้
็ฝฎๆไปถnginx.conf่ช็ถไนๅจ่ฟ้้ข๏ผๆไปฌไธ้ข็ๆไฝๅ ไน้ฝๆฏๅฏนnginx.conf่ฟไธช้
็ฝฎๆไปถ่ฟ่กไฟฎๆนใ
ๅฏๆฏ๏ผๆๆไน็ฅ้ๆnginx่ฃ
ๅชไบ๏ผๆ่ฆๆฏไธ็ฅ้nginx่ฃ
ๅชไบๅๅ๏ผ
่ฟไธช๏ผ็ปๅฟ็ๆๅไปฌๅฏ่ฝไผๅ็ฐ๏ผ่ฟ่กnginx -tๅฝไปค๏ผไธ้ข้คไบ็ปๅบnginx้
็ฝฎๆไปถๆฏๅฆOKๅค๏ผๅๆถไนๅ
ๆฌไบ้
็ฝฎๆไปถ็่ทฏๅพใ่ฏบ๏ผๅฐฑๆฏ่ฟไธช
```shell
[root@izuf61d3ovm5vx1kknakwrz ~]# nginx -t
nginx: the configuration file /etc/nginx/nginx.conf syntax is ok
nginx: configuration file /etc/nginx/nginx.conf test is successful
```
ไฝฟ็จvimๆๅผ่ฏฅ้
็ฝฎๆไปถ๏ผๆไปฌไธๆข็ฉถ็ซ๏ผไธๅ็ๆฌ็้
็ฝฎๆไปถๅฏ่ฝ็จๆไธๅ๏ผๆ็้
็ฝฎๆไปถๅ
ๅฎนๅฆไธ๏ผ
```shell
# For more information on configuration, see:
# * Official English Documentation: http://nginx.org/en/docs/
# * Official Russian Documentation: http://nginx.org/ru/docs/
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
events {
worker_connections 1024;
}
http {
log_format main '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
access_log /var/log/nginx/access.log main;
sendfile on;
tcp_nopush on;
tcp_nodelay on;
keepalive_timeout 65;
types_hash_max_size 2048;
include /etc/nginx/mime.types;
default_type application/octet-stream;
# Load modular configuration files from the /etc/nginx/conf.d directory.
# See http://nginx.org/en/docs/ngx_core_module.html#include
# for more information.
include /etc/nginx/conf.d/*.conf;
server {
listen 80 default_server;
listen [::]:80 default_server;
server_name _;
root /usr/share/nginx/html;
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
```
? ๏ผ ?
่ฟไธๅ ้ฝๆฏๅฅ็ฉๆer๏ผๅฎๅ
จๆฒกๆๅคด็ปชๅ
ๆฒกๅ
ณ็ณป๏ผไธ้ขๆไปฌๅฐฑๆฅ่ฏฆ็ปๅๆไธไธnginx.conf่ฟไธชๆไปถไธญ็ๅ
ๅฎนใ
ๆ็
งๅ่ฝๅๅ๏ผๆไปฌ้ๅธธๅฐnginx้
็ฝฎๆไปถๅไธบไธๅคงๅ๏ผ**ๅ
จๅฑๅ๏ผeventsๅ๏ผhttpๅ**ใ
### ็ฌฌไธ้จๅ๏ผๅ
จๅฑๅ
้ฆๅ
ๆ ๅ
ฅ็ผๅธ็่ฟไธๅ ๏ผ
```shell
user nginx;
worker_processes auto;
error_log /var/log/nginx/error.log;
pid /run/nginx.pid;
# Load dynamic modules. See /usr/share/doc/nginx/README.dynamic.
include /usr/share/nginx/modules/*.conf;
```
ๆไปฌ็งฐไนไธบ**ๅ
จๅฑๅ**๏ผ็ฅ่ฏ็นๅๆๅไปฌ๏ผ่ฆ่ฎฐไฝ๏ผ่ฟ้ๅข๏ผไธป่ฆไผ่ฎพ็ฝฎไธไบๅฝฑๅ nginx ๆๅกๅจๆดไฝ่ฟ่ก็้
็ฝฎๆไปค๏ผไธป่ฆๅ
ๆฌ้
็ฝฎ่ฟ่ก Nginx ๆๅกๅจ็็จๆท๏ผ็ป๏ผใๅ
่ฎธ็ๆ็ worker process ๆฐ๏ผ่ฟ็จ PID ๅญๆพ่ทฏๅพใๆฅๅฟๅญๆพ่ทฏๅพๅ็ฑปๅไปฅๅ้
็ฝฎๆไปถ็ๅผๅ
ฅ็ญใ
ๆฏๅฆ worker_processes auto๏ผ ่ฟไธ่ก๏ผworker_processes ๅผ่ถๅคง๏ผๆไปฌnginxๅฏๆฏๆ็ๅนถๅๆฐ้ๅฐฑ่ถๅค๏ผๅพๅคไบบๆณ่ฟไธๅฐฑ็ฝไบๅ๏ผๆ่ฎพ็ฝฎๆๆญฃๆ ็ฉท๏ผๆ ้ๅนถๅflag่พพๆ๏ผ็งๆ้ฎ้ข่ฝปๆพ่งฃๅณ๏ผ่ฟไธช๏ผๅ่ชๅทฑๆๅกๅจ็กฌไปถ้ๅถ็๏ผไธ่ฝไนฑๆฅใ
### ็ฌฌไบ้จๅ๏ผevents ๅ๏ผ
```shell
events {
worker_connections 1024;
}
```
่ฟไธๅ ๏ผๅฐฑๆฏๆไปฌ้
็ฝฎๆไปถ็็ฌฌไบ้จๅ๏ผ**events ๅ**
่ตทๅๅญ่ฟไน้ๆ็ไน๏ผ้ฃ็ฌฌไธ้จๅๆฏไธๆฏๅซhttpๅ๏ผ
wc๏ผ่ฟไฝ ้ฝ็ฅ้๏ผๆฏ็
events ๅๆถๅ็ๆไปคไธป่ฆๅฝฑๅ Nginx ๆๅกๅจไธ็จๆท็็ฝ็ป่ฟๆฅ๏ผๅธธ็จ็่ฎพ็ฝฎๅ
ๆฌๆฏๅฆๅผๅฏๅฏนๅค work process
ไธ็็ฝ็ป่ฟๆฅ่ฟ่กๅบๅๅ๏ผๆฏๅฆๅ
่ฎธๅๆถๆฅๆถๅคไธช็ฝ็ป่ฟๆฅ๏ผ้ๅๅช็งไบไปถ้ฉฑๅจๆจกๅๆฅๅค็่ฟๆฅ่ฏทๆฑ๏ผๆฏไธช word
process ๅฏไปฅๅๆถๆฏๆ็ๆๅคง่ฟๆฅๆฐ็ญใ
### ็ฌฌไธ้จๅ๏ผhttpๅ๏ผ
ๅ
ๅฎนๅคชๅค๏ผ็ฅ
```shell
http {
server {
}
}
```
> ๆณจๆ๏ผ
>
> httpๆฏไธไธชๅคงๅ๏ผ้้ขไนๅฏไปฅๅ
ๆฌๅพๅคๅฐๅ๏ผๆฏๅฆhttpๅ
จๅฑๅ๏ผserverๅ็ญใ
http ๅ
จๅฑๅ้
็ฝฎ็ๆไปคๅ
ๆฌๆไปถๅผๅ
ฅใMIME-TYPE ๅฎไนใๆฅๅฟ่ชๅฎไนใ่ฟๆฅ่ถ
ๆถๆถ้ดใๅ้พๆฅ่ฏทๆฑๆฐไธ้็ญใ
่httpๅไธญ็serverๅๅ็ธๅฝไบไธไธช่ๆไธปๆบ๏ผไธไธชhttpๅๅฏไปฅๆฅๆๅคไธชserverๅใ
serverๅๅๅ
ๆฌ**ๅ
จๅฑserver**ๅ๏ผๅ**location**ๅใ
ๅ
จๅฑserverๅไธป่ฆๅ
ๆฌไบๆฌ่ๆๆบไธปๆบ็็ๅฌ้
็ฝฎๅๆฌ่ๆไธปๆบ็ๅ็งฐๆ IP ้
็ฝฎ
locationๅๅ็จๆฅๅฏน่ๆไธปๆบๅ็งฐไนๅค็ๅญ็ฌฆไธฒ่ฟ่กๅน้
๏ผๅฏน็นๅฎ็่ฏทๆฑ่ฟ่กๅค็ใๅฐๅๅฎๅใๆฐๆฎ็ผ
ๅญๅๅบ็ญๆงๅถ็ญๅ่ฝ๏ผ่ฟๆ่ฎธๅค็ฌฌไธๆนๆจกๅ็้
็ฝฎไนๅจ่ฟ้่ฟ่กใๆฏๅฆ๏ผๅฏน/usr็ธๅ
ณ็่ฏทๆฑไบค็ป8080ๆฅๅค็๏ผ/adminๅ่พ็ป8081ๅค็ใ
่ฏดไบ่ฟไนๅค๏ผๆ่ฟๆฏไธๆฏ็นๅซ็่งฃๅๅ๏ผ้ฎ้ขไธๅคง๏ผๆฅไธๆฅๆไปฌ้่ฟๅ ไธชๅฎไพๆฅๅธฎๅฉๅคงๅฎถๆดๅฅฝ็็่งฃ่ฟไบ้
็ฝฎๅจๅฎ้
ไธญๆๅๆฅ็ไฝ็จใ
## Nginx้
็ฝฎๅฎๆ:
ๆฅไธๆฅๆไปฌๅฐ้่ฟๅฏนnginx้
็ฝฎๆไปถ็ไฟฎๆนๆฅๅฎๆๅๅไปฃ็๏ผ่ด่ฝฝๅ่กก๏ผๅจ้ๅ็ฆป็็ฎๅ้
็ฝฎใ
### nginx้
็ฝฎๅๅไปฃ็๏ผ
ๆๅ็ฐๅพๅคๆ็จ่ฏดnginx้
็ฝฎๅๅไปฃ็็ๆถๅไธๆฅๅฐฑๆนhostๆไปถ๏ผ่ฟ้็่ฏ๏ผๅ ไธบไธไธ็ฏๆ็ซ ๆไปฌๆๆป็ป่ฟๅๅไปฃ็็็ฒพ้ซ๏ผไนๅฐฑๆฏ๏ผ
**ๅๅไปฃ็ๆๅกๅจๅ็ฎๆ ๆๅกๅจๅฏนๅคๅฐฑๆฏไธไธชๆๅกๅจ๏ผๆด้ฒ็ๆฏไปฃ็ๆๅกๅจๅฐๅ๏ผ้่ไบ็ๅฎๆๅกๅจ IP ๅฐๅใ**
ๆไปฅๆฅไธๆฅๆไปฌ้่ฟไธไธชๅฐๆ ๅญ๏ผๅฝๆไปฌ่ฎฟ้ฎๆๅกๅจ็ๆถๅ๏ผ็ฑไบๆ็ๆๅกๅจๆฒกๅคๆก๏ผ้ฟ้ไบ้ป่ฎค80็ซฏๅฃๆฒกๅผ๏ผๆไปฅ่ฟ้ๆไปฌ่ฎพ็ฝฎๅฏนๅคๆๅก็็ซฏๅฃไธบ8888๏ผ**ๅฝๆไปฌ่ฎฟ้ฎ8888็ซฏๅฃ็ๆถๅ๏ผๅฎ้
ไธๆฏ่ทณ่ฝฌๅฐ8080็ซฏๅฃ็ใ**
้ฆๅ
ๆไปฌ็จdockerๅฏๅจไธไธชtomcatๅฎนๅจ๏ผ็ถๅ้
็ฝฎ็ซฏๅฃๆ ๅฐไธบ8080ใ
็ญ็ญ๏ผไธไผdockerๆไนๅ๏ผไธไผdocker็่ฏ๏ผๅฏไปฅ็้ฉๆฐ**ๆๆฐ็dockerๅ็บงๅ
ฅ้จๆ็จ๏ผๆป็จฝ๏ผ**
ๅฆๆๅฏนdockerไธๆฏๅพไบ่งฃ็่ฏ๏ผๅฏไปฅไฝฟ็จไผ ็ป็linuxไธ่ฟ่กtomcat๏ผ้็ๆฏไธๆ ท็ใ
็ถๅไฟฎๆนๆไปฌ็้
็ฝฎๆไปถnginx.conf้้ข็serverๅ๏ผไฟฎๆนไนๅ็ๅ
ๅฎนๅฆไธ๏ผ
```shell
server {
listen 8888 ; ##่ฎพ็ฝฎๆไปฌnginx็ๅฌ็ซฏๅฃไธบ8888
server_name [ๆๅกๅจ็ipๅฐๅ];
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
proxy_pass http://127.0.0.1:8080; ##้่ฆไปฃ็็ๆๅกๅจๅฐๅ
index index.html;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
```
็ถๅๅจๆต่งๅจไธญ่พๅ
ฅ๏ผๆๅกๅจip:8888 ๅ็ฐๆต่งๅจๆพ็คบๅบๆฅไบ8080็ซฏๅฃtomcat็ๆฌข่ฟ็้ข๏ผไป่ๅฎ็ฐไบ้่็ๅฎๆๅกๅจๅฐๅ่ฟๆ ทไธไธชๅๅไปฃ็็่ฆๆฑใ
ๅฆ๏ผ็็ๅฅฝ็ฅๅฅๅฆ๏ผ้ฃ๏ผๆไนๅ็ปๅธธๆ็ๅฐ้ฃ็ง๏ผๅฐฑๆฏๅ็ง/image /video ไธๅ็้พๆฅๅฏนๅบ็ๆฏไธๅ็็ฝ็ซ๏ผ้ฃไนๆฏ่ฟไนๅ็ๅฏ๏ผ
่ชๆ๏ผ่ฟ้ๆไปฌๅๆฐๅปบไธไธชtomcatๅฎนๅจ๏ผ็ซฏๅฃไธบ8081๏ผๅๆถๆๅจๅฎนๅจไธญtomcat webapps็ฎๅฝๆฐๅปบไธไธชๆไปฌ่ชๅทฑ็็ฎๅฝ๏ผ่ฟ้ๅซhello๏ผ้้ขๆฐๅปบไธไธชhello.htmlๆไปถ๏ผๅ
ๅฎนไธบ<h1>I am hello<h1>
ๅๆถๆไปฌๅจ็ซฏๅฃไธบ8080็tomcatๅฎนๅจไธญ๏ผๅจwebappsๆฐๅปบๆไปฌ็ๆไปถๅฎถhi๏ผๅนถๆฐๅปบhi.htmlๆไปถ๏ผๅ
ๅฎนไธบ<h1>I am hi<h1>
ๅ๏ผ่ฟๆ ท็่ฏ้
็ฝฎๆฏไธๆฏๅพ้พๅ?
ไฝ ๆณๅคไบ๏ผๆฒ็ฎๅ็ใ
ไฟฎๆนๆไปฌ้
็ฝฎๆไปถไธญ็serverๅฟซ๏ผๅฆไธ๏ผ
```shell
server {
listen 8888 ; ##่ฎพ็ฝฎๆไปฌnginx็ๅฌ็ซฏๅฃไธบ8888
server_name [ๆๅกๅจ็ipๅฐๅ];
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location /hi/ {
proxy_pass http://127.0.0.1:8080; ##้่ฆไปฃ็็ๆๅกๅจๅฐๅ
index index.html;
}
location /hello/ {
proxy_pass http://127.0.0.1:8081; ##้่ฆไปฃ็็ๆๅกๅจๅฐๅ
index index.html;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
```
ๅจๆต่งๅจไธญ่พๅ
ฅ๏ผๆๅกๅจip:8888/hi/hi.html
ๆต่งๅจๆพ็คบ **I am hi** ๅฏนๅบๆๅกๅจ็ซฏๅฃไธบ 8080
ๅจๆต่งๅจไธญ่พๅ
ฅ๏ผๆๅกๅจip:8888/hello/hello.html
ๆต่งๅจๆพ็คบ **I am hello** ๅฏนๅบๆๅกๅจ็ซฏๅฃไธบ 8081
ไป่ๅฎ็ฐไบ้ๅฏนไธๅurl่ฏทๆฑๅๅ็ปไธๅๆๅกๅจ็ๅ่ฝ้
็ฝฎใ
ๅฐไพ ๏ผไธๆ
ข๏ผไฝ ๆฏไธๆฏๅฟไบไปไนไธ่ฅฟ๏ผlocation /hello/ ๆฏไปไนๆๆ๏ผๅช่ฝ่ฟไนๅไน๏ผ
ๅฝ็ถไธๆฏใๅญฆไผlocationๆไปคๅน้
่ทฏๅพ๏ผ้ไพฟๆขๅงฟๅฟ
**locationๆไปค่ฏดๆ:**
ๅ่ฝ๏ผ็จไบๅน้
URL
่ฏญๆณๅฆไธ๏ผ
```shell
1ใ= ๏ผ็จไบไธๅซๆญฃๅ่กจ่พพๅผ็ uri ๅ๏ผ่ฆๆฑ่ฏทๆฑๅญ็ฌฆไธฒไธ uri ไธฅๆ ผๅน้
๏ผๅฆๆๅน้
ๆๅ๏ผๅฐฑๅๆญข็ปง็ปญๅไธๆ็ดขๅนถ็ซๅณๅค็่ฏฅ่ฏทๆฑใ
2ใ~๏ผ็จไบ่กจ็คบ uri ๅ
ๅซๆญฃๅ่กจ่พพๅผ๏ผๅนถไธๅบๅๅคงๅฐๅใ
3ใ~*๏ผ็จไบ่กจ็คบ uri ๅ
ๅซๆญฃๅ่กจ่พพๅผ๏ผๅนถไธไธๅบๅๅคงๅฐๅใ
4ใ^~๏ผ็จไบไธๅซๆญฃๅ่กจ่พพๅผ็ uri ๅ๏ผ่ฆๆฑ Nginx ๆๅกๅจๆพๅฐๆ ่ฏ uri ๅ่ฏทๆฑๅญ
็ฌฆไธฒๅน้
ๅบฆๆ้ซ็ location ๅ๏ผ็ซๅณไฝฟ็จๆญค location ๅค็่ฏทๆฑ๏ผ่ไธๅไฝฟ็จ location
ๅไธญ็ๆญฃๅ uri ๅ่ฏทๆฑๅญ็ฌฆไธฒๅๅน้
ใ
```
ๆณจๆ:
> ๅฆๆ uri ๅ
ๅซๆญฃๅ่กจ่พพๅผ๏ผๅๅฟ
้กป่ฆๆ ~ ๆ่
~* ๆ ่ฏใ
ๅฐ่ฟ้๏ผๅ
ณไบnginxๅฆไฝ็ฎๅ็้
็ฝฎไธไธชๅๅไปฃ็ๆๅกๅจๅฐฑๅคงๅๅๆไบ๏ผไธ้ขๆไปฌๆฅ่ฏดไธไธๆไนๅฎ็ฐ่ด่ฝฝๅ่กก็็ฎๅ้
็ฝฎใ
### nginx้
็ฝฎ่ด่ฝฝๅ่กก๏ผ
ๅจnginxไธญ้
็ฝฎ่ด่ฝฝๅ่กกไนๆฏๅๅๅฎนๆ็๏ผๅๆถ่ฟๆฏๆไบๅค็ง่ด่ฝฝๅ่กก็ญ็ฅไพๆไปฌ็ตๆดป้ๆฉใ้ฆๅ
ไพๆงๆฏๅๅคไธคไธชtomcatๆๅกๅจ๏ผไธไธช็ซฏๅฃไธบ8080๏ผไธไธช็ซฏๅฃไธบ8081๏ผ่ฟ้ๅข๏ผๆจ่ๅคงๅฎถ็จdocker้จ็ฝฒ๏ผๅคชๆนไพฟไบ๏ผไปไน๏ผไธไผdocker๏ผๅฏไปฅ็งปๆญฅๆ็้ขๅๅ็ซฏ็dockerๅ็บงๅ
ฅ้จๆ็จ๏ผ็็ๆบๅฅฝ็จ๏ผ็ไบๅพๅคๅทฅไฝ้ใ
ๅงๆงฝ๏ผๅนฟๅ
็ถๅไฟฎๆนๆไปฌ็httpๅๅฆไธ:
```shell
http {
###ๆญคๅค็็ฅไธๅคงๅ ๆฒกๆๆน็้
็ฝฎ
##่ชๅฎไนๆไปฌ็ๆๅกๅ่กจ
upstream myserver{
server 127.0.0.1:8080;
server 127.0.0.1:8090;
}
server {
listen 8888 ; ##่ฎพ็ฝฎๆไปฌnginx็ๅฌ็ซฏๅฃไธบ8888
server_name [ๆๅกๅจ็ipๅฐๅ];
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
proxy_pass http://myserver; ##ๅฎ๏ผๆ ธๅฟ้
็ฝฎๅจ่ฟ้
proxy_connect_timeout 10; #่ถ
ๆถๆถ้ด๏ผๅไฝ็ง
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
}
```
่ฟๅฐฑๅฎไบ?ๅฝ็ถ่ฟๆฒกๆ๏ผไนๅๅฐฑๆ่ฏด่ฟ๏ผnginxๆไพไบไธ็งไธๅ็่ด่ฝฝๅ่กก็ญ็ฅไพๆไปฌ็ตๆดป้ๆฉ๏ผๅๅซๆฏ๏ผ
- **่ฝฎ่ฏข(้ป่ฎคๆนๅผ):** ๆฏไธช่ฏทๆฑๆๆถ้ด้กบๅบ้ไธๅ้
ๅฐไธๅ็ๅ็ซฏๆๅกๅจ๏ผๅฆๆๅ็ซฏๆๅกๅจ down ๆ๏ผ่ฝ่ชๅจๅ้คใ
็จๆณ๏ผๅฅไนไธๅ ๏ผไธๆๅฎไพๅฐฑๆฏ้ป่ฎค็ๆนๅผ๏ผๅฐฑๆฏ้ป่ฎค็
- **ๆ้(weight):** weight ไปฃ่กจๆ้,้ป่ฎคไธบ 1,ๆ้่ถ้ซ่ขซๅ้
็ๅฎขๆท็ซฏ่ถๅค,ๆ้่ถๅคง๏ผ่ฝๅ่ถๅคง๏ผ่ดฃไปป่ถๅคง๏ผๅค็็่ฏทๆฑๅฐฑ่ถๅคใ
็จๆณ:
```shell
upstream myserver{
server 127.0.0.1:8080 weight =1;
server 127.0.0.1:8090 weight =2;
}
```
- **ip_hash**๏ผๆฏไธช่ฏทๆฑๆ่ฎฟ้ฎ ip ็ hash ็ปๆๅ้
๏ผ่ฟๆ ทๆฏไธช่ฎฟๅฎขๅบๅฎ่ฎฟ้ฎไธไธชๅ็ซฏๆๅกๅจ๏ผๅฏไปฅ่งฃๅณ session ็้ฎ้ขใ
็จๆณ๏ผ
```shell
upstream myserver{
ip_hash;#ๅฏไธweight้
ๅไฝฟ็จ
server 127.0.0.1:8080 weight =1;
server 127.0.0.1:8090 weight =2;
}
```
### nginx้
็ฝฎๅจ้ๅ็ฆป๏ผ
ๆฅไธๆฅ่ฏดๆๅไธไธชๅฎไพ๏ผๅจ้ๅ็ฆป็็ฎๅ้
็ฝฎใ
็ญ็ญ๏ผๆ่ฎฐๅพๆๆๆฏๅไธช๏ผๆๆ่ฟๆไธไธชๆญฃๅไปฃ็ๅข๏ผ
่ฟไธช๏ผ็ฑๅฝๅฎๆณ๏ผไบบไบบๆ่ดฃ๏ผๆ้่ฆ่ฎฟ้ฎๆไบๅฝๅ
ไธ่ฝ่ฎฟ้ฎ็็ฝ็ซ้ๆฑ็ๅๅญฆ๏ผๅฏไปฅ่ช่กไธๅปๆฅ้
่ตๆใ
่ณไบๆไน้
็ฝฎๆญฃๅไปฃ็๏ผๅฑไนไธ็ฅ้๏ผๅฑไนไธๆข่ฏด๏ผๅฑไนไธๆข้ฎใ
**ๅบ็ก็ฏๅ้กพ๏ผ**
> ๅจ้ๅ็ฆปๅฐฑๆฏๆๅพๅฐไผๅ็ไฟฎๆน็่ฏธๅฆๅพๅ๏ผ่ง้ข๏ผcssๆ ทๅผ็ญ้ๆ่ตๆบๆไปถๆพ็ฝฎๅจๅ็ฌ็ๆๅกๅจไธ๏ผ่ๅจๆ่ฏทๆฑๅ็ฑๅฆๅคไธๅฐๆๅกๅจไธ่ฟ่ก๏ผ่ฟๆ ทไธๆฅ๏ผ่ด่ดฃๅจๆ่ฏทๆฑ็ๆๅกๅจๅๅฏไปฅไธๆณจๅจๅจๆ่ฏทๆฑ็ๅค็ไธ๏ผไป่ๆ้ซไบๆไปฌ็จๅบ็่ฟ่กๆ็๏ผไธๆญคๅๆถ๏ผๆไปฌไนๅฏไปฅ้ๅฏนๆไปฌ็้ๆ่ตๆบๆๅกๅจๅไธๅฑ็ไผๅ๏ผๅขๅ ๆไปฌ้ๆ่ฏทๆฑ็ๅๅบ้ๅบฆใ
ๅ
ทไฝ็ๅจ้ๅ็ฆป้
็ฝฎไนไธๆฏๅๅ็ๅคๆ๏ผๅ่ด่ฝฝๅ่กก๏ผๅๅไปฃ็ๅทฎไธๅคใ
ไธบไบๆผ็คบๅจ้ๅ็ฆปๅข๏ผ้ฆๅ
ๆไปฌ้่ฆๅๅคไธคไธชๆไปถๅคน๏ผไธไธชๆฏdataๆไปถๅคน๏ผ็จๆฅๅญๆพๆไปฌjs๏ผcss่ฟไบ้ๆ่ตๆบๆไปถ๏ผไธไธชๆฏhtmlๆไปถๅคน๏ผ็จๆฅๅญๆพๆไปฌ็htmlๆไปถใ
ๅจhtmlๆไปถๅคนๆฐๅปบไธไธชhtmlๆไปถ๏ผindex.html๏ผๅ
ๅฎนๅฆไธ
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>ๆๆฏไธไธช้ๆ็้ข</title>
</head>
<script type="text/javascript" src="jquery.js"></script>
<body>
<h1>ๆๆฏไธไธช้ๆ็้ข</h1>
<div id="test_div"></div>
</body
</html>
```
ๆณจๆ๏ผ่ฟ้ๆไปฌๅนถๆฒกๆๅฐjquery.js ่ฟไธชๆไปถๆพๅจhtml็ฎๅฝไธ๏ผ่ๆฏๅฐๅฎๆพๅจไบๅฆๅคไธไธช็ฎๅฝdata้้ข๏ผๅฝๆๅกๅจๆฅ้่ฆ่ฏทๆฑjquery.js่ฟไธชๆไปถๆถ๏ผๅนถไธไผๅปindex.htmlๆๅจ็้ฃไธชๆๅกๅจๅป่ฏทๆฑ่ฟไธชๆไปถ๏ผ่ๆฏไผ็ดๆฅๅปๆไปฌ้
็ฝฎๅฅฝ็ๆๅกๅจๆ่
่ทฏๅพๅปๅฏปๆพ่ฟไธชjsๆไปถ๏ผๅจๆฌๅฎไพไธญ๏ผไผๅปdataๆไปถๅคนไธ้ขๅปๆพ่ฟไธชjquery.js่ฟไธชๆไปถใ
ไฟฎๆนserver็้
็ฝฎๅฆไธ:
```shell
server {
listen 8886 ;
server_name [ไฝ ็ๆๅกๅจipๅฐๅ];
# Load configuration files for the default server block.
include /etc/nginx/default.d/*.conf;
location / {
root /html/;
index index.html;
}
#ๆฆๆช้ๆ่ตๆบ๏ผstatic้้ขๅญๆพ็ๆไปฌๅพ็ไปไน็้ๆ่ตๆบ
location ~ .*\.(gif|jpg|jpeg|bmp|png|ico|js|css)$ {
root /data/;
}
error_page 404 /404.html;
location = /40x.html {
}
error_page 500 502 503 504 /50x.html;
location = /50x.html {
}
}
```
ๆต่ฏ:
ๅจๆต่งๅจไธญ่พๅ
ฅipๅฐๅ:8888/index.html,ๅฑๅนไธๆพ็คบๆๆฏไธไธช้ๆ็้ข๏ผๅๆถๆๅผๅผๅ่
ๅทฅๅ
ท

ไผๅ็ฐjquery.jsๅทฒ็ป่ขซๆญฃๅธธ่ฏทๆฑๅฐไบใ
## ไธ้ขๅผๅงๆๆฏๆป็ป๏ผ
ๅๅฐ่ฟ้ๅฎๆ็ฏ็ปๆไบๅ๏ผๅนถๆฒกๆ๏ผๅฐฝ็ฎกไธ้ข็ปๅบไบ่ด่ฝฝๅ่กก๏ผๅๅไปฃ็,ๅจ้ๅ็ฆป็ๅฎไพ๏ผไฝไป็ถๅชๆฏๆๅบ็ก็้
็ฝฎ๏ผๆฏๅฆๅคๅฑ่ด่ฝฝๅ่กก๏ผ็ผๅญ็ญ้ซ็บง้
็ฝฎ๏ผ้ฝ้่ฆๆไปฌๅจๆฅๅ็ๅผๅ็ๆดป้ๆธ็ๅปๆฅ่งฆๅไบ่งฃใไธไธ็ฏๅข๏ผๆไปฌๅฐๆทฑๅ
ฅnginx่
นๅฐ๏ผๅป็จๅพฎ็จๅพฎ็ฎๅไธ็ป่ดๅคง่ด็ไธ็ผ้ฃ็งๅปไบ่งฃไธไธnginxๅ
้จๆฏๅฆไฝไฟๆๅฆๆญค้ซๆ็็ๅทฅไฝ็ใ
ๆๅ๏ผ้ฉๆฐ็ๅญฆไน ็ฌ่ฎฐ็ฎๅๅทฒ็ปๆๆฐๅผๆบ่ณgithub๏ผไธๅฎ่ฆ็นไธช**star**ๅๅๅๅๅๅๅ
**ไธๆฐดๅๅฑฑๆปๆฏๆ
๏ผ็ปไธชstar่กไธ่ก**
[้ฉๆฐ็ๅผๅ็ฌ่ฎฐ](https://github.com/hanshuaikang/HanShu-Note)
ๆฌข่ฟ็น่ต๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ๏ผๆป็จฝ๏ผ
<file_sep># Springbootๅญฆไน ็ฌ่ฎฐ:ๅตๅ
ฅๅผWebๅฎนๅจ
## ๅ่จ๏ผ
## ็ๆฌ
> ไฝ่
๏ผ้ฉๆฐ
>
> Github๏ผhttps://github.com/hanshuaikang
>
> ๅพฎไฟกๅ
ฌไผๅนณๅฐ:็ ไธMarson
>
> ๅฎๆๆฅๆ๏ผ2019-07-02ๆฅ
>
> jdk๏ผ1.8
>
> springboot็ๆฌ๏ผ2.1.6.RELEASE
## ่ด่ฐข๏ผ
**ๅฐ้ฉฌๅฅ๏ผ Java ๅพฎๆๅกๅฎ่ทต - Spring Boot / Spring Cloud่ดญไนฐ้พๆฅ๏ผ**
https://segmentfault.com/ls/1650000011387052
## ็ตๅญ็ๅ็ธๅ
ณไปฃ็ ไธ่ฝฝ๏ผๆฌข่ฟStar๏ผ:
Github๏ผhttps://github.com/hanshuaikang/Spring-Note
ๅพฎไฟกๅ
ฌไผๅท๏ผ**็ ไธmarson**
## 1.้กน็ฎๅๅค๏ผ
- ๆฐๅปบไธไธชSpringboot้กน็ฎ๏ผๅ
ๅซๆๅบ็ก็Web็ปไปถ
- ๆฐๅปบไธไธชControllerๅ
๏ผๆฐๅปบHelloControllerไฝไธบๆไปฌ็URLๆ ๅฐๆต่ฏ็ฑป
**HelloController.java**ไปฃ็ ๅฆไธ:
```java
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class HelloController {
@GetMapping("/")
public String helloWord(){
return "Hello World";
}
}
```
## 2.ๅตๅ
ฅๅผServlet Webๅฎนๅจ
**ๅ่จ:**ๅจSpringbootไธญ๏ผTomcatไฝไธบSpringboot็ไธไธช็ปไปถ็ฑSpring้ฉฑๅจ๏ผๆฏๆjarๅ
็ดๆฅ่ฟ่กweb้กน็ฎ็ฎๅไบๆไปฌๅจๆฌๅฐๅทฅ็จ็ฏๅขไธ็ๅผๅๆต็จใ่Springbootๅฝ็ถไฝไธบไธไธช็ตๆดป็ๆกๆถ๏ผไนไธบๅผๅ่
ไปฌๆไพไบๅ
ถไป็้ๆฉ๏ผๅฆjetty๏ผUndertowๅTomcat๏ผๅทฒ็ป2.0+็ๆฌๆฐๅข็Netty Web Serverใ
### 1.ไฝฟ็จTomactไฝไธบWebๅฎนๅจ
> ๅ ไธบSpringboot้ป่ฎค้็จ็ๅฐฑๆฏTomcatๅฎนๅจ๏ผๆไปฅๅฆไฝ้
็ฝฎTomcatไฝไธบWeb ๅฎนๅจ่ฟ้ไธๅๅค่ฎฒใ
### 2.ไฝฟ็จJettyไฝไธบWebๅฎนๅจ
Eclipse Jetty Web ServerๆไพไบไธไธชHTTPๆๅกๅจๅServletๅฎนๅจ๏ผ่ฝๅคๆไพๆฅ่ช็ฌ็ซๅฎไพๆๅตๅ
ฅๅผๅฎไพ็้ๆๅๅจๆๅ
ๅฎนใไปjetty-7ๅผๅง๏ผjetty webๆๅกๅจๅๅ
ถไปๆ ธๅฟ็ปไปถ็ฑEclipse Foundationๆ็ฎกใjettyๆฏๆ:
- ๅผๆญฅHTTPๆๅกๅจ
- ๅบไบๆ ๅ็Servletๅฎนๅจ๏ผๆๆฐ็ๆฌๆฏๆServlet3.1่ง่๏ผ
- websocketๆๅกๅจ
- http / 2ๆๅกๅจ
- ๅผๆญฅๅฎขๆทๆบ(http/1.1ใhttp/2ใwebsocket)
- OSGIใJNDIใJMXใJASPIใAJPๆฏๆ
ๅฆไฝไปTomcatๅๆขๅฐJettyๅฎนๅจ๏ผSpringbootๅฎๆนๆๆกฃไธญๅทฒ็ปๆไพไบๆนๆณ๏ผๅช้ๅฐspring-boot-starter-webไพ่ตไธญ็Tomcatไพ่ตๆ้คๆ๏ผๅผๅ
ฅspring-boot-starter-jettyไพ่ตๅณๅฏ๏ผxmlไปฃ็ ๅฆไธ:
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- ๆ้คTomcatไพ่ต้กน-->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
```
้ๅฏSpringboot้กน็ฎ๏ผ่ฎฟ้ฎhttp://127.0.0.1:8080/ ๏ผๅฑๅนไธๆพ็คบHello World ๏ผๆญฃๅธธใ
### 3.ไฝฟ็จUndertowไฝไธบๅตๅ
ฅๅผServlet Webๅฎนๅจ๏ผ
Undertow ๆฏ็บขๅธฝๅ
ฌๅธๅผๅ็ไธๆฌพ**ๅบไบ NIO ็้ซๆง่ฝ Web ๅตๅ
ฅๅผๆๅกๅจ**
Untertow ็็น็น๏ผ
- **่ฝป้็บง**๏ผๅฎๆฏไธไธช Web ๆๅกๅจ๏ผไฝไธๅไผ ็ป็ Web ๆๅกๅจๆๅฎนๅจๆฆๅฟต๏ผๅฎ็ฑไธคไธชๆ ธๅฟ Jar ๅ
็ปๆ๏ผๅ ่ฝฝไธไธช Web ๅบ็จๅฏไปฅๅฐไบ 10MB ๅ
ๅญใ
- **Servlet3.1 ๆฏๆ**๏ผๅฎๆไพไบๅฏน Servlet3.1 ็ๆฏๆใ
- **WebSocket ๆฏๆ**๏ผๅฏน Web Socket ๅฎๅ
จๆฏๆ๏ผ็จไปฅๆปก่ถณ Web ๅบ็จๅทจๅคงๆฐ้็ๅฎขๆท็ซฏใ
- **ๅตๅฅๆง**๏ผๅฎไธ้่ฆๅฎนๅจ๏ผๅช้้่ฟ API ๅณๅฏๅฟซ้ๆญๅปบ Web ๆๅกๅจใ
ๅๆขๆนๅผๅJettyไธ่ด๏ผไปฃ็ ๅฆไธ๏ผ
```xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<!-- Exclude the Tomcat dependency -->
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
```
## 3.ๅตๅ
ฅๅผReactive Web ๅฎนๅจ
**ๅ่จ**๏ผๅตๅ
ฅๅผReactive Web ๅฎนๅจไฝไธบspringboot2.0็ๆฐ็นๆง๏ผไธ่ฌๆฅ่ฏดๅนถไธๆฏ็ณป็ป้ป่ฎค็้ๆฉใๅจๆไบๆ
ๅตไธๅฝๆฐๅผ็ผ็จ็็กฎไผๅคงๅคงๆ้ซๆไปฌ็ๅผๅๆ็ใ่jetty๏ผtomcat๏ผๅundertowไนๅๅบ็ๅฏนReactiveๅไบๆฏๆใ
### 1.ไฝฟ็จUndertowไฝไธบๅตๅ
ฅๅผReactive Web ๅฎนๅจ:
ๆณจ:ๅฝ**spring-boot-starter-web**ๅ**spring-boot-starter-webflux**ๅๆถๅญๅจๆถ๏ผ**spring-boot-starter-webflux**ๅฎ้
ไธๆฏไผ่ขซ้ป่ฎคๅฟฝ็ฅๆ็๏ผ็ๆญฃๅ
ถไฝ็จ็ๆฏ**spring-boot-starter-web**๏ผๆไปฅๅจไฝฟ็จ**spring-boot-starter-webflux**็ๆถๅ๏ผๆไปฌ้่ฆๆ**spring-boot-starter-web**ๆณจ้ๆใไฟฎๆนๅ็pomๆไปถๅฆไธใ
```xml
<dependencies>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-web</artifactId>-->
<!--<exclusions>-->
<!--<!– Exclude the Tomcat dependency –>-->
<!--<exclusion>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-undertow</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
```
็ฐๅจๆฐๅขไธไธชMyRoute็ฑป๏ผ้่ฟๅฝๆฐๅผ็ผ็จๆไปฌ็ผๅไธไธชhelloword่ทฏ็ฑ:
```java
@Configuration
public class MyRoute {
@Bean
public RouterFunction<ServerResponse> helloWord(){
return route(GET("/"),
request -> ok().body(Mono.just("helloworld"),String.class)
);
}
}
```
้ๅฏSpringboot้กน็ฎ๏ผ่ฎฟ้ฎhttp://127.0.0.1:8080/ ๏ผๅฑๅนไธๆพ็คบhelloworld ๏ผๆญฃๅธธใ
### 2.ไฝฟ็จjettyไฝไธบๅตๅ
ฅๅผReactive Web ๅฎนๅจ:
ๅ็๏ผๅช้่ฆ็ฎๅไฟฎๆนpomๆไปถๅฐฑๅฏไปฅไบใ
```xml
<dependencies>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-web</artifactId>-->
<!--<exclusions>-->
<!--<!– Exclude the Tomcat dependency –>-->
<!--<exclusion>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jetty</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
</dependencies>
```
### 3.ไฝฟ็จTomcatไฝไธบๅตๅ
ฅๅผReactive Web ๅฎนๅจ:
```xml
<dependencies>
<!--<dependency>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-web</artifactId>-->
<!--<exclusions>-->
<!--<!– Exclude the Tomcat dependency –>-->
<!--<exclusion>-->
<!--<groupId>org.springframework.boot</groupId>-->
<!--<artifactId>spring-boot-starter-tomcat</artifactId>-->
<!--</exclusion>-->
<!--</exclusions>-->
<!--</dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
</dependency>
</dependencies>
```
## 4.ๆป็ป
ๆฌๆ่พไธบ็ฎๅ็่ฎฐๅฝไบspringbootๅผๅไธญไธๅWeb ๅฎนๅจ็ๅๆข๏ผๅนถ็ฎๅ็้่ฟฐไบๆฏไธชๅฎนๅจ็็น็น๏ผๅฐฑๅๆ็ฑไธๆ ท๏ผๅ้ๆๆฏๆๅฅฝ็๏ผๆฌ็ณปๅๆ็ซ ๅฑไบSpringๅญฆไน ็ฌ่ฎฐไธญboot้จๅ็ๅญฆไน ็ฌ่ฎฐ๏ผmarkdown็ฌ่ฎฐๆไปถไปฅๅไปฃ็ ไผ้็ปญๅผๆบๅฐGithubไธ๏ผๆฌข่ฟๅคงๅฎถไธ่ฝฝๅ็นStar๏ผๅฆๆ็ฌ่ฎฐไธญๆ็ๆผๆ่
้่ฏฏ็ๅฐๆน๏ผ่ฟ่ฏทๅไฝๅคงไฝฌๆน่ฏๆนๆญฃใ<file_sep># jvmๅ
ๅญๅๆถ็ปๆๅฅฅไน๏ผๅๅพๆถ้็ฎๆณ
## ๅ่จ๏ผ
ไธไธ็ฏๆ็ซ ๆไปฌ็จๅฐฝๅบ่ฏ่ฏดไบ่ฏดไธไธชๅฏน่ฑกๆฏๅฆไฝ่ขซๅคๅฎไธบๆญปไบก็๏ผๅนถๆๅฐjavaๅ
ๅญๅๆถๅฑ็ปๅ่ฟๅคๅนด็ๅๅฑ๏ผๅๆๅบๆฅไธๆฌพ**java้ชๆญปไปช**๏ผไป่ไธไธพ่งฃๅณไบๆฎ้javaๅฏน่ฑก๏ผ้ชๆญป้พ๏ผๅๆถ้พ็้ๅคง้ฎ้ข๏ผๅๅฐไบjava่ๆๆบๆปๅฑๅไฝ้ขๅฏผ็ไธ่ด่กจๆฌใๅณๅณ๏ผ่ท้ขไบ๏ผๅฝ็ถ๏ผไป
ไป
ๆฏๆ่ฟไธ้กน็ฅๅจๆฏไธ่ถณไปฅjavaๅ
ๅญๅๆถๅฑ่ฃ่ทๆฏๅนด็ๆไฝณ็ป็ปๅฅ็๏ผjvmไธบไบๆดๆนไพฟ็่ฟ่กๅ
ๅญๅๆถ๏ผ่ฟๅๆๅบไบๅค่พพ7็งjavaๅๅพๅๆถไปช๏ผๅฎไปฌ่ขซ็ป็งฐไธบ:
ๅๅพๅฏน่ฑกๅๆถไปช๏ผ๏ผๅๅฆAๆขฆ้ณๆ๏ผ
ๆฌ็โ**ๅๆถๅๅพ๏ผๆๆกๆ ธๅฟ็งๆ**โ็ไฟกๅฟต๏ผๅๅพๅฏน่ฑกๅๆถไปชๅๆ ทไนๆฏ็ฑๅๅคง็ฎๆณไธบๅ็้ฉฑๅจ็๏ผๅฎไปฌๅๅซๆฏ๏ผ
**ๆ ่ฎฐ-ๆธ
้ค็ฎๆณใๅคๅถ็ฎๆณใๆ ่ฎฐๆด็็ฎๆณ๏ผๅไปฃๆถ้็ฎๆณใ**
## ๅบๆฌๆฆๅฟต๏ผ
javaไธญๅไปฃๅๅพๆถ้็ฎๆณๅฐjavaๅ ๆๅญๆดปๆถ้ดๅไธบไธคไธชๅบๅ๏ผไธไธช็จๆฅๅญๆพๆฐ็ไปฃๅฏน่ฑก๏ผไธไธช็จๆฅๅญๆพ่็ไปฃๅฏน่ฑกใ
ๆฐ็ไปฃ๏ผๆฐ็ไปฃๅฐฑๅฎนๆ็่งฃๅคไบ๏ผๆ่ฟไธ้จ็ผไบไธไธช็ซฅ่ฐฃ(ๆป็จฝ)๏ผ
โ ๆฐ็ไปฃ๏ผๆฐ็ไปฃ
โ ๅฏน่ฑกๅฐ๏ผๆญป็ๅฟซ
ไฝ ๆๆฏๅงใ
่็ไปฃ๏ผ็นๆ้ฃไบๆดปๅพๆถ้ดๆฏ่พ้ฟ็ๅฏน่ฑกใ
## ๆ ่ฎฐ-ๆธ
้ค็ฎๆณ๏ผMark-Sweep๏ผ๏ผ
ๆ ่ฎฐ-ๆธ
้ค็ฎๆณ๏ผๆฏๆๆๅๅพๆถ้็ฎๆณไธญๆๅบ็ก็ไธไธช๏ผๅจๅซ็ๅๅพๆถ้็ฎๆณ้ขๅๅฐฑๆฏไธชๅผๅผใ้ฟๆฑๅๆตชๆจๅๆตชๅ๏ผๆ ่ฎฐๆธ
้ค็ฎๆณๅๆฒๆปฉไธ๏ผๅๆไปฌๅคงๅคๆฐๅๅฑ่งๅพไธๆ ท๏ผๅ้ข็็ฎๆณๅพๅค้ฝๆฏๅบไบๆ ่ฎฐ-ๆธ
้ค็ฎๆณๆน่ฟ่ๆฅ็ใ
ๆ ่ฎฐ-ๆธ
้ค็ฎๆณ๏ผๅฐฑๆฏไธไธชๅ
ๆ ่ฎฐ็ถๅๅๆธ
้ค็็ฎๆณ๏ผไฝ ่ฟไธๆฏ่ฑไบ่ฃคๅญๆพ..ๅ๏ผ๏ผๅ
ทไฝ็ๅๆถๆต็จๆฏ่ฟๆ ท็๏ผ
- ๆ ่ฎฐๅบๆๆ้่ฆๅๆถ็ๅฏน่ฑก
- ๆ ่ฎฐๅฎไนๅ็ปไธๅๆถ่ฟไบ่ขซๆ ่ฎฐ็ๅฏน่ฑก
ๆฒกไบ๏ผ่ฆไธ่ฏดๅฎ็ฎๅๅขใ
ไฝๆฏๅจๅฎ็ฐ็ฎๅ็ๅๆถไนๅๆถๅธฆๆฅไบๅพๅค้ขๅค็้ฎ้ข๏ผๅ
ถไธญไธป่ฆ้ไธญๅจไธค็น๏ผ
- ้ฆๅ
้ฆๅฝๅ
ถๅฒ็ๅฐฑๆฏๆ็้ฎ้ข๏ผๆฌ่บซๆ ่ฎฐๆธ
้ค่ฟไธคไธช่ฟ็จ้ฝไธๅคช้ซ๏ผๅ ไธบไฝ ่ฆๆพๅฐไธไธชไธชๅฏน่ฑก๏ผ็ปไปไปฌ็ไธ็ซ ๏ผ็ถๅๅไธไธชไธชๅปๆธ
้ค๏ผ่ฏๅฎๆฒกๆไธ้
็ซฏไบๅฟซใ
- ็ฌฌไบไธชๅฐฑๆฏ็ฉบ้ดๅฉ็จ้ฎ้ขไบ๏ผๅ ไธบๅจๅ
ๅญไธญ้ฃไบ้่ฆ่ขซๅๆถ็ๅฏน่ฑกไธๆฏไธไธชๆจ็ไธไธช้ฃไนๆ็้็ญไฝ ๅๆถ็๏ผ่ๆฏๅๆฃๅจๅ
ๅญๅๅค๏ผๆธ
้ค็ๆถๅJava่ๆๆบ่ฆไธไธชๅฐๅฟไธไธชๅฐๅฟ็่ท๏ผ็ถๅๅๅปๅๆถ๏ผๅ ไธบๅฏน่ฑกๆฏๅๆฃๅจๅๅค็๏ผๆไปฅๆไปฌๅๆถๅฎๅฐฑๅฎนๆๅบ็ฐ๏ผ่ฟไธๅฐๅๅ
ๅญๆฏ็ฉบ็๏ผ้ฃไธๅฐๅๅ
ๅญๆฏ็ฉบ็๏ผ่ฟไนไธๅปไผๅฏผ่ดๅ
ๅญไธญ้ฝๆฏไธๅฐๅไธๅฐๅ็ๅ
ๅญ๏ผๅฝไธไธชๆฏ่พๅคง็ๅฏน่ฑก้่ฆๅ้
ๅ
ๅญๆถ๏ผ็ณป็ปๆพไธๅฐ่ฟไนๅคงๅ็่ฟ็ปญๅ
ๅญไบ๏ผๆพไธๅฐ็ณป็ปๅพ็ๆฅๅ๏ผไบๆฏๅฐฑไธๅพไธๆๅ่งฆๅๅฆๅคไธๆฌกๅๅพๆถ้ๅจไฝไบใ
ๅพๅคงๆฆๆฏ้ฟ่ฟไธชๆ ทๅญ๏ผๆฅ่ชๆ้(ๅๆ่)ๅคงไฝฌ็ๅพ๏ผ

่ฟๆ ท็ปๅๆๅญๅ็ๅฐฑๆฏไธๆฏๅฐฑๅฎนๆ็่งฃๅคไบใ
## ๅคๅถ็ฎๆณ๏ผCopying๏ผ๏ผ
ๆ ่ฎฐ-ๆธ
้ค็ฎๆณๅบๆฅไนๅ๏ผๅคๅฅณๅบง็ไธไธๅปไบใ
ๅคๅฅณๅบง๏ผไฝ ็ง็งไฝ ๅๆถ็้ฃ้ฝๆฏไปไน็ฉๆๅฟ๏ผๅๆถๅฎ้ฃๅ
ๅญไนฑ็๏ผๅๅๅฆๅๆ้ฝๆฒกๆณ็๏ผๅฐฑไธ่ฝๆด็ไธไธๅ๏ผไธๅฎถไบบๆดๆด้ฝ้ฝ็ๅคๅฅฝใ
ไบๆฏๅคๅถ็ฎๆณๅบ่ฟ่็ไบใ๏ผ็บฏๅฑ็ๆฏ๏ผๅๅฟๅฝ็๏ผ
่ฟไธช็ฎๆณๅข๏ผๅฐๅ
ๅญๅฎน้ๆ็
งๅฎน้ๅไธบไธคไธชๅคงๅฐ็ธ็ญ็ไธคๅ๏ผๆฏๆฌกๅข๏ผๆๅช็จไธๅ๏ผๆๅฆไธๅๅ
็็๏ผๅฝๅ
ถไธญไธๅ็ๅ
ๅญ็จๅฎ็ๆถๅ๏ผๅฐฑๆ่ฟๆดป็็ๅฏน่ฑกๅคๅถๅฐๅฆๅคไธๅไธๅป๏ผ็ถๅๅฐไฝฟ็จ่ฟ็่ฟๅ็ดๆฅไธๆฌกๆธ
ๅฎ๏ผ**็ฎๅ็ฒๆด๏ผ่ฟ่ก้ซๆ**๏ผๅ ไธบๆฏๆดไธชไธๅคงๅๅ
ๅญไธๆฌกๅๆถ๏ผๆไปฅไนไธๅญๅจไปไนๅ
ๅญ็ข็็้ฎ้ขไบ๏ผไฝๆฏๅคฉไธๆฒกๆๅ
่ดน็ๅ้ค๏ผ่ฟไนๅไนๆฏ่ฆไปๅบไธๅฎ็ไปฃไปท็๏ผ้ฃๅฐฑๆฏๅๆฌๆ100M็ๅ
ๅญ๏ผ็ฐๅจไธๆฌกๅช่ฎฉๆ็จ50Mใ
**่ฟๅฐฑๅฅฝๅไฝ ๆไธๆดๅ
่พฃๆก๏ผไธๆฌกๅดๅช่ฎฉไฝ ๅๅ่ข๏ผๆณๆณๅฐฑ้พๅใ**
ๅคๅถ็ฎๆณๅข๏ผไธ่ฌไธป่ฆ็จๆฅๅๆถๆฐ็ไปฃ็ๅฏน่ฑก๏ผไธบไปไน๏ผๅ ไธบ**ๆฐ็ไปฃ๏ผๆญป็ๅฟซ**ใ
ๅ ไธบๆฐ็ไปฃ็ๅฏน่ฑกๅพๅฟซ้ฝไผ่ขซๅๆถๆ๏ผๆไปฅไธ่ฌๆไปฌไนไธๆ็
งไธๆฏไธ้ฃไนๅ๏ผๅจ hotspot่ๆๆบไธญ๏ผๅฐๅ
ๅญๅๆไธๅ๏ผไธๅๆฏๆฏ่พๅคง็Eden(ไผ็ธๅญ),ๅไธคๅ่พๅฐ็Survivor(ๅนธๅญ่
)็ฉบ้ด๏ผๆฏๆฌกไฝฟ็จไธๅEdenๅไธๅSurvivor๏ผๅฝ้่ฆๅๆถๆถ๏ผๅฐ่ฟไธคๅๅ
ๅญไธญๅญๆดป็ๅฏน่ฑกไธๆฌกๆงๅคๅถๅฐๅฆไธๅsurvivorไธญ๏ผ็ถๅ็ดๆฅๆธ
็ๆๅๆ็จ่ฟ็edenๅsurvivor็ฉบ้ดใๅจ hotspot่ๆๆบไธญ๏ผEdenๅSurvivor็ๆฏไพ้ป่ฎคไธบ8๏ผ1๏ผๅๆๅฏไปฅ้่ฟไฟฎๆน่ๆๆบๅๆฐๆฅไฟฎๆนEdenๅSurvivorไน้ด็ๆฏไพ๏ผ็ป่ฟๆ็ป่ดๅ
ฅๅพฎๅคด่้ฃๆด่ฌ็่ฎก็ฎ๏ผๅซไบบ็ฎ็ๅฅฝๅง๏ผ๏ผๅจ hotspot่ๆๆบไธญ้็จ่ฟ็งๆฏไพ็ๅคๅถ็ฎๆณๅจๆฐ็ไปฃไธญๅ
ๅญๆตช่ดน็ๅชๆ10%๏ผ็็กฎ่ฆ่ฟ่ฟไฝไบไธ้ข็็พๅไน50.
็ญ็ญ๏ผไฝ ไธๆฏ่ฏดsurvivor็ฉบ้ด่พๅฐๅ๏ผไธคๅๅ
ๅญๅญๆดป็ๅฏน่ฑก้ฝๅคๅถๅฐไธๅsurvivorไธ๏ผไธไธsurvivor่ฃ
ไธไธๅๅผใ้พไฝไฝ ไบๅง๏ผๆ็ไฝ ๆไนๅใ
**ๆๆฒกๆ๏ผๆไธ่ฝๅๅ**๏ผjvmๅผๅ
ฅไบๅ้
ๆ
ไฟ่ฟไธชๆฆๅฟต๏ผๅฝsurvivor็ฉบ้ดไธๅคๆถ๏ผ่ฟไบๅฏน่ฑกๅฐ้่ฟๅ้
ๆ
ไฟๆบๅถ็ดๆฅ่ฟๅ
ฅ่ๅนดไปฃใ่ณไบๅ้
ๆ
ไฟๅ
ทไฝๆฏๆไน็ฉ็๏ผๅคงๅฎถๅฏไปฅๆฅ้
็ธๅ
ณ่ตๆ็ไธๅ๏ผๆๆๅญๆ็ๆ็ผ๏ผๅฐๅฃฐ้ผ้ผ๏ผไฝ ไนๆฒกๆๆก่ฎฒๆธ
ๆฅๅฅฝๅง๏ผๅ๏ผใ
้ฃๅคๅถ็ฎๆณๆข็ถ่กจ็ฐ่ฟไน้ฆ๏ผ้ฃไธบไปไนไธ่ฝ็จๆฅๅๆถ่ๅนดไปฃๅบๅๅข๏ผ
ไฝ ๆณๆณ๏ผ่ๅนดไปฃๆฏไปไน๏ผjava่ๆๆบไธญ็้ฟๅฏฟๆ๏ผๅนณๅธธไธ่ฌ้ฝไธๆญป๏ผไฝ ๆไธชๅคๅถ็ฎๆณ่ฟๅปไธ็
ๅฐผ็๏ผ้ฝ่ฟๆดป็ๅข
็ถๅไธไธชไธไธชๆไธๅคงๅ ๆดป็็่ๅฏน่ฑกๅคๅถ่ฟๅป๏ผๆดๅซ่ฏดๆ็ซฏๆกไปถไธไธไธชไนๆฒกๆญป็ๆ
ๅตไบใ
ๅฏนไบ๏ผๅคๅถ็ฎๆณ็ๅพๅฆไธ๏ผ

## ๆ ่ฎฐ-ๆด็็ฎๆณ๏ผMark-Compact๏ผ๏ผ
้พ้้ๅฏน่ๅนดไปฃๅฐฑๆฒกไปไนๅๆณไบ๏ผๆ ้ข้ฝๅไบ๏ผ้ฃ่ฏๅฎๅฐฑๆฏๆ็๏ผ้ฃๅฐฑๆฏๆ ่ฎฐ-ๆด็็ฎๆณ๏ผๆๅๆๅฎ็งฐไธบโ**ๅผๅผไปฌ้ฝๅพ่พนไธ้ ้ โ**็ฎๆณใ
ๆ ่ฎฐ-ๆด็็ฎๆณ็นๅซ้ๅ่ๅนดไปฃ๏ผไธบไปไนๅข๏ผๅ ไธบไธๅซๆ ่ฎฐ -ๅคๅถๅ๏ผๆ ่ฎฐ-ๆด็็ฎๆณๅ
ถๅฎๅๆ ่ฎฐ-ๆธ
้ค็ฎๆณๅ็ๅทฎไธๅค๏ผๅชไธ่ฟไธๆฏ็ดๆฅๅฏนๅ
ๅญๆด็๏ผ่ๆฏ่ฎฉ**ๅผๅผไปฌ้ฝๅพ่พนไธ้ ้ **๏ผๅณ่ฎฉๅญๆดป็่ๅนดไปฃๅฏน่ฑก้ฝๅไธไพง็งปๅจ๏ผ็ญ่ฟไบๅผๅผ้ฝๆจ็ๆชๅฐไธๅๅฟไนๅ๏ผ็ดๆฅๆๅ
ถไปๅฐๆน็ๅ
ๅญ็ดๆฅๆธ
็ๆใ

## ๅไปฃๆถ้็ฎๆณ๏ผ
ๅไปฃ็ฎๆณๆฒกไปไนๆฐ็ไธ่ฅฟ๏ผๅ้ขๅบๆฌๆฆๅฟต้ฃไธๅฐ่ๅ
ถๅฎๅฐฑๆฏ่ฏด็่ฟไธช็ฎๆณ๏ผๅไปฃๆถ้็ฎๆณๆ นๆฎๅฏน่ฑก็ๅญๆดปๅจๆ็ไธๅๆๅฏน่ฑกๅๅไธบๆฐ็ไปฃๅ่ๅนดไปฃไธค็ง๏ผๅไปฃๆถ้็ฎๆณ็ๅฅฝๅคๅฐฑๆฏๅฎ็ฐไบๅฏน็ไธ่ฏ๏ผไฝฟๅพๆไปฌๅฏไปฅๆ นๆฎไธๅ็ๅฏน่ฑก้็จไธๅ็ๅๅพๆถ้็ฎๆณ๏ผๆฏๅฆๆฐ็ไปฃ๏ผๆญป็ๅฟซ(ๅๆฅ)๏ผๅฐฑ็จๅคๅถ็ฎๆณ๏ผ่็ไปฃ็่ฏๅฐฑ็จๆ ่ฎฐ-ๆด็็ฎๆณ๏ผๆ่
ๆ ่ฎฐ-ๆธ
้ค็ฎๆณๆฅๅๆถใ
ๆฒกไบ
่ฟไธช็ๆฒกๅพ
## ๆป็ป๏ผ
ๆฌ็ฏๆ็ซ ๆไปฌ่พไธบ็ป่ด็่ฏดไบๆไปฌๅๅพๆถ้็ฎๆณๅๅฐ้พ๏ผไนไธพไบๆฏๅฆ่พฃๆก็ๅฎไพๅธฎๅฉๅคงๅฎถๅ ๆทฑ็่งฃใๅ็งๅๅพๅๆถ็ฎๆณๅๆไผๅฃ๏ผๅนถ็ฑๆญค่ก็ๅบๆฅ7ไธญๅธธ็จ็ๅๅพๆถ้ๅจ๏ผๅ
ณไบๅๅพๆถ้ๅจ็ๆ็ซ ๅข๏ผๆไปฌๅๆๅๆดๆฐใ
ๅฏไปฅๅค็นๆดๆฐๅ๏ผ
ไธๆๆด๏ผไฝ ๅ
ณๆณจๆๅใ
ๆๅ
ณๆณจไฝ
ๅฅฝ
ๆๆฏ้ฉๆฐ๏ผๆไปฌไธ็ฏๆ็ซ ๅ่งใ
<file_sep># ้ขๅๅๅญฆ่
็dockerๅญฆไน ๆ็จ๏ผๅบ็ก็ฏ
## ๅ่จ:
ไนๅๅพๆฉๅฐฑๅฏนDockerๆๆ่ณ้ป๏ผไฝๆฏ็ขไบๆถ้ด(ๅฐฑๆฏๆๅพๅญฆ)็ๅ
ณ็ณป๏ผๅฐฑไธ็ดๆฒกๆๅผๅง่กๅจ๏ผ็ดๅฐๆ่ฟ่ฟไธชๅญฆๆ่ฏพๆฏ่พๅฐ๏ผๅฎๅจไธ็ฅ้่ฏฅๅนฒๅฅไบ๏ผ็ฎไบ๏ผๅญฆไน ๅงใๆไปฅๅฐฑๅผๅงไบๆๆผซ้ฟDockerๅญฆไน ไนๆ
ใๅฝ็ถ๏ผๅ่ฟ็ฏ็ฌ่ฎฐ็ๆถๅ๏ผๆๅฏนDockerๅทฒ็ปๅคงๆฆๆไบไธไธชๅๆญฅ็ไบ่งฃ๏ผๆไปฅๅฐฑๆไบ่ฟไธช้ขๅๅๅญฆ่
็Dockerๅญฆไน ็ฌ่ฎฐ็ณปๅ๏ผไธบไปไนๆฏๅๅญฆ่
ๅข๏ผๅ ไธบๆ่ช่ฎคไธบๆๅฏนDocker็ไบ่งฃไพ็ถๆฏไธไธชๆฏ่พๅ็บง็้ถๆฎต๏ผๆไปฅๆด้ซ็บง็ๅ
ๅฎนๆ่ฏดไธๆ็ฝ๏ผไปฅ่ณไบ่ฏฏๅฏผไบๅซไบบ๏ผๅ่ฟ็ณปๅ็็ฌ่ฎฐไธป่ฆๅ่กทๆไธคไธช๏ผไธๆฅๆฏไธบไบๅฏน่ชๅทฑ่ฟไธช้ถๆฎตๆๅญฆ็็ฅ่ฏๅไธไธชๅ
จ้ข็ๆขณ็ๅๆป็ป๏ผไบๆฅ้กบไพฟๅฐ่ฟไบ็ฅ่ฏ็จๆ้ฃ้ช็ๅๆณๅๆ็ฌ่ฎฐ๏ผๅธฎๅฉๅ้ขๅญฆไน Docker็ๅฐไผไผดๆด้ไฟๆๆ็ๅป็่งฃDocker็ธๅ
ณ็็ฅ่ฏๅๆฆๅฟต๏ผๆฌ็ฏๆ็ซ ไฝไธบๅบ็ก็ฏ็ฌฌไธ็ฏ๏ผๅฐๅด็ป่ฟไธไธช้ฎ้ขๆฅๅฑๅผ๏ผ
1. ไปไนๆฏDocker๏ผ
2. ไธบไปไนๆฏDocker๏ผ
3. Docker ๅ
ทไฝ่งฃๅณไบไปไนๆ ท็้ฎ้ข๏ผ
## ไปไนๆฏdocker?
DockerๆฏๅบไบGo่ฏญ่จๅฎ็ฐ็ๅจ2013ๅนดๅๅธ็ไบๅผๆบ้กน็ฎ๏ผๅฎๅฉ็จไบๅด็ปๅฎนๅจ่ฟไธช็ฐๆ็่ฎก็ฎๆฆๅฟต๏ผ็นๅซๆฏๅจLinuxไธ็ไธญ๏ผ่ฟไบๅๅงๆฆๅฟต่ขซ็งฐไธบcgroupsๅๅฝๅ็ฉบ้ดใDocker็ๆๆฏไนๆไปฅ็ฌ็นๆฏๅ ไธบๅฎไธๆณจไบๅผๅไบบๅๅ็ณป็ปๆไฝๅ็้ๆฑ๏ผไปฅๅฐๅบ็จ็จๅบไพ่ต้กนไธๅบ็กๆถๆๅๅผใ
Docker็ไธป่ฆ็ฎๆ ๆฏโBuild๏ผShip and Run Any App,Anywhereโ๏ผไนๅฐฑๆฏ้่ฟๅฏนๅบ็จ็ปไปถ็ๅฐ่ฃ
ใๅๅใ้จ็ฝฒใ่ฟ่ก็ญ็ๅฝๅจๆ็็ฎก็๏ผไฝฟ็จๆท็APP๏ผๅฏไปฅๆฏไธไธชWEBๅบ็จๆๆฐๆฎๅบๅบ็จ็ญ็ญ๏ผๅๅ
ถ่ฟ่ก็ฏๅข่ฝๅคๅๅฐโไธๆฌกๅฐ่ฃ
๏ผๅฐๅค่ฟ่กโใ
ไธๅฅ่ฏๆฆๆฌ๏ผDocker็ๅบ็ฐ่งฃๅณไบ่ฟ่ก็ฏๅขๅ้
็ฝฎ็ฏๅขไธไธ่ด็ๆ
ๅต๏ผไป่ๆดๆนไพฟ็ๅๆ็ปญ้ๆๅนถๆๅฉไบๆดไฝๅๅธใ
## ไธบไปไนๆฏDocker๏ผ
่ฆไบ่งฃ่ฟไธช้ฎ้ข๏ผๆไปฌๅฐฑ้่ฆไบ่งฃๅจDockerไนๅ็ไผ ็ป็่ๆๆบๆๆฏๆฏๆๆ ท็๏ผๆ็ธไฟกๅคงๅฎถ้ฝๆไฝฟ็จ่ฟ่ๆๆบ่ฝฏไปถๅจ่ชๅทฑ็ต่ไธ่ๆๅบๅฆๅค็ๆไฝ็ณป็ป็็ปๅ๏ผๆฏๅฆๅจwinไธ้่ฟvmๅฎ่ฃ
ไธไธชlinux็ณป็ป๏ผไผ ็ป็่ๆๆบๅ
ถๅฎๆฏไธ็งๅธฆ็ฏๅขๅฎ่ฃ
็่งฃๅณๆนๆก๏ผไนๅฐฑๆฏ่ฏด๏ผๆๆจกๆ็ๆฏไธๅฅๅฎๆด็ๆไฝ็ณป็ป็ฏๅข๏ผ่ฟไธช็ณป็ปไพ็ถๆฏๆๅฎ็ฌ็ซ็ๅ
ๆ ธ๏ผ้ฉฑๅจ็ญ็ญใ
ๅฆๅพๆ็คบ๏ผ
โ 
ๅฏนไบ่ๆๆบไธญ่ฟ่ก็็จๅบ่่จ๏ผ็ฑไบ่ๆๆบๆจกๆไบไธๆดๅฅ็ณป็ป็็ฏๅข๏ผ้ฃไนๅจ่ๆๆบไธญ่ฟ่ก็ๅบ็จ็จๅบๆฏๆ็ฅไธๅฐ่ชๅทฑๆฏๅจ่ๆๆบไธญ่ฟ่ก็๏ผๅฐฑๅๅๅจ็ๅฎ็ๆไฝ็ณป็ปไธญ่ฟ่กไธๆ ทใ
ๅฝ็ถ๏ผ็ๅฐ่ฟ๏ผๅพๅคไบบๅฏ่ฝไผ่งๅพ๏ผ่ฟไธๆฏๆบๅฅฝ็ๅ๏ผ็็กฎ๏ผๅจ้ๆฑไธๆฏๅพๅคง๏ผๆฏๅฆๅช้่ฆ้ขๅคๅผไธคไธๅฐ่ๆๆบ็ๆถๅ๏ผ่ฟ็งๅๆณๅนถๆฒกๆไปไนๆๆพ็็ญๆฟ๏ผไฝๆฏ๏ผ็ฑไบๆไปฌๆจกๆ็ๆฏไธๆดๅฅๆไฝ็ณป็ป็็ฏๅข๏ผ่ฟๅฐฑๅฏผ่ดไบไปไน้ฎ้ขๅข๏ผๆไปฌๆฏๅผไธไธช่ๆๆบ้ฝไผ้ขๅคๅ ็จๅพๅคงไธ้จๅ่ตๆบ๏ผๅฐฝ็ฎกไฝ ๅฏ่ฝไธคๅฐ่ๆๆบไธญ็linux็ณป็ปๅ
ๆ ธๆฏไธๆจกไธๆ ท็๏ผ่ฟๅฐฑ้ ๆไบๅฏน่ตๆบ็ไธไธชๅพๅคง็ๆตช่ดน๏ผๅๆถๅข๏ผ็ฑไบๆไปฌๅฏๅจ่ๆๆบ็ๆถๅๅฏๅจ็ๆฏไธๆดๅฅๆไฝ็ณป็ป๏ผ่ฟๅฐฑไผๅฏผ่ดๅฏๅจๅๅพ้ๅธธ็ๆ
ข๏ผๅฏ่ฝ้่ฆๅ ๅ้๏ผๅฝ็ถ๏ผๅ ๅ้ๅนถไธๆฏๅพ้ฟ๏ผๅฏๆฏๅฆๆๆๅพๅคๅฐ่ๆๆบๅข๏ผๅฏ่ฝๅฝ่ฟ็ปดๅฅฝไธๅฎนๆๆๆๆ่ๆๆบๅฏๅจๅฎๆไบ๏ผๅ็ฐ็งๆๅทฒ็ป็ปๆไบ๏ผ่ฟๅฏนไบๅพๅคๅคง่งๆจก็ๅบ็จๆฅ่ฏดๆฏไธ่ฝๅฟ็๏ผ็ฌฌไธ็น๏ผๅฐฑๆฏๆญฅ้ชค้ๅธธ็น็๏ผๆไปฌ็ฐๅจๆป็ปไธไธไผ ็ป่ๆๆบๆไธป่ฆ็ไธไธช็ผบ็น:
- ่ตๆบๅ ็จๆฏ่พๅค
- ๅฏๅจๆฏ่พๆ
ข
- ๆญฅ้ชค็น็
ๅฝ็ถ๏ผๆถไปฃๅ่ฟๆญฅ๏ผlinuxไนไธ่ฝ็็่ฟไบ้ฎ้ขๆพไปปไธ็ฎกๅ๏ผไบๆฏlinuxๅๅฑๅบไบๅฆๅคไธ้กน่ๆๅๆๆฏ๏ผๅณlinuxๅฎนๅจๆๆฏใ
linuxๅฎนๅจๆๆฏๆฏๆไนไธๅไบๅข๏ผ่ฟ็นๅๆไปฌๅจๅฎ้
ๅผๅไธญๆฝๅๅ
ฌๅ
ฑ้ป่พ็ๆ่ทฏๆฏ็ฑปไผผ็๏ผไนๅไธๆฏๅผๅพๅค่ๆๆบๅ
ๆ ธไปไน็้ฝไธๆ ท้ ๆ่ตๆบๆตช่ดนๅ๏ผ้ฃๆ่ฟไธๆๅ
ๆ ธๅ็ฌๆฝ็ฆปๅบๆฅ๏ผๅคงๅฎถๅ
ฌ็จ๏ผ**ๆไปฅlinuxๅฎนๅจๅฎ้
ไธ่ฟ่ก็ๅนถไธๆฏไธไธชๅฎๆด็ๆไฝ็ณป็ป๏ผ่ๆฏ้่ฟ่ฟ็จๅฏนไธๅ็ๅฎนๅจ่ฟ่กไบ้็ฆป๏ผๅฎนๅจไธ่ๆๆบไธๅ๏ผไธ้่ฆๆ็ปไธๆดๅฅๆไฝ็ณป็ป๏ผๅช้่ฆ่ฝฏไปถๅทฅไฝๆ้็ๅบ่ตๆบๅ่ฎพ็ฝฎใ็ณป็ปๅ ๆญค่ๅๅพ้ซๆ่ฝป้ๅนถไฟ่ฏ้จ็ฝฒๅจไปปไฝ็ฏๅขไธญ็่ฝฏไปถ้ฝ่ฝๅง็ปๅฆไธๅฐ่ฟ่กใ**
ๅฆๅๆ็คบ๏ผ
โ 
็ฑไบๅฏๅจ็ๆถๅ๏ผๅฏๅจ็ๅนถไธๆฏๆดๅฅๆไฝ็ณป็ป็ฏๅข๏ผไป
ไป
ๆฏๅฏๅจๅบ็จๆ้็็ฏๅขๅฐฑ่กไบ๏ผๅฏๅจ้ๅบฆ่ช็ถๅฐฑๆฏไผ ็ป็่ๆๆบๅฟซไบๅพๅค๏ผ็่ณ่ฏดๅฏไปฅๅๅฐ็งๅฏๅจ๏ผๅๆถๅ่งฃๅณไบ่ตๆบๆตช่ดน็้ฎ้ข๏ผ่Dockerๆญฃๆฏๅบไบlinuxๅฎนๅจๆๆฏ่่ก็ๅบๆฅ็ๅผๆบ้กน็ฎ๏ผไฝฟๅ
ถๅฏนไบๅนฟๅคงๅผๅ่
ๆฅ่ฏดๆดๅฎนๆไธๆ๏ผ้ไฝไบไฝฟ็จ็้จๆงใ
## Docker ๅ
ทไฝ่งฃๅณไบไปไนๆ ท็้ฎ้ข๏ผ
่ฟไธชๅฐฑ่ฆไปๅพไน
ๅพไน
ไปฅๅ่ฏด่ตทไบใ
ๆ
ไบๅ็ๅจ9012ๅนดๅ
จ็ๆไผๅคง็ไบ่็ฝๅ
ฌๅธ้ฟ้ๅฅถๅฅถๆฌกไธไปฃไบงๅ**ๅ
่ดน็ๆๅฎ**็ไธ็บฟๅๅค๏ผ็จๅบๅ้ฟๅๆ่ชๅทฑๅคๆฅไปฅๆฅ**ๅๅฟๆฒฅ่กๅผๅผๅคง็กไธ็ญๆธ้ฑผไธ็ญ่นฆ่ฟช**ๅ็็จๅบไปฃ็ ไบคไป็ปไบ่ฟ็ปดไบๅ๏ผๆฌไปฅไธบ่ชๅทฑๅฐไปฃ็ ็ปไบไบๅๅฐฑๅฏไปฅ**ๆปก้ขๆฅๅ
ๅฆ้้่ด่ฟ็ๅ
ญไบฒไธ่ฎค็ๆญฅไผๆทฑๅคไนฐ้็ซๅๅจ็ฏ็บข้
็ปฟ็บธ้้่ฟท็้
ๅง**๏ผไฝๆฏๆญฃๅฝ้ฟๅๅๅคๅผๅง่ฟๅดญๆฐ็็ๆดป็ๆถๅ๏ผไบๅๆฆไฝไบไป๏ผ
้ฟๅ๏ผไฝ ่ฟไปฃ็ ๆ้ฎ้ขๅง๏ผๆๆไน่ทไธ่ตทๆฅ๏ผ
้ฟๅ๏ผWTF ๏ผๆๆฒกๅฌ้ๅง๏ผไฝ ็ซ็ถ่ฏดๆ็ไปฃ็ ๆ้ฎ้ข๏ผๅตๅต๏ผๆไบบ่ฟ็ปดๆๆฏไธ่ก๏ผ่ฟๅฅฝๆๆ่ฏดๆ่๏ผ
ไบๅ๏ผๆ่ฟ็ปดๆๆฏไธ่ก๏ผๆ่ฟ็ปดๆๆฏไธ่ก๏ผไฝ ่กไฝ ไธๅ๏ผๅผ็ฉ็ฌ๏ผไฝ ไปฃ็ ๅ็ๆฒก้ฎ้ขๆ่ฝ่ทไธ่ตทๆฅ๏ผ
้ฟๅ๏ผไฝ ็ๅคงไฝ ็24k้ๅ้x็ผ็็๏ผๆ็ต่ไธๆฏไธๆฏ่ท็ๅฅฝๅฅฝ็๏ผๆฏไฝ ่ฟ็ปดๆๆฏไธ่ก๏ผok?
ไบๅ๏ผๆ&%๏ฟฅ%*&*,ไฝ ไปฃ็ ๆฒก้ฎ้ขๆฏๅง๏ผไฝ ไปฃ็ ๆฒก้ฎ้ขๆฏๅง๏ผไฝ ๆฅๅ๏ผๆๆฌไบไฝ ่ท่ตทๆฅ๏ผไฝ ่ฆ่ฝ่ท่ตทๆฅๆ็ดๆญๅฅณ่ฃ
๏ผ่ญๅผๅผใ
้ฟๅ๏ผๆไปๅคฉๅฐฑ่ฎฉไฝ ็็๏ผๆๆฏๆไนๆๅฎๅฎ็พ็้จ็ฝฒไธๅป็๏ผไฝ ็ปๆๅฅฝๅฅฝ็็๏ผ็ฅ้ๅ๏ผ๏ผ
ๆญคๆถ๏ผ้ฟๅ็ๅฅณๆๅๆๆฅ็ต่ฏ๏ผ้ฟๅ๏ผไธๆฏ่ฏดๅฅฝไบไธ่ตทๅป้็ๆขฆๆญป็ๅ๏ผ
้ฟๅ๏ผๆป๏ผ็ฐๅจๆฒก็ฉบๆญ็ไฝ ใ
ๆณจ๏ผไปฅไธ็ไธบ่็ฎๆๆ๏ผๅคงๅฎถ่ฏทๅฟๅฝ็ใ
ไผ ็ป็ๅผๅไธญๆปๆฏไผๅบ็ฐ่ฟ็ฑปๅผๅ็ฏๅขๅ็ไบง็ฏๅขไธไธ่ด็้ฎ้ข๏ผ่Docker็ๅบ็ฐๆฏซๆ ็้ฎๆๅคงๅฐ็ฎๅไบ่ฟ็ปดๅทฅ็จๅธ็ๅทฅไฝ้๏ผไนๅคงๅคง้ไฝไบๅผๅๅ่ฟ็ปดไน้ดๆ้ผ็ๆฆ็ใๅคงๅฎถ่ฟไนๆฅ็่งฃ๏ผ
ๆไปฌไปฅๆฌๅฎถไธบไพ๏ผไผ ็ป็ๆต็จๅฐฑๅฏไปฅ็ไฝๆฏๆๆๆๅฎถๅ
ทไธไปถไธไปถๅฐๆฌๅฐๆฐ็ๅฐๆน๏ผไธไธๅชไธชๅฎถๅ
ท็ๆๆพไฝ็ฝฎๆฒก่ฎฐๆธ
ๆฅ๏ผๅฐฑๆๅฏ่ฝๅฏผ่ดๆฐๅฎถ่ฟ่กไธ่ตทๆฅ๏ผ๏ผ๏ผไปไน้ฌผ๏ผ๏ผ่**Dockerๅฐฑๅพ็ฎๅ็ฒๆด๏ผDocker้ๅ็ๆนๅผๅฐฑๆฏๆๆดๅฅ็ฏๅขๆๅ
็ปไฝ ๏ผไนๅฐฑๆฏ็ดๆฅๆๆดไธชๆฅผ้ฝ็ปไฝ ๆฌ่ฟๅป๏ผ้ฎ้ขๅฎ็พ่งฃๅณ**ใ
ๅๆถๅข๏ผDockerๆฏๅ
ๆ ธ็บง่ๆๅ๏ผไธๅไผ ็ป็่ๆๅๆๆฏไธๆ ท้่ฆ้ขๅค็Hypervisorๆฏๆ๏ผๆไปฅๅจไธๅฐ็ฉ็ๆบไธๅฏไปฅ่ฟ่กๅพๅคไธชๅฎนๅจๅฎไพ๏ผๅฏๅคงๅคงๆๅ็ฉ็ๆๅกๅจ็CPUๅๅ
ๅญ็ๅฉ็จ็ใ
ๆป็ป่ตทๆฅ๏ผdockerๅคงๆฆๅฐฑๆฏไปฅไธๅไธชไผ็น:
- ๆดๅฟซ็ๅบ็จไบคไปๅ้จ็ฝฒ
- ๆดไพฟๆท็ๅ็บงๅๆฉ็ผฉๅฎน
- ๆด็ฎๅ็็ณป็ป่ฟ็ปด
- ๆด้ซๆ็่ฎก็ฎ่ตๆบๅฉ็จ
ๅฎๅจๆฏๅคช้ฆไบใ
## ๆป็ป๏ผ
ๆฌ็ฏ็ฌ่ฎฐ็ฎๅ็่ฎฒไบไธไธdocker็ไธไธชๅบๆฌๆ
ๅต๏ผ็ธไฟก็ๅฐ่ฟ้็ๅฐไผไผดๅทฒ็ปๅฏนdockerๆไบไธไธชๅบๆฌ็่ฎค่ฏ๏ผ่ณๅฐ็ฅ้dockerๆฏไปไนไบ๏ผไธไธ็ฏ็ฌ่ฎฐๅข๏ผ่ฎฒๅดDocker ไธ่ฆ็ด ้ๅ ๅฎนๅจ ๅไปๅบ่ฟไธไธชๆฆๅฟตๅฑๅผ๏ผ้ข็ฅๅไบๅฆไฝ๏ผ็นไธช่ตๅ่ตฐๅงใ
ๆๆฏ้ฉๆฐ๏ผๆไปฌไธไธ็ฏ็ฌ่ฎฐใDockerไธ่ฆ็ด :้ๅ๏ผๅฎนๅจๅไปๅบใๅ่งใ
PS๏ผๆดๅค็ฌ่ฎฐๆฌข่ฟๅคงๅฎถๅปๆ็githubไธไธ่ฝฝ(ๆฌข่ฟstar)๏ผ
<https://github.com/hanshuaikang/HanShu-Note>
<file_sep># ้ขๅๅ็ซฏ็Dockerๅ็บงๅ
ฅ้จๆ็จ๏ผๅฎๆ็ฏ
ๅจไนๅ็ไธค็ฏๆ็ซ ไธญ๏ผๆไปฌๅจ [้ขๅๅๅญฆ่
็Dockerๅญฆไน ๆ็จ๏ผๅบ็ก็ฏ](https://juejin.im/post/5d96fd6fe51d45781d5e4bac)ไธญ้่ฟ
1. ไปไนๆฏDocker๏ผ
2. ไธบไปไนๆฏDocker๏ผ
3. Docker ๅ
ทไฝ่งฃๅณไบไปไนๆ ท็้ฎ้ข๏ผ
่ฟไธไธช้ฎ้ขๆฅๅธฎๅฉๅคงๅฎถๆดๅฅฝ็ไบ่งฃDocker๏ผไนๅๅจ็ฌฌไบ็ฏๆ็ซ [Docker ไธ่ฆ็ด ๏ผ้ๅใๅฎนๅจๅไปๅบ](https://juejin.im/post/5d9ac7596fb9a04e1135e85d)ไธญ่งฃ้ไบdockerไธญๆๆ ธๅฟ็ไธไธชๆฆๅฟต๏ผ้่ฟ่ฟไธค็ฏ็ๅญฆไน ๏ผๆๆณๅคงๅฎถๅฏนไบDockerๆฏไปไน๏ผ่ฟไธช้ฎ้ขๅทฒ็ปๆไบ่ชๅทฑ็็ญๆก๏ผ้ฃไนๅไบ่งฃ่ฟ่ฟไบๆฆๅฟตไนๅ๏ผๆไปฌๅฐ้่ฟๅฎ้
็ๅฝไปค่กๆฅไฝฟ็จDocker๏ผๅนถ่ฝๅคๅฎๆไธไบๅบ็ก็ๆไฝใ
ไธๅบ่ฏ๏ผ็ดๆฅไธไปฃ็ :
## Docker ๅฎ่ฃ
:
ๅจไฝฟ็จDockerไนๅ๏ผๆไปฌ้่ฆๅ
ๅฎ่ฃ
Docker๏ผๅจ่ฟ้ ๏ผๆๅชๅไธพๆ็ฎๅ็้ฃไธ็งๅฎ่ฃ
ๆนๅผ๏ผๅฆๆ้่ฆๅ
ถไปๆนๅผๅฎ่ฃ
็่ฏ๏ผๅฏไปฅๅ็
งๅฎๆนๆๆกฃ-ๅฟซ้ไธๆ๏ผไธ้ขๆๆดไธบ่ฏฆ็ป็ๅฎ่ฃ
ๆ็จใ
**Docker ๅฎ่ฃ
(yum):**
```shell
#ๅจ็ป็ซฏ่พๅ
ฅyumๅฝไปค๏ผๅฎ่ฃ
dockerๅ็ธๅ
ณไพ่ต
yum install docker
#ๅฏๅจdocker ๆๅก๏ผcentos 7+
systemctl start docker
#ๅฏๅจdocker ๆๅก๏ผcentos 6+
service docker restart
```
**้ช่ฏDockerๆฏๅฆๅฎ่ฃ
ๆๅ:**
```shell
#ไปdockerๅฎๆนไปๅบๆๅdocker hello-world้ๅ
docker pull hello-world
#่ฟ่กhello-world้ๅ
docker run hello-world
```
ๅฆๆๅบ็ฐ Hello from Docker! ๅ่ฏดๆๆไปฌ็Dockerๅทฒ็ปๆญฃ็กฎๅฎ่ฃ
ๅฎๆๅฆ
ๆณจ:
> docker ๅฎๆน็้ๅๆบ็ฑไบๅจๅฝๅค๏ผๅฏผ่ดๅฝๅ
ๅพๅคๅจๆฌไฝ่ๆๆบๅญฆไน docker็ๅๅญฆไธ่ฝฝ้ๅ็นๅซ็นๅซ็ๆ
ข๏ผๅฎๆต้ฟ้ไบๆๅกๅจ้ๅบฆ่ฟๅฏไปฅ๏ผๅฆไธ่ฝฝ่พๆ
ข็ๅๅญฆๅฏไปฅๅฐ่ฏๆดๆขๅฝๅ
้ฟ้ไบ๏ผๆ่
็ฝๆไบ็้ๅไปๅบ๏ผ้่ฆ็ๅๅญฆๅฏไปฅ่ช่กๅป็ฝไธๆ็ดข็ธๅ
ณๆ็จใ
## Docker ้ๅๆไฝ๏ผ
Dockerๅฎ็พ่ๅLinux๏ผๆไปฅDockerๅฝไปค่ก็้ฃๆ ผๅLinux่ฟๆฏๆฏ่พๆฅ่ฟ็๏ผ็ธๅฏนๆฅ่ฏดๆฏ่พๅฎนๆไธๆ๏ผ้ฆๅ
๏ผๆไปฌๅ
่ฏด้ๅ็ธๅ
ณ็ๅฝไปค:
```shell
#ๆ็ดข้ๅ:
docker search ้ๅๅ
#ไพ๏ผdocker search centos ๆ็ดขcentos็ธๅ
ณ็้ๅใ
#ๆๅ้ๅๅฐๆฌๅฐๆๅกๅจ ้ป่ฎคTAGๆฏlastetๅณๆๆฐ็ๆฌ
docker pull ้ๅๅ:TAG
#ไพ๏ผdocker pull mysql or docker pull mysql:5.6 ๆๅๆๆฐ็ๆฌๆ่
5.6็ๆฌ็mysql้ๅ
#ๆฅ็ๆๆ้ๅ:
docker images
##ๆฅ็้กถๅฑ้ๅ
docker image ls
#ๆฅ็ไธญ้ดๅฑ้ๅ
docker image ls -a
#ๅจไนๅ็ๅบ็ก็ฏไธญๆ่ฏดๅฐ๏ผdocker็้ๅๆฏๅๅฑๆฅๅญๅจ็๏ผไธบไบๅ ้้ๅๆๅปบใ้ๅคๅฉ็จ่ตๆบ๏ผDocker ไผๅฉ็จ ไธญ้ดๅฑ้ๅใๆไปฅๅจไฝฟ็จไธๆฎตๆถ้ดๅ๏ผๅฏ่ฝไผ็ๅฐไธไบไพ่ต็ไธญ้ดๅฑ้ๅ๏ผ่ฟๆ ทไผ็ๅฐๅพๅคๆ ๆ ็ญพ็้ๅ๏ผไธไนๅ็่ๆฌ้ๅไธๅ๏ผ่ฟไบๆ ๆ ็ญพ็้ๅๅพๅค้ฝๆฏไธญ้ดๅฑ้ๅ๏ผๆฏๅ
ถๅฎ้ๅๆไพ่ต็้ๅใ่ฟไบๆ ๆ ็ญพ้ๅไธๅบ่ฏฅๅ ้ค๏ผๅฆๅไผๅฏผ่ดไธๅฑ้ๅๅ ไธบไพ่ตไธขๅคฑ่ๅบ้ใๅฎ้
ไธ๏ผ่ฟไบ้ๅไนๆฒกๅฟ
่ฆๅ ้ค๏ผๅ ไธบไนๅ่ฏด่ฟ๏ผ็ธๅ็ๅฑๅชไผๅญไธ้๏ผ่่ฟไบ้ๅๆฏๅซ็้ๅ็ไพ่ต๏ผๅ ๆญคๅนถไธไผๅ ไธบๅฎไปฌ่ขซๅๅบๆฅ่ๅคๅญไบไธไปฝ๏ผๆ ่ฎบๅฆไฝไฝ ไนไผ้่ฆๅฎไปฌใๅช่ฆๅ ้ค้ฃไบไพ่ตๅฎไปฌ็้ๅๅ๏ผ่ฟไบไพ่ต็ไธญ้ดๅฑ้ๅไนไผ่ขซ่ฟๅธฆๅ ้คใ
#ๅๅบ้จๅ้ๅ๏ผๅฆๆไธๆๅฎ็่ฏ๏ผTAG้จๅๅฏไปฅ็็ฅ
docker image ls ubuntu:18.04
#ๅ ้ค้ๅ
docker image rm ้ๅID
#ๆน้ๅ ้ค้ๅ:
docker image rm $(docker image ls -q redis)
```
ๆง่กdocker images ๅฝไปค,ๅฆไธๅพๆ็คบ๏ผ

ๅ่กจๅ
ๅซไบ **ไปๅบๅใๆ ็ญพใ้ๅ IDใๅๅปบๆถ้ด** ไปฅๅ **ๆๅ ็จ็็ฉบ้ดใ**
## Docker ๅฎนๅจๆไฝ
ๅจไนๅๆไปฌๆ่ฏดๅฐ่ฟ๏ผ้ๅไธๅฎนๅจไน้ด็ๅ
ณ็ณป็ฑปไผผไบ็ฑปไธๅฎไพไน้ด็ๅ
ณ็ณป๏ผๅจDockerไธญ๏ผๆไปฌ้่ฟ่ฟ่ก้ๅๆฅ่ทๅพไธไธช็ๅฎนๅจ๏ผๅจ่ฟ้ๆไปฌไปฅcentosไธบไพ:
```shell
docker run [้้กน] [้ๅๅๆ่
IMAGEID]
ไพ:
docker run -it centos
-it ไบคไบๅผ็ป็ซฏ่ฟ่ก
#ๆฏๅฆๅพๅคๆฏๅฆmysql้ๅ๏ผๆไปฌ้่ฆ่ฟไธชๅฎนๅจๅจๅๅฐ่ฟ่ก๏ผๅนถไธๆฏๅๅ้่ฆ่ฟๅ
ฅๅฎนๅจ็ป็ซฏ๏ผ่ฟไธชๆถๅๆไปฌๅช้่ฆๅฐ-it ๆฟๆขๆ -d ๅณๅฏๅฏๅจๅฎๆคๅผๅฎนๅจ:
docker run -d centos
```
้่ฟๆง่กไธ้ข็ๅฝไปค๏ผๆไปฌไผ่ชๅจไปฅไบคไบๆจกๅผ่ฟๅ
ฅๅฐๅฎนๅจไธญ๏ผๅฆๅพๆ็คบ:

ๅฏไปฅๅ็ฐ๏ผๆไปฌๅฎ้
ไธๅทฒ็ป่ฟๅ
ฅcentosๅฎนๅจๅ
้จ็bin/bashไบ๏ผๅจ่ฟ้๏ผๆไปฌๅฏไปฅ่พๅ
ฅ็ธๅ
ณ็ๅฝไปคๆฅๆไฝๆไปฌ็ๅฎนๅจใๅฆๆๅชๆฏๅ็บฏ็ๆณๅๅปบไธไธชๅฎนๅจ๏ผๅนถไธๆไน็ๆฅๅฏๅจ็่ฏ๏ผๅฏไปฅไฝฟ็จ**create**ๅฝไปค:
```shell
#ๅๅปบไธไธชๅฎนๅจไฝๆฏไธ็ซๅณๅฏๅจ
docker creat ้ๅๅๆ่
้ๅID
#ไพ:docker create centos
#dockerๅฎนๅจ้ป่ฎคๅฝๅ่งๅๆฏ็งๅญฆๅฎถ+ไป็ๅ็ฐ๏ผๅฆๆๆไปฌ้่ฆ่ชๅฎไน่ชๅทฑ็ๅซๅ๏ผๆฏๅฆ่ฏดcentosๅฎนๅจๅซmycentos๏ผๆไปฌ้่ฆๅ ๅ
ฅ--name้้กน
docker run -it --name [ๅซๅ] [้ๅๅ]
#ไพ:docker run -it --name mycentos centos
```
ๅฝๆไปฌๆๆไบๅบ็จๆฏๅฆtomcat้่ฆไฝฟ็จ็นๅฎ็ซฏๅฃๅๅค้จๆไพๆๅกๆถ๏ผๆไปฌๅฏไปฅไฝฟ็จ **-p** ้้กน้
็ฝฎๅฎฟไธปๆบไธๅฎนๅจไน้ด็็ซฏๅฃๆ ๅฐ๏ผไปฅtomcatไธบไพ:
```shell
docker run -it -p 8899:8080 tomcat
-p ้
็ฝฎ็ซฏๅฃๆ ๅฐ
```
่ฟๆ ท๏ผๅฝๆไปฌ่ฎฟ้ฎip:8899 ๆถ๏ผๅฐฑไผๅ็ฐๆต่งๅจๅบ็ฐไบtomcat็้ฆ้กต๏ผ่ฟไธชๆถๅ็ซฏๅฃๅฐฑๅทฒ็ปๆญฃ็กฎๆ ๅฐๅฐๅฎนๅจ้้ข8080็ซฏๅฃไธไบใ
ๅฝ็ถ๏ผ้ๅบไบคไบๅผ็ป็ซฏ๏ผDockerๅๆ ทไนๆไพไบไธค็งๆนๅผไพๆไปฌ้ๆฉ:
```shell
#้ๅบไบคไบๅผๅฝไปค็ฏๅข๏ผ่ฟ็งๆฏๆฏ่พไผ้
็้ๅบ๏ผ้ๅบๅๅฎนๅจไป็ถๅจ่ฟ่ก
Ctrl+P+Q
exit
#ไธๅคชไผ้
็ๆนๅผ๏ผ้ๅบไนๅๅฎนๅจไนไผๅๆญข
```
ๅฆๆ้ๅบไบไนๅ๏ผๆๅๆไบ๏ผๅ็ช็ถๆณๅ่ฟๅปๅฎนๅจ็ป็ซฏๅ
ๆนไธไบไธ่ฅฟ๏ผ้ๆฐ่ฟๅ
ฅๅฎนๅจไบคไบๅผ็ป็ซฏ๏ผDockerๆไพไบๅฆไธไธค็งๆนๅผ:
```shell
docker attach [ๅซๅๆIMAGEID]
##ๆจ่็ฌฌไบ็ง
docker exec -it centos bash
##docker exec ๏ผๅจ่ฟ่ก็ๅฎนๅจไธญๆง่กๅฝไปค
```
้คๅปไธ้ข่ฟไบ๏ผDocker็ๅฎนๅจ่ฟๆฏๆๅฏๅจ๏ผ้ๅฏ๏ผๅ ้ค็ญๆไฝ:
```shell
#ๅๆญขๅฎนๅจ: ๆธฉๆๅผ๏ผๆญฃๅธธๅ
ณๆบ
docker stop [ๅซๅๆIMAGEID]
#ไพ
docker stop mycentos
#ๅผบๅถๅๆญขๅฎนๅจ: ๆๆๅคด
docker kill [ๅซๅๆIMAGEID]
#ๅฏๅจๅฎนๅจ:
docker start [ๅซๅๆIMAGEID]
#้ๅฏๅฎนๅจ:
docker restart [ๅซๅๆIMAGEID]
#ๅ ้คๅฎนๅจ,ๅช่ฝๅ ้คๅๆญข็ๅฎนๅจ
docker rm [ๅซๅๆIMAGEID]
```
ๅฆๆๆณๆฅ็ๆญฃๅจ่ฟ่ก็ๅฎนๅจ๏ผๅฏไปฅไฝฟ็จไปฅไธๅฝไปค:
```shell
#ๆฅ็ๆญฃๅจ่ฟ่ก็ๅฎนๅจ
docker ps
#ๆฅ็ๆๆๅฎนๅจ๏ผๅ
ๆฌๅทฒ็ปๅๆญข็ๅฎนๅจ
docker ps -a
```
่ทๅๅฎนๅจ่พๅบไฟกๆฏ:
```shell
docker logs container
```
## ๅฎนๅจๆฐๆฎๅท:
ๅจๆไบๆ
ๅตไธ๏ผๆไปฌ้่ฆๅฎๆถๅคไปฝๅฎนๅจๅ
็ๆฐๆฎๅฐๆไปฌ็ๅฎฟไธปๆบไธ๏ผๅๆ ทๅจDockerไธญ๏ผๆฏๆฏๆๅฎนๅจไธๅฎฟไธปๆบไน้ดๅปบ็ซๅ
ฑไบซ็ฎๅฝ็๏ผไฝฟ็จ่ตทๆฅไน้ๅธธ็ฎๅ,ๅช้่ฆๅ ไธไธช **-v** ้้กนๅฐฑๅฏไปฅไบใ
```shell
#ไพ๏ผๆง่ก่ฟไนๅ๏ผๆไปฌๅจๅฎฟไธปๆบ็ฎๅฝไธญๅๅปบไธไธชๆฐๆไปถ๏ผๅฎนๅจๅ
็ฎๅฝไนไผ็ธๅบ็ๅบ็ฐ่ฟไธชๆไปถ๏ผๆไปฅๅฐฑๅฏไปฅๆmysqlๆฐๆฎๅญๆพ็็ฎๅฝ้่ฟ่ฟ็งๆนๅผๅๅฎฟไธปๆบๅ
ฑไบซ๏ผ่พพๅฐๅฎๆถๅคไปฝๆฐๆฎ็็ฎ็ใ
docker run -it -v /ๅฎฟไธปๆบ็ฎๅฝ:/ๅฎนๅจๅ
็ฎๅฝ centos /bin/bash
#ๅฆๆ้่ฆ็ปๅฎนๅจๅ
็ฎๅฝ่ฎพๅฎๆ้๏ผๅๅช้่ฆๅ ไธ ro ๅณๅฏ๏ผread -only ็็ผฉๅ
docker run -it -v /ๅฎฟไธปๆบ็ฎๅฝ:/ๅฎนๅจๅ
็ฎๅฝ:ro /bin/bash
ro ๅช่ฏป๏ผ่ฟๆ ทๆไปฌๅฎฟไธปๆบๅจๅ
ฑไบซ็ฎๅฝ้้ขๅๅปบ็ๆไปถๅจๅฎนๅจๅ
ๆฏๅช่ฏป็
#ๆฅ็ๅฎนๅจๆฏๅฆๆ่ฝฝๆๅ๏ผ
docker inspect ๅฎนๅจID
```
## ๅถไฝDocker้ๅ:
### ไฝฟ็จcommitๅฝไปคๅถไฝ้ๅ:
ๅพๅคๆถๅๆไปฌไธๅฏ้ฟๅ
็ไผๅฏนๅฎนๅจๆๆไฟฎๆน๏ผๆฏๅฆไฟฎๆนไบtomcat๏ผmysql็ญ็ญ็้
็ฝฎๆไปถ๏ผไฝๆฏๅฆๆๅ้
็ฝฎไธๅฐไธๆจกไธๆ ท็tomcatๅฎนๅจ็่ฏ๏ผๅๅ่ฆ้ๆฐไฟฎๆน้
็ฝฎๆไปถ๏ผDockerๅฏไปฅ้่ฟ**commitๅฝไปค**ๅฐ็ฐๅจ็ๅฎนๅจ้ๆฐๆๅ
ๆไธไธช้ๅ๏ผๅฆๆไฝ ็ฐๅจไฟฎๆนไบtomcatๅฎนๅจๅ
็ซฏๅฃไธบ8081็่ฏ๏ผ้ฃไนๆไปฌไฝฟ็จcommitๅฐ่ฏฅๅฎนๅจๆๅ
ๆ้ๅ็่ฏ๏ผไนๅๆไปฌ่ฟ่ก่ฟไธชๆฐ้ๅ๏ผไผๅ็ฐ้ๅ้้ขtomcat้ป่ฎค็ซฏๅฃๆฏ8081.
ๆไปฌๅฎๅถๅฅฝไบๅๅ๏ผๅนถไธๅธๆ่ฝๅฐๅ
ถไฟๅญไธๆฅๅฝขๆ้ๅใ่ฆ็ฅ้๏ผๅฝๆไปฌ่ฟ่กไธไธชๅฎนๅจ็ๆถๅ๏ผๅฆๆไธไฝฟ็จๅท็่ฏ๏ผ๏ผๆไปฌๅ็ไปปไฝๆไปถไฟฎๆน้ฝไผ่ขซ่ฎฐๅฝไบๅฎนๅจๅญๅจๅฑ้ใ่ Docker ๆไพไบไธไธช docker commit ๅฝไปค๏ผๅฏไปฅๅฐๅฎนๅจ็ๅญๅจๅฑไฟๅญไธๆฅๆไธบ้ๅใๆขๅฅ่ฏ่ฏด๏ผๅฐฑๆฏๅจๅๆ้ๅ็ๅบ็กไธ๏ผๅๅ ๅ ไธๅฎนๅจ็ๅญๅจๅฑ๏ผๅนถๆๆๆฐ็้ๅใไปฅๅๆไปฌ่ฟ่ก่ฟไธชๆฐ้ๅ็ๆถๅ๏ผๅฐฑไผๆฅๆๅๆๅฎนๅจๆๅ็ๆไปถๅๅใ
```shell
docker commit [้้กน] <ๅฎนๅจ ID ๆๅฎนๅจๅ> [<ไปๅบๅ>[:<ๆ ็ญพ>]]
#ไพ:
docker commit \
--author "<NAME> <<EMAIL>>" \
--message "ไฟฎๆนไบ้ป่ฎค็ฝ้กต" \
webserver \
nginx:v2
##ๅ
ถไธญ --author ๆฏๆๅฎไฟฎๆน็ไฝ่
๏ผ่ --message ๅๆฏ่ฎฐๅฝๆฌๆฌกไฟฎๆน็ๅ
ๅฎนใ่ฟ็นๅ git ็ๆฌๆงๅถ็ธไผผ๏ผไธ่ฟ่ฟ้่ฟไบไฟกๆฏๅฏไปฅ็็ฅ็็ฉบใ
```
### ไฝฟ็จDockerFileๆฅๅฎๅถ้ๅ:
ๅณไฝฟDockerๆไพไบcommitๆฅๅถไฝ้ๅ๏ผๅฏๆฏไพ็ถๆ่ง้บป็ฆไบ็นใๅฆๆๆไปฌๅฏไปฅๆๆฏไธๅฑไฟฎๆนใๅฎ่ฃ
ใๆๅปบใๆไฝ็ๅฝไปค ้ฝๅๅ
ฅไธไธช่ๆฌ๏ผ็จ่ฟไธช่ๆฌๆฅๆๅปบใๅฎๅถ้ๅ๏ผ้ฃไนไนๅๆๅ็ๆ ๆณ้ๅค็้ฎ้ขใ้ๅๆๅปบ้ๆๆง็้ฎ้ขใไฝ็งฏ็้ฎ้ขๅฐฑ้ฝไผ่งฃๅณใ่ฟไธช่ๆฌๅฐฑๆฏ Dockerfileใ Dockerfile ๆฏไธไธชๆๆฌๆไปถ๏ผๅ
ถๅ
ๅ
ๅซไบไธๆกๆก็ๆไปค(Instruction)๏ผๆฏไธๆกๆ ไปคๆๅปบไธๅฑ๏ผๅ ๆญคๆฏไธๆกๆไปค็ๅ
ๅฎน๏ผๅฐฑๆฏๆ่ฟฐ่ฏฅๅฑๅบๅฝๅฆไฝๆๅปบใ
็ฑไบDockerFileๆดๅๅ
ๅฎน่ฟๆฏๅพๅค็๏ผๆไปฅๅๆๆๆ็ฎๅ็ฌๆฟๅบๆฅๅๆ็ฌ่ฎฐ๏ผๆฌ็ฏๆ็ซ ไฝไธบๅ
ฅ้จๆ็จ๏ผๅฐไฝฟ็จไธไบ็ฎๅ็ๆกไพๆฅๅธฎๅฉๅคงๅฎถๅ่ฏDockerFile๏ผๅคๆ้ๅ็ๆๅปบ๏ผๅไผๅ็ฌๆพๅจไธ็ฏๆ็ซ ไธญ่ฏดๆใ
็ฑไบๆไปฌไนๅ็centos้ๅๅชไฟ็ไบcentos็ๆ ธๅฟๅ่ฝ๏ผๅพๅคๅธธ็จ็่ฝฏไปถ้ฝๆฒกๆ๏ผไบๆฏๆไปฌๆ็ฎๅถไฝไธไธช็ฎๅ็centos้ๅ๏ผๅจๅๆฅ็ๅบ็กไธไฝฟๅ
ถๆฅๆvim็ผ่พๅจๅnet-toolsๅทฅๅ
ทใ
้ฆๅ
ๆฐๅปบไธไธชDockerFileๆไปถ๏ผๅๅ
ฅไปฅไธๅ
ๅฎน:
```shell
from centos //็ปงๆฟ่ณcentos
ENV mypath /tmp //่ฎพ็ฝฎ็ฏๅขๅ้
WORKDIR $mypath //ๆๅฎๅทฅไฝ็ฎๅฝ
RUN yum -y install vim //ๆง่กyumๅฝไปคๅฎ่ฃ
vim
RUN yum -y install net-tools //ๆง่กyumๅฝไปคๅฎ่ฃ
net-tools
EXPOSE 80 //ๅฏนๅค้ป่ฎคๆด้ฒ็็ซฏๅฃๆฏ80
CMD /bin/bash //CMD ๅฎนๅจๅฏๅจๅฝไปค๏ผๅจ่ฟ่กๅฎนๅจ็ๆถๅไผ่ชๅจๆง่ก่ฟ่กๅฝไปค๏ผๆฏๅฆๅฝๆไปฌ docker run -it centos ็ๆถๅ๏ผๅฐฑไผ็ดๆฅ่ฟๅ
ฅbash
```
็ถๅ็ผ่ฏ่ฏฅ้ๅ:
```shell
็ถๅ็ผ่ฏ่ฏฅ้ๅ
docker build -f ./DockerFile -t mycentos:1.3.
-t ๆฐ้ๅๅๅญ:็ๆฌ
-f ๆไปถ -d ๆไปถๅคน
```
ไนๅๆไปฌๆง่กdocker imagesๅฝไปคๅฐฑไผๅบ็ฐๆไปฌๆๅปบๅฅฝ็ๆฐ้ๅ๏ผ mycentos:1.3 ๏ผ่ฟ่ก่ฏฅ้ๅ๏ผไผๅ็ฐvimๅnet-tools ๆฏๅฏไปฅๆญฃๅธธไฝฟ็จ็ใ
ๆๅๅฐฑๅคงๅๅๆๅฆใ
## ไธ้ขๅผๅงๆๆฏๆป็ป:
ๆฌ็ฏๆ็ซ ๅข๏ผๆไปฌ่ฎฒ่งฃไบDockerๅธธ่ง็ๅฝไปค่ก็ไฝฟ็จๅ่งฃ้๏ผไปฅๅDockerFile็็ฎๅๅ
ฅ้จ๏ผไธไธ็ฏๅข๏ผๆไปฌๅฐไปDockerFileๅ
ฅๆ๏ผๅผๅง่ฏฆ็ป็ไบ่งฃๅปๆไนๅปๅถไฝๅๅๅธไธไธช่ชๅทฑ็้ๅใ
ๆๅ๏ผ็ธๅ
ณ็ฌ่ฎฐๅทฒ็ปๅๆญฅๅผๆบ่ณGithub(**ๆฌข่ฟstar**)๏ผ:
https://github.com/hanshuaikang/HanShu-Note
<file_sep># Spring ไบไปถ้ฉฑๅจ็ผ็จ
่ฐๅฐSpring ไบไปถ้ฉฑๅจๆจกๅ๏ผๆๆณๅคงๅฎถ้ฝไธ้็๏ผไบไปถ้ฉฑๅจๆจกๅ๏ผ้ๅธธไนๅฏไปฅ่ฏดๆฏ่งๅฏ่
่ฎพ่ฎกๆจกๅผ๏ผๅฏน่งๅฏ่
่ฎพ่ฎกๆจกๅผไธ็ๆ็ๆๅๅฏไปฅ็ๆไนๅๅ็็ฌ่ฎฐ๏ผ[่ฎพ่ฎกๆจกๅผjava่ฏญ่จๅฎ็ฐไน่งๅฏ่
ๆจกๅผ](https://zhuanlan.zhihu.com/p/56032704)๏ผๅจjavaไบไปถ้ฉฑๅจ็ๆฏๆไธญ๏ผEventBusๅ็งปๅจ็ซฏๅผๅ็ๆๅๅบ่ฏฅ้ฝๆฏ่พไบ่งฃ๏ผๅ
ถๅฎ๏ผjavaๆฌ่บซไน่ชๅธฆไบๅฏนไบไปถ้ฉฑๅจ็ๆฏๆ๏ผไฝๆฏๅคง้จๅ้ฝๆฏ็จไบๆไปฌ็ๅฎขๆท็ซฏๅผๅ๏ผๆฏๅฆGUI ๏ผSwing่ฟไบ๏ผ่Spring ๅๅจjava็ๅบ็กไธ๏ผๆฉๅฑไบๅฏนไบไปถ้ฉฑๅจ็ๆฏๆใ
ไธ่ฏดๅบ่ฏ๏ผ็ดๆฅไธไปฃ็
## 1.ไปฃ็ ๅฎๆ
้ฆๅ
๏ผๆไปฌๆฐๅปบไธไธช็ฑปNotifyEvent ็ปงๆฟApplicationEvent๏ผ็จไบๅฐ่ฃ
ๆไปฌไบไปถ้ขๅค็ไฟกๆฏ๏ผ่ฟ้ๅๆฏString็ฑปๅ็msg๏ผ็จไบ่ฎฐๅฝ่ฏฆ็ป็ไบไปถๅ
ๅฎนใ
```java
public class NotifyEvent extends ApplicationEvent {
private String msg;
public NotifyEvent(Object source, String msg) {
super(source);
this.msg = msg;
}
public String getMsg() {
return msg;
}
}
```
ๅ
ถไธญ๏ผApplicationEvent ๆฏไธไธชๆฝ่ฑก็ฑป๏ผๆฉๅฑไบjavaๆฌ่บซ็EventObject ็ฑป๏ผๆฏไธไธช็ปงๆฟไบApplicationEvent็ๅญ็ฑป้ฝ่กจ็คบไธ็ฑปไบไปถ๏ผๅฏไปฅๆบๅธฆๆฐๆฎใ
็ถๅๆฐๅปบไธไธชNotifyPublisher็จไบๆไปฌไบไปถ็ๅๅธๅทฅไฝ๏ผ่ฏฅ็ฑปๅฎ็ฐไบApplicationContextAwareๅนถ้ๅไบsetApplicationContext ๆนๆณ๏ผ่ฟไธๆญฅ็็ฎ็ๆฏๅฏไปฅ่ทๅๆไปฌSpring็ๅบ็จไธไธๆ๏ผๅ ไธบไบไปถ็ๅๅธๆฏ้่ฆๅบ็จไธไธๆๆฅๅ็๏ผไธไบ่งฃๅบ็จไธไธๆ็ๅๅญฆๅฏไปฅๅป็ๆ็ๅฆๅคไธ็ฏ็ฌ่ฎฐ:[ๅฐๅบไปไนๆฏไธไธๆ๏ผ](https://juejin.im/post/5d8ebf8ef265da5b633cc90f)
```java
@Component //ๅฃฐๆๆ็ปไปถ๏ผไธบไบๅๆๆณจๅ
ฅๆนไพฟ
public class NotifyPublisher implements ApplicationContextAware {
private ApplicationContext ctx; //ๅบ็จไธไธๆ
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.ctx= applicationContext;
}
// ๅๅธไธไธชๆถๆฏ๏ผ่ฟ้ๅคงๅฎถๅฏไปฅๆ นๆฎไธๅ็็ถๆๅฎ็ฐๅๅธไธๅ็ไบไปถ๏ผๆ่ฟ้ๅฐฑๅชๅไบไธไธชไบไปถ็ฑป๏ผๆไปฅif else
//้ฝๅๅธNotifyEventไบไปถใ
public void publishEvent(int status, String msg) {
if (status == 0) {
ctx.publishEvent(new NotifyEvent(this, msg));
} else {
ctx.publishEvent(new NotifyEvent(this,msg)) ;
}
}
}
```
ๆๅไธๆญฅๅฐฑๆฏๅฎ็ฐไธไธช็ฑปไฝไธบไบไปถ็่ฎข้
่
ๅฆ๏ผๅฝไบไปถๅๅธๆถ๏ผไผ้็ฅ่ฎข้
่
๏ผ็ถๅ่ฎข้
่
ๅ็ธๅ
ณ็ๅค็๏ผๆฏๅฆๆฐ็จๆทๆณจๅๅ้ไบไปถ่ชๅจๅ้ๆฌข่ฟ้ฎไปถ็ญ็ญใๅๆถ๏ผSpring 4.2 ็ๆฌๆดๆฐ็EventListener๏ผๅฏไปฅๅพๆนไพฟๅธฎๅฉๆไปฌๅฎ็ฐไบไปถไธๆนๆณ็็ปๅฎ๏ผๅช้่ฆๅจ็ฎๆ ๆนๆณไธๅ ไธEventListenerๅณๅฏใ
```java
@Component
public class NotifyListener {
@EventListener
//ๅๆฐNotifyEvent ๏ผๅฝๆNotifyEvent ็ฑปๅ็ไบไปถๅ็ๆถ๏ผไบค็ปsayHelloๆนๆณๅค็
public void sayHello(NotifyEvent notifyEvent){
System.out.println("ๆถๅฐไบไปถ:"+notifyEvent.getMsg());
}
}
```
**ๆต่ฏ๏ผ**็ผๅๆไปฌ็ๆต่ฏ็ฑปTestControllerใ
```java
@RestController
public class TestController {
@Autowired
private NotifyPublisher notifyPublisher;
@GetMapping("/sayHello")
public String sayHello(){
notifyPublisher.publishEvent(1, "ๆๅๅธไบไธไธชไบไปถ");
return "Hello Word";
}
}
```
ๅฏๅจๆไปฌ็ๅบ็จ๏ผๅจๆต่งๅจไธญ่พๅ
ฅhttp://127.0.0.1:8080/sayHello๏ผๆงๅถๅฐ่พๅบ:
```text
2019-09-28 16:55:51.902 INFO 716 --- [on(4)-1172.16.17.32] o.s.web.servlet.DispatcherServlet : Completed initialization in 12 ms
ๆถๅฐไบไปถ:ๆๅๅธไบไธไธชไบไปถ
```
ๅไธช็ฅ่ฏ็น:
> ๅฆๆไธไธชๆฐ็ไบไปถ็ปงๆฟไบNotifyEvent๏ผๅฝๆไปฌๆจ้NotifyEvent็ฑปๅ็ไบไปถๆถ๏ผNotifyEventๅๅ
ถๅญ็ฑป็็ๅฌๅจ้ฝๅฏไปฅๆถๅฐ่ฏฅไบไปถใ
ๅฎไบๅ๏ผ่ฟๆฒกๆ๏ผๆฅๅธธ้คไบๅฌๅฐ่ฟไบไปถ้ฉฑๅจ็ผ็จ๏ผๅถๅฐ่ฟไผ่งๅฐๅผๆญฅไบไปถ้ฉฑๅจ็ผ็จ่ฟๅ ไธชๅญ๏ผๅๆ ท็Spring ไนๆไพไบ@Async ๆณจ่งฃๆฅๅฎ็ฐๅผๆญฅไบไปถ็ๆถ่ดนใ็จ่ตทๆฅไนๅพ็ฎๅ๏ผๅช้่ฆๅจ @EventListenerไธๅ ไธ@Async ๅฐฑๅฅฝไบใ
## 2. Spring ๅผๆญฅไบไปถๅฎ็ฐ:
**ไปฃ็ ๅฆไธ๏ผ**
```java
@Component
public class NotifyListener {
@Async
@EventListener
public void sayHello(NotifyEvent notifyEvent){
System.out.println("ๆถๅฐไบไปถ:"+notifyEvent.getMsg());
}
}
```
ๆๅ้
็ฝฎไธไธช็บฟ็จๆฑ
```java
@Configuration
@EnableAsync
public class AysncListenerConfig implements AsyncConfigurer {
/**
* ่ทๅๅผๆญฅ็บฟ็จๆฑ ๆง่กๅฏน่ฑก
*
* @return
*/
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.initialize();
executor.setCorePoolSize(10); //ๆ ธๅฟ็บฟ็จๆฐ
executor.setMaxPoolSize(20); //ๆๅคง็บฟ็จๆฐ
executor.setQueueCapacity(1000); //้ๅๅคงๅฐ
executor.setKeepAliveSeconds(300); //็บฟ็จๆๅคง็ฉบ้ฒๆถ้ด
executor.setThreadNamePrefix("ics-Executor-"); ////ๆๅฎ็จไบๆฐๅๅปบ็็บฟ็จๅ็งฐ็ๅ็ผใ
executor.setRejectedExecutionHandler(
new ThreadPoolExecutor.CallerRunsPolicy()); // ๆ็ป็ญ็ฅ
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
}
```
```java
public class ExceptionHandlingAsyncTaskExecutor implements AsyncTaskExecutor {
private AsyncTaskExecutor executor;
public ExceptionHandlingAsyncTaskExecutor(AsyncTaskExecutor executor) {
this.executor = executor;
}
//็จ็ฌ็ซ็็บฟ็จๆฅๅ
่ฃ
๏ผ@Asyncๅ
ถๆฌ่ดจๅฐฑๆฏๅฆๆญค
public void execute(Runnable task) {
executor.execute(createWrappedRunnable(task));
}
public void execute(Runnable task, long startTimeout) {
//็จ็ฌ็ซ็็บฟ็จๆฅๅ
่ฃ
๏ผ@Asyncๅ
ถๆฌ่ดจๅฐฑๆฏๅฆๆญค
executor.execute(createWrappedRunnable(task), startTimeout);
}
public Future submit(Runnable task) { return executor.submit(createWrappedRunnable(task));
//็จ็ฌ็ซ็็บฟ็จๆฅๅ
่ฃ
๏ผ@Asyncๅ
ถๆฌ่ดจๅฐฑๆฏๅฆๆญคใ
}
public Future submit(final Callable task) {
//็จ็ฌ็ซ็็บฟ็จๆฅๅ
่ฃ
๏ผ@Asyncๅ
ถๆฌ่ดจๅฐฑๆฏๅฆๆญคใ
return executor.submit(createCallable(task));
}
private Callable createCallable(final Callable task) {
return new Callable(){
@Override
public Object call() throws Exception {
try {
return task.call();
} catch (Exception ex) {
handle(ex);
throw ex;
}
}
};
}
private Runnable createWrappedRunnable(final Runnable task) {
return new Runnable() {
public void run() {
try {
task.run();
} catch (Exception ex) {
handle(ex);
}
}
};
}
private void handle(Exception ex) {
//ๅ
ทไฝ็ๅผๅธธ้ป่พๅค็็ๅฐๆน
System.err.println("Error during @Async execution: " + ex);
}
}
```
**ๆต่ฏ๏ผ**็ผๅๆไปฌ็ๆต่ฏ็ฑปTestControllerใ
```text
2019-09-28 16:55:51.902 INFO 716 --- [on(4)-127.0.0.1] o.s.web.servlet.DispatcherServlet : Completed initialization in 12 ms
ๆถๅฐไบไปถ:ๆๅๅธไบไธไธชไบไปถ
```
ๅคงๅๅๆๅฆใ
็ธๅ
ณ็ตๅญ็็ฌ่ฎฐๅทฒ็ปๅผๆบ่ณgithub๏ผๆฌข่ฟstarๅฆ๏ผ:
<https://github.com/hanshuaikang/HanShu-Note>
<file_sep>package com.jdkcb.demo.event;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
@Configuration
@EnableAsync
public class AysncListenerConfig implements AsyncConfigurer {
/**
* ่ทๅๅผๆญฅ็บฟ็จๆฑ ๆง่กๅฏน่ฑก
*
* @return
*/
@Override
@Bean(name = "taskExecutor")
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.initialize();
executor.setCorePoolSize(10); //ๆ ธๅฟ็บฟ็จๆฐ
executor.setMaxPoolSize(20); //ๆๅคง็บฟ็จๆฐ
executor.setQueueCapacity(1000); //้ๅๅคงๅฐ
executor.setKeepAliveSeconds(300); //็บฟ็จๆๅคง็ฉบ้ฒๆถ้ด
executor.setThreadNamePrefix("ics-Executor-"); ////ๆๅฎ็จไบๆฐๅๅปบ็็บฟ็จๅ็งฐ็ๅ็ผใ
executor.setRejectedExecutionHandler(
new ThreadPoolExecutor.CallerRunsPolicy()); // ๆ็ป็ญ็ฅ
return new ExceptionHandlingAsyncTaskExecutor(executor);
}
}
<file_sep># Jvmๅ
ๅญๅๆถ็ปๆๅฅฅไน:ๅๅพๆถ้ๅจ
## ๅ่จ:
ไนๅๅจ[ไธไธชjavaๅฏน่ฑก็ๆญปไบก่ฏๆ](https://juejin.im/post/5d5a00b7f265da03bd051b59)ๆไปฌ่ฎฒไบไธไธชๅฏน่ฑกๆฏๅฆไฝ่ขซๅคๅฎไธบๆญปไบก็๏ผๅนถๅจไนๅ็ [Jvmๅ
ๅญๅๆถ็ปๆๅฅฅไน๏ผๅๅพๆถ้็ฎๆณ](https://juejin.im/post/5d5ca0fbf265da03e921cdde)่ฏฆ็ป็ไป็ปไบ็ฎๅ่พไธบๆต่ก็ๅ็งๅๅพๅๆถ็ฎๆณ๏ผๅๆฅๅๅคง่ๆๆบๅ
ๅ้ช่ฏไบ่ฟๅ็ง็ฎๆณ็ๅฏ่กๆง๏ผๆ่ฐๆ้ๆฑๅฐฑไผๆๅธๅบ๏ผๆฌ็**ๅๆถๅๅพ๏ผๆๆกๆ ธๅฟ็งๆ**็ๅผบๅคงไฟกๅฟต๏ผๅๅพๅ
ฌๅธๅบ่ฟ่็ไบ(ไฝ ็กฎๅฎไธๆฏๅจ้ชไบบ?),ๅๅพๅ
ฌๅธไธๅฃๆฐๆจๅบไบ่ฆ็ๅๅคงๅบๆฏ็ไธ็งๅๅพๅๆถๅจไพๅนฟๅคงๆถ่ดน่
้ๆฉ๏ผไธ่ดนๅน็ฐไนๅๅ ้ขไบ็พๅไน90็ๅธๅบไปฝ้ข๏ผๅ
ฌๅธๆ็ซไธๅคฉ๏ผ็ซ้ไธๅธ๏ผ่็ซไบ่
ไปฌๅ่ขซๅฎๆๅปไบ้ๆดฒ๏ผๆ
ไบๅฐ่ฟ้๏ผJVMๅฎๅฎๆญฃๅผๅฝขๆไบใ
ๆฏ็๏ผไธๆฌๆญฃ็ป็่ก่ฏดๅ
ซ้ใ
่ฟไธ็งไบงๅๅๅซไธบ:
- ๅ็บฟ็จๅๅพๆถ้ๅฐ็ๅญ๏ผ**Serialๆถ้ๅจ**
- ๅค็บฟ็จๅๅพๆถ้ๅฐ็ๅญ๏ผ**ParNew ๆถ้ๅจ**
- ๅๅ้ไผๅ
ๅฐ็ๅญ๏ผ**Parallel Scavengeๆถ้ๅจ**
- ๅ็บฟ็จๅๅพๆถ้่็ๅญ ๏ผ**Serial Oldๆถ้ๅจ**
- ๅค็บฟ็จๅๅพๆถ้่็ๅญ:**ParNew Old ๆถ้ๅจ**
- ๅๅพๆถ้ๅจๆๆฅไนๆ๏ผ**CMSๆถ้ๅจ**
- ๆฅ่ชๆชๆฅ็ๆฌกไธไปฃๆถ้ๅจ๏ผ**G1ๆถ้ๅจ**
ๅญ็ๅจๅๅพๅๆถ้ขๅ็ไผ็ง่กจ็ฐ๏ผๆ ๆฐๆฌกๆฏๆไบๅ
ๅญๅฑๆบ๏ผๅฎไปฌ่ขซๅไบบ็งฐไธบ**ๅๅพๅๆถ่
่็**
## Serialๆถ้ๅจ:
้ฆๅ
็ฌฌไธไธชไธๅบ็ๆฏSerialๆถ้ๅจ๏ผๅฎๆฏๆๆๆถ้ๅจ้้ขๅนด้พๆๅคง็ๆถ้ๅจ๏ผๅจjdk1.3ไนๅ้ฃ็ฉ่ดจ่ดซ็ ็ๆถไปฃ๏ผSerialๆถ้ๅจๅฐฑๅIEไธๆ ทๆฏๅฏไธ็้ๆฉ๏ผSerial็ๅๅพๆถ้ๆนๅผๆ็น็ฑปไผผไบๆไปฌๅนณๅธธ็ไฟๆด้ฟๅงจ๏ผๆถ้ๅๅพ็ๆถๅ๏ผไผๅ
ๅ่ฏๅจๅบ็ๆๆ็บฟ็จ๏ผ
**ไฝ ๏ผไฝ ๏ผไฝ ๏ผๅซๅจ๏ผๅๆซๅฎ**
Serialๆถ้ๅจๅทฅไฝ็ๆถๅไผๆๅๆๅ
ถไปๅทฅไฝ็บฟ็จ๏ผ็ดๅฐๅฎๆถ้็ปๆ๏ผ่ฟๅฏนๅพๅคๅบ็จๆฏ้พไปฅๆฅๅ็๏ผๆฏๅฆไฝ ๅๆไธๆฌพๆธธๆjava่ฃ่๏ผๆญฃๅๅคๅขๆๅข๏ผSerialๆถ้ๅจ็ซๅบๆฅ่ฏด๏ผๅผๅผไปฌๅ
ๅพ่พนไธ้ ้ ๏ผๆ่ฆๆฅๆถ้ๅๅพไบ๏ผ็ปไฝ ๆๅไธชไบๅ้๏ผ่ฐๅๅพไบ๏ผไธ้ขๆฏSerialๆถ้ๅจ็่ฟ่ก่ฟ็จ๏ผๅ
ถไธญๆฐ็ไปฃไฝฟ็จ็ๆฏ**ๅคๅถ็ฎๆณ**๏ผ่็ไปฃไฝฟ็จ**ๆ ่ฎฐ-ๆด็็ฎๆณ**

่ฏป่
็ๅฐ่ฟ้่ฏๅฎไผ่ฏดไบ๏ผ่ฟๅๅพๆถ้ๅจไนๅคชๅๅพไบๅง๏ผๅ
ถๅฎไธ็ถ๏ผSerial็ไธไธ๏ผๅ็บฟ็จ๏ผๆถ้ๅจๅชๆไธไธชๅ
ๆ ธ็็ณป็ปไธญๅ ไธบไธ้่ฆๅปๅๅ
ถไปๅๆถ็บฟ็จ่ฟ่กไบคไบ๏ผๅ่ๆ็ๆด้ซไธ็นใ
## ParNew ๆถ้ๅจ๏ผ
ParNew ๆถ้ๅจๅข๏ผๅ
ถๅฎๅฐฑๆฏSerialๆถ้ๅจ็ๅค็บฟ็จ็ๆฌ๏ผๅ
ถไธญ็จๅฐ็ๆถ้็ฎๆณ๏ผStop the word๏ผๅ้กฟ็ฑปๅSTW๏ผๆๅๅ
ถไป็บฟ็จ๏ผ๏ผๅฏน่ฑกๅ้
่งๅ๏ผๅๆถ็ญ็ฅๅ ไน้ฝไธSerialๆถ้ๅจไธๆจกไธๆ ท๏ผไฝ้ๅบไบ่่่ไบ่๏ผParNewๅจๅฎ่กๅๅพๅๆถ็ๆถๅๆฏ้็จๅค็บฟ็จ็๏ผๅฝ็ถ๏ผ่ฟๅนถไธ่ถณไปฅไฝฟๅฎ็ซ่ถณไบjava่ๆๆบ็็็ฑ๏ผๅฎๆๅคง็ไผๅฟๅฐฑๆฏๅCMSๅ
ณ็ณป็นๅฅฝ๏ผๅ ไนๆฏๆๆๅญ็ๅ
ๅผ๏ผไฟฉไบบๅไฝ่ตทๆฅ้ปๅฅๅ่ถณ๏ผ่่ฟไบ๏ผSerial ๅ Parallel Scavengeๆถ้ๅจๅฐฑๅช่ฝ็ธๅฝข่ง็ปไบ๏ผๅฏ่ง๏ผไธไธชๅฅฝ็้ๅๆฏๅคไน้่ฆใParNew็ๅทฅไฝ่ฟ็จๅฆไธๅพๆ็คบ:

ไฝ ่ฟๅพ็็ๆ็นๆๅ๏ผๅคงๅฎถไธ่ฆๅจๆ่ฟไบ็ป่๏ผ้
ไฝๆฏparNewๆถ้ๅจๅนถไธๆฏ่ฏดๅ ไธบๅ ไบๅค็บฟ็จๅฐฑๅฎ็Serialๆถ้ๅจไบ๏ผๅฝๅชๆไธไธชๅ
ๆ ธ็ๆถๅ๏ผParNew็ๆ็ๅฐฑ้ๅธธๆฒกๆSerialๆถ้ๅจ้ซ๏ผๅๅ ๅจไบไธไธชๅฐๆฟ้ดไธไธชๆๆซ่ตทๆฅๆฏๅไธชไบบๆซ่ตทๆฅๅฟซ๏ผๅ ไธบๆฒกๆไบ็ธๆฒ้็ๆๆฌ๏ผไฝ้็ๅ
ๆ ธไธชๆฐ็ๅขๅ ๏ผParNew็ไผๅฟๆไผ้ๆธไฝ็ฐๅบๆฅใ
## Parallel Scavengeๆถ้ๅจ๏ผ
ๅทงไบ๏ผParallel Scavengeๆฏไธไธชๆฐ็ไปฃๆถ้ๅจ๏ผๅParNewๆถ้ๅจๅจๅค็บฟ็จ๏ผๅคๅถ็ฎๆณๅๅ ไนๅทฎไธๅค๏ผ้ฃไป็ฉถ็ซๅจๅชไบ๏ผๆฒก้๏ผๆฏIdea๏ผๅฝๅซ็ๅๅพๆถ้ๅจ้ฝๅจๆผๅฝๅๅฐ็จๆท็บฟ็จๅ้กฟๆถ้ด็ๆถๅ๏ผๅฎๅฆ่พ่นๅพ๏ผ้ๆฉไบ**ๅๅ้**ไผๅ
ใ
PS:ๅๅ้ = ็จๆท่ฟ่กไปฃ็ ๆถ้ด/๏ผ็จๆท่ฟ่กไปฃ็ ๆถ้ด+ๅๅพๆถ้ๅจๆถ้ด๏ผ
ๅๅ้่ถ้ซๆๅณ็็จๆทไปฃ็ ่ฟ่ก็ๆถ้ดๅฐฑ่ถ้ซ๏ผ่ฟ้ๅผ็จๆทฑๅ
ฅ็่งฃjvm่ๆๆบไธญ็ๅๆ๏ผๆ่งๆๆไน่ฏดไนๆฒกไฝ่
่ฏดๅพๅฅฝใ
> ๅ้กฟๆถ้ด่ถ็ญ่ถ้ๅ้่ฆไธ็จๆทไบคไบ็็จๅบ๏ผ่ฏๅฅฝ็็ธๅบ้ๅบฆ่ฝๆๅ็จๆทไฝ้ช๏ผ่้ซๅๅ้ๅๅฏไปฅ้ซๆ็ๅฉ็จCPUๆถ้ด๏ผๅฐฝๅฟซๅฎๆ็จๅบ็่ฟ็ฎไปปๅก๏ผไธป่ฆ้ๅๅจๅๅฐ่ฟ็ฎ่ไธ้่ฆๅคชๅคไบคไบ็ไปปๅกใ
ๅญๅจๆๆ็นไฝ๏ผๆฒกๆๅพ๏ผ๏ผ๏ผ
## Serial Oldๆถ้ๅจ๏ผ
Serial Oldๆถ้ๅจๆฏSerialๆถ้ๅจ็่ๅนดไปฃ็ๆฌ๏ผๅฎๅๆ ทๆฏๅ็บฟ็จ็ๆถ้ๅจ๏ผไฝฟ็จ**ๆ ่ฎฐ-ๆด็็ฎๆณ**๏ผๅฎไธป่ฆๅทฅไฝๅจClientๆจกๅผ๏ผไธค็นๅข๏ผ็ฑไบParallel Scavengeๆถ้ๅจๅSerialๅcmsๆถ้ๅจๅ
ณ็ณป้ฝไธๅคชๅฅฝ๏ผๆๆๅฎไปฌไธคไธชๆไบๅฅฝๆๅ๏ผไธไธชๆฐ็ไปฃ๏ผไธไธช่ๅนดไปฃ๏ผๆไปฅๅฏไปฅ้
ๅไฝฟ็จ๏ผ็ฌฌไบไธชๆฏไฝไธบCMSๆถ้ๅจ็ๅๅค้ขๆกใๅฎ็ๅทฅไฝๅพๅฆไธๆ็คบ๏ผ

## ParNew Old ๆถ้ๅจ๏ผ
ๅๆ ท็๏ผParNew Oldๆถ้ๅจๅๆฏParNewๆถ้ๅจ็่ๅนดไปฃ็ๆฌไบ๏ผไฝฟ็จ**ๅค็บฟ็จ**ๅ**ๆ ่ฎฐ-ๆด็็ฎๆณ**๏ผ็ฑไบไธๆๆไปฌ่ฏดๅฐ๏ผParallel Scavengeๆถ้ๅจๅCMSๆถ้ๅจๅฐคๅ
ถไธๅ๏ผๆไปฅๅฆๆไธๆฆ้ๆฉไบParallel Scavengeๆถ้ๅจไฝไธบๆฐ็ไปฃๆถ้ๅจ็่ฏ๏ผ้ฃไนๅฐฑๆๅณ็่ๅนดไปฃๆถ้ๅจๆไปฌๅช่ฝ้Serial Oldๆถ้ๅจ๏ผ่Serial Oldๆถ้ๅจๅฑไบๅ็บฟ็จๅค็ๅจ๏ผ้พๅ
ไผๆ็ๆง่ฝไธ็้ฎ้ข๏ผๆไปฅ่ฟๅฐฑๆฏ่พ่็ผไบ๏ผ็ฎ็ดๅฐฑๆฏๆ็ป้ๅฎ๏ผ่ฟไธๅ็ดๅฐParNew Old ๆถ้ๅจ็้ขไธๆๅพๅฐ่งฃๅณ๏ผ่ณๆญค๏ผParallel Scavengeๆถ้ๅจ+ParNew Old ๆถ้ๅจๆ็ฎๆฏ็ๆญฃ็ๅฎ็ฐไบๅๅ้ไผๅ
็่ณ่ป็ปๅใ
ไธๅพๆฏParNew Old ๆถ้ๅจ่ฟ่ก็คบๆๅพ:

## CMSๆถ้ๅจ๏ผ
CMSๆถ้ๅจ๏ผๅ
จ็งฐConcurrent Mark Sweep ๆถ้ๅจ๏ผๅๅคงๅคๆฐๆถ้ๅจ็ฑปไผผ๏ผไนๆฏ่ดๅไบ็ผฉ็ญ็บฟ็จๅ้กฟๆถ้ด็ๅๅพๆถ้ๅจใๆฌ่บซ้็จ็ๆฏ่ฟ้ถ็็**ๆ ่ฎฐ-ๆธ
้ค็ฎๆณ**๏ผ
ไธป่ฆๅไธบๅไธชๆต็จ๏ผ
1. ๅๅงๆ ่ฎฐ
2. ๅนถๅๆ ่ฎฐ
3. ้ๆฐๆ ่ฎฐ
4. ๅนถๅๆธ
้ค
ๅ
ถไธญๅนถๅๆ ่ฎฐๅๅนถๅๆธ
้ค่ฟไธคไธชๅ็ๆญฃๅทฅไฝ็ๅ ๆฎไบๆดไธชๅๅพๅๆถ่ฟ็จ็็ปๅคงๅคๆฐๆถ้ดใๅๅงๆ ่ฎฐๅฏไปฅ่ฏดๆฏๅ
ๆฅๅ็ฅ็็ไธ็ผ๏ผ่ฑไธไบๅคๆฌกๆถ้ด๏ผ้ๆฐๆ ่ฎฐๅๆฏ็็ๅชไธช่ขซๆ ่ฎฐ็ๆนๅจไบ๏ผไนๆฏๅพๅฟซๅฐฑๅฎๆ็ใ
ๆง่กๆต็จๅฆไธ:

่ฝ็ถCMSๆถ้ๅจๆฏไปๆฅไนๆๆถ้ๅจ๏ผไฝๆฏไนๅนถ้ๅฎๅ
จๆฒกๆ็ผบ้ท๏ผๅ
ถไธญๆไธไธชๆฏ่พๆๆพ็้ฎ้ขใ
- ็ฌฌไธไธชๅฐฑๆฏCMSๆถ้ๅจไฝฟ็จ็ๆ ่ฎฐ-ๆธ
้ค็ฎๆณไผๅฏผ่ดๅคง้็็ฉบ้ด็ข็๏ผ่ตทๅๅ ๆๅทฒ็ปๅจไธ็ฏๆ็ซ ๅๅพๆถ้็ฎๆณๆ่ฏดๆ๏ผไธไบ่งฃ็ๆๅๅฏไปฅๅป็ไธไธใ
- ็ฌฌไบไธชๅๆฏๅฏนCPU่ตๆบ้ๅธธๆๆ๏ผๅคงๅฎถๆณ๏ผๆต็จๅพ้ฃไนๅค็บฟ็จ๏ผๅฝCPUๅค็ๆถๅ่ฟ่ฝๆฅๅ๏ผๆๅฎถๅบๅ๏ผไฝ ๅๅพๅคไนๅทฎไธๅค่ฝๅ
ป่ตท๏ผๅฏๆฏๅฝCPUๆฐ้ๆฏ่พๅฐ็ๆถๅ๏ผๅฐฑ็ธๅฝไบไธไธชๆฏไบฒๅ
ปไธๅ ๅทๅทๅพ
ๅบ็ๅญฉๅญ๏ผๅฐฑไผๅพๅๅ๏ผ็ธๅบ็ไนไผๅฏผ่ดๆไปฌๅบ็จๆง่ฝ็ไธ้ใ
- ็ฌฌไธไธชๅฐฑๆฏๆฒกๅๆณๅๆถโๆตฎๅจๅๅพโ๏ผ่ฟไธชๆตฎๅจๅๅพๆฏไปไนๆๆๅข๏ผๅคงๅฎถ่ฟไน็่งฃ๏ผไฝ ๅจๅฎถๆซๅฐๅข๏ผไฝ ๅผๅผๅจๆ่พนๅ็ๅญ๏ผๅฝไฝ ๆซๅฐไฝ ๅผๅผ้ฃ่พน็ๆถๅ๏ผไฝ ่พนๆซๅฎ่พนๅพไฝ ๆซๅนฒๅ็ๅฐๆนไป๏ผไฝๆฏ๏ผ่ๆๆบ่งๅฎไฝ ไธๆฌกๅช่ฝๆซไธๆฌก๏ผๆฒกๆณๅๅป๏ผๆไปฅไฝ ๅพ็ญไธไธๆฌกๆซ็ๆถๅๅจๅค็่ฟไบๅๅพใๆไปฅ๏ผCMSๆ ๆณๅๆถๅชไบ็บฟ็จๅจๅๆถ็่ฟ็จไธญๅ ไธบ่ฟ่ก่ไบง็็ๆฐๅๅพใ
## G1ๆถ้ๅจ:
G1ๆถ้ๅจๆ็งฐๅฎไธบ**ๆฌกไธไปฃๅๅพๆถ้ๅจ**๏ผไธๆฌพๆฅ่ชๆชๆฅ็ๅๅพๆถ้ๅจ๏ผ็ๅฎ็่ฎฒๅข๏ผๅฐฑๆฏG1ๆฏๅฝไปๅๅพๆถ้ๅจๅๅฑ็ๆๅๆฒฟ็ๆๆไนไธ๏ผไฝๆฏ๏ผ็ฑไบไธไบ้ฎ้ขๆฒกๆ่งฃๅณๆไปฅ่ฟ่ฟไธ่ฝไธๅธ๏ผ็ดๅฐJDK7ๆๆญฃๅผๅ ๅ
ฅjvm่ๆๆบๅคงๅฎถๅบญ๏ผJDK9ๆไฝไธบ้ป่ฎค็ๅๅพๅๆถๅจ๏ผ
G1็ๅบ็ฐไธๆฏๅทฅ็จๅธไปฌ่งๅพๅๅพๅๆถๅจๅคชๅฐๅ้ไพฟๅ ไธช๏ผๆ นๆฎๆไปฌไปฅๅพ็ๅๅฒ็ป้ช๏ผไธๆฌพๆฐๆๆฏ็่ฏ็ๅฟ
ๅฎๆฏไธบไบๅผฅ่กฅๆงๆๆฏ็ไธ่ถณ๏ผG1ๅๆ ทๆฏไธบไบๅผฅ่กฅCMSๅๅพๆถ้ๅจ็ไธไบ้ฎ้ข่่ฏ็็๏ผ็ธๅฏนไบCMSๅๅพๅๆถๅจ๏ผG1็ไธป่ฆๆๅไธป่ฆๅจๅฆไธๅ ไธชๆน้ข:
- G1ๅจๅ็ผฉ็ฉบ้ดๆน้ขๆไผๅฟ
- G1้่ฟๅฐๅ
ๅญ็ฉบ้ดๅๆๅบๅ๏ผRegion๏ผ็ๆนๅผ้ฟๅ
ๅ
ๅญ็ข็้ฎ้ข Eden, Survivor, Oldๅบไธๅๅบๅฎใๅจๅ
ๅญไฝฟ็จๆ็ไธๆฅ่ฏดๆด็ตๆดป
- G1ๅฏไปฅ้่ฟ่ฎพ็ฝฎ้ขๆๅ้กฟๆถ้ด๏ผPause Time๏ผๆฅๆงๅถๅๅพๆถ้ๆถ้ด้ฟๅ
ๅบ็จ้ชๅดฉ็ฐ่ฑก
- G1ๅจๅๆถๅ
ๅญๅไผ้ฉฌไธๅๆถๅๅๅนถ็ฉบ้ฒๅ
ๅญ็ๅทฅไฝใ่CMS้ป่ฎคๆฏๅจSTW๏ผstop the world๏ผ็ๆถๅๅ
- G1ไผๅจYoung GCไธญไฝฟ็จใ่CMSๅช่ฝๅจOๅบไฝฟ็จ
่็ธ่พไบๅ
ถไป็ๅๅพๆถ้ๅจ่่จ๏ผG1ไธป่ฆๆๅฆไธๅไธช็น็น:
- **ๅนถ่กไธๅนถๅ**:่ฝๆดๅฅฝ็ๅฉ็จๅคCPU็ไผๅฟใ
- **ๅไปฃๆถ้**:่ฟไธชๅฐฑๅๅฎณไบ๏ผๅผบๅคงๅฐๆฒก้ๅ๏ผๅฏไปฅ็ฎก็ๆดไธชGCๅ ๏ผไธไธชไบบcarryๅ
จๅ
ๅญใ
- **็ฉบ้ดๆดๅ**:่ๅฎ่ฐ็ๅๅพๅๆถ็ฎๆณ๏ผๆดไฝ็ๆฏๅบไบๆ ่ฎฐ-ๆด็็ฎๆณๅฎ็ฐ็๏ผๅฑ้จ็ๅๅๆฏๅบไบๅคๅถ็ฎๆณๅฎ็ฐ็๏ผไฝๆ ่ฎบไฝฟ็จๅฎไปฌไธคไธชไธญ็ๅชไธช๏ผ้ฝๅ ไนไธไผไบง็็ฉบ้ดๅ
ๅญ็ข็ใ
- ๅฏ้ขๆต็ๅ้กฟ๏ผๆ็นๅAI๏ผไผๅปบ็ซๅฏ้ขๆต็ๅ้กฟๆถ้ดๆจกๅ๏ผๅฏไปฅๆ่ฎกๅ็้ฟๅ
ๅจๆดไธชJavaๅ ๅฎ็ฐๅ
จๅบๅ็ๅๅพๆถ้ใ
่G1ๆฏๅฎ็ฐๆต็จ็ธๅฏนๆฅ่ฏด่ฟๆฏๅพๅคๆ็๏ผๅจ่ฟ้ๆไปฌๅฐฑไธๅคๅ ๅ่ฟฐไบ๏ผๆณ่ฆไบ่งฃ็ๅๅญฆๅฏไปฅๅปๆ็ดข็ธๅ
ณ่ตๆใ
ๅCMS็ธๅ๏ผG1็ๅๅพๅๆถ่ฟ็จไนไธป่ฆๅไธบๅไธช้ถๆฎต:
1. ๅๅงๆ ่ฎฐ
2. ๅนถๅๆ ่ฎฐ
3. ๆ็ปๆ ่ฎฐ
4. ็ญ้ๅๆถ
ๆต็จๅพๅฆไธ:

## ๆป็ป:
ๆฌ็ฏๆ็ซ ๆไปฌ่พไธบๅ็ฅ็่ฏดไบ่ฏดjvmไธ็งๅๅพๆถ้ๅจ๏ผๅๆๆ้ฟ๏ผๆฒกๆ็ปๅฏน็ๅๆ๏ผๅชๆๅบๆฏ็้ๆฉใๅ้็ๅบๆฏ็จๅ้็ๅๅพๆถ้ๅจ๏ผๆไผไฝฟๆไปฌ็ๅบ็จๆง่ฝๅพๅฐๆนๅใ
ๆๆฏ้ฉๆฐ๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ๏ผๅผ๏ผ
ๆดๅคๆ็ซ ่ฏทๅๅปๆ็github๏ผๆฌข่ฟๅคงๅฎถstar๏ผ
<file_sep># Docker ไธ่ฆ็ด ๏ผ้ๅใๅฎนๅจๅไปๅบ
ไธไธ็ฏ็ฌ่ฎฐ [้ขๅๅๅญฆ่
็Dockerๅญฆไน ๆ็จ:ๅบ็ก็ฏ](https://juejin.im/post/5d96fd6fe51d45781d5e4bac) ๆไปฌไปไธไธชๆน้ขๅคง่ด็ไป็ปไบไธไธDocker
1. ไปไนๆฏDocker๏ผ
2. ไธบไปไนๆฏDocker๏ผ
3. Docker ๅ
ทไฝ่งฃๅณไบไปไนๆ ท็้ฎ้ข๏ผ
็ธไฟก็่ฟ่ฟ็ฏๆ็ซ ็ๅฐไผไผดๅทฒ็ปๅฏนDockerๆไบไธไธชๅๆญฅ็่ฎค่ฏ๏ผๅชๆๆไปฌๅ
ๅ่ฎค่ฏไบDocker็ๅฅๅฆไนๅค๏ผๅ้ขๆ่ฝๆดๅฅฝ็ไฝฟ็จๅฎ๏ผๆฅไธๆฅๅข๏ผๆไปฌๅฐ่ฏดไธไธDockerๆ้่ฆ็ไธไธชๅบๆฌๆฆๅฟต๏ผ**้ๅ๏ผๅฎนๅจๅไปๅบ**
## ้ๅ
ๅจไบ่งฃ้ๅ่ฟไธชๆฆๅฟตไนๅ๏ผๆไปฌ้่ฆๅ
ๅคง่ดไบ่งฃไธไธ่ๅๆไปถ็ณป็ป-UnionFS๏ผๅฎๆฏDocker้ๅ็ๅบ็ก๏ผ่ๅๆไปถ็ณป็ปๆฏไธ็งๅๅฑ๏ผ่ฝป้็บงๅนถไธ้ซๆง่ฝ็ๆไปถ็ณป็ป๏ผๅฎๆฏๆๅฏนๆไปถ็ณป็ป็ไฟฎๆนไฝไธบไธๆฌกๆไบคๆฅไธๅฑไธๅฑ็ๅ ๅ ๏ผๅๆถๅฏไปฅๅฐไธๅ็ฎๅฝๆ่ฝฝๅฐๅไธไธช่ๆๆไปถ็ณป็ปไธ๏ผ้ๅๅฏไปฅ้่ฟๅๅฑๆฅ่ฟ่ก้ๆ๏ผๆไปฌๅฏไปฅๅบไบไธไธชๅบ็ก็้ๅ๏ผ็ถๅๅถไฝๅบๅ็งๅๆ ทๆปก่ถณๆไปฌ้ๆฑ็ๅบ็จ้ๅใ
ๅๆถ๏ผๅฏนไบไธไธช็ฒพ็ฎ็OS๏ผrootfsๅฏไปฅๅพๅฐ๏ผๆๅธธ่ง็ๅฝไปคๅฐฑ่ก๏ผๅๆถ๏ผๅบๅฑๅๆฏ็ดๆฅไฝฟ็จ็ๆไฝ็ณป็ป็ๅ
ๆ ธ๏ผๆไปฅๅพๅพDockerไธญไธไธช้ๅ็ไฝ็งฏ็ธๅฏนๆฅ่ฏดๅฏไปฅๅพๅฐ๏ผๆฏๅฆไธไธชๅฎๆด็็centosๅฏ่ฝ่ฆๅ ไธชG๏ผไฝๆฏDockerไธญ็centosๅคงๆฆๅชๆ300M.
ๅฏนไบdocker้ๅ๏ผๅฎๆน็ๅฎไนๅฆไธ:
> An image is a read-only template with instructions for creating a Docker container. Often, an image is based on another image, with some additional customization. For example, you may build an image which is based on the ubuntu image, but installs the Apache web server and your application, as well as the configuration details needed to make your application run.โ
>
> ๆ ๅๆฏไธไธชๅช่ฏปๆจกๆฟ๏ผๅธฆๆๅๅปบDockerๅฎนๅจ็ๆไปคใ้ๅธธ๏ผไธไธชๆ ๅๆฏๅบไบๅฆไธไธชๆ ๅ็๏ผ่ฟ้่ฆ่ฟ่กไธไบ้ขๅค็ๅฎๅถใไพๅฆ๏ผๆจๅฏไปฅๆๅปบไธไธชๅบไบubuntuๆ ๅ็ๆ ๅ๏ผไฝๆฏๅฎ่ฃ
Apache webๆๅกๅจๅๆจ็ๅบ็จ็จๅบ๏ผไปฅๅไฝฟๆจ็ๅบ็จ็จๅบ่ฟ่กๆ้็้
็ฝฎ็ป่ใ
PS:ไธไธช้ๅๅฏไปฅๅๅปบๅคไธชๅฎนๅจใ
## ๅฎนๅจ๏ผ
ๅฎนๅจๆฏ็จ้ๅๅๅปบ็่ฟ่กๅฎไพใ
ๆฏไธชๅฎนๅจ้ฝๅฏไปฅ่ขซๅฏๅจ๏ผๅผๅง๏ผๅๆญข๏ผๅ ้ค๏ผๅๆถๅฎนๅจไน้ด็ธไบ้็ฆป๏ผไฟ่ฏๅบ็จ่ฟ่กๆ้ด็ๅฎๅ
จใ
ๆไปฌๅฏไปฅๆๅฎนๅจ็่งฃไธบไธไธช็ฒพ็ฎ็็linuxๆไฝ็ณป็ป๏ผๅ
ๆฌroot็จๆทๆ้๏ผ่ฟ็จ็ฉบ้ด๏ผ็จๆท็ฉบ้ดๅ็ฝ็ป็ฉบ้ด็ญ็ญ่ฟไบ๏ผ็ถๅๅ ไธๅๅฎไนไธ่ฟ่ก็ๅบ็จ็จๅบใ
ๆฏๅฆๆไปฌ็ฐๅจๅบไบmysql้ๅๅๅปบไบไธไธชๅฎนๅจ๏ผ้ฃไน๏ผ่ฟไธชๅฎนๅจๅ
ถๅฎๅนถไธๆฏๅชๆไธไธชmysql็จๅบ๏ผ่ๆฏmysqlๅๆ ทไนๆฏๅฎ่ฃ
่ฟ่กๅจๆไปฌๅฎนๅจๅ
็linux็ฏๅขไธญ็ใ
### ๅฎนๅจๅ้ๅ็ๅ
ณ็ณป:
ๅ่ฏด่ฟไธช้ฎ้ขไนๅ๏ผๆไปฌไธๅฆจๅ
ๆฅ็ไธไธไธ้ข่ฟๆฎตjavaไปฃ็ :
```java
Person p = new Person();
Person p1 = new Person();
Person p2 = new Person();
```
้ๅๅจ่ฟ้ๅฐฑๆฏๆไปฌ็Person๏ผๅฎนๅจๅฐฑๆฏไธไธชไธชPerson็ฑป็ๅฎไพใไธไธชPersonๅฏไปฅๅๅปบๅคไธชๅฎไพ๏ผไธไธช้ๅไนๅฏไปฅๅๅปบๅคไธชๅฎนๅจใ
## ไปๅบ:
ไปๅบ็ธๅฏนๆฅ่ฏดๅฐฑๆฏ่พๅฎนๆ็่งฃไบ๏ผไปๅบ๏ผRepository๏ผๆฏ้ไธญๅญๆพ้ๅๆไปถ็ๅบๆใ
ไปๅบๅไธบๅ
ฌๅผไปๅบๅ็งๆไปๅบ๏ผ็ฎๅ็่ฏ๏ผๅ
จไธ็ๆๅคง็ไปๅบๆฏDockerๅฎๆน็ [Docker Hub](https://hub.docker.com/)
็ฑไบไธไบไธๅฏๆๆ็ๅ ็ด ๏ผๅฏผ่ดๆไปฌๅฆๆไปDocker Hubไธไธ่ฝฝๅ
ฌๅผ็้ๅๆฏ้ๅธธ่็ผ็๏ผ่ฟ็นๅคงๅฎถๅฏไปฅๅ่ไฝ ็จ็พๅบฆ็ฝ็ๅฎๆนไธ่ฝฝๆถ็ๆ่งใๆไปฅ๏ผๅฝๅ
ๆไปฌไธ่ฌไฝฟ็จ้ฟ้ไบๆ่
็ฝๆไบ็้ๅไปๅบใ
้ๅ ๅฎนๅจ ไปๅบ ไปไปฌไธ่
ไน้ด็ๅ
ณ็ณปๅพๅฆไธ:

## ๆป็ป:
ไปๅคฉๅข๏ผๆไปฌ็ฎๅ็ๆ่ฟฐไบไธไธDockerไธ่ฆ็ด ๏ผ้ๅ๏ผๅฎนๅจๅไปๅบ๏ผๅจไนๅ็ๅญฆไน ไธญๆไปฌไผ็ปๅธธ็ๅฐ้ๅๅๅฎนๅจ่ฟไธคไธชๆฆๅฟต๏ผๅๆถไนไผ็ผๅๆไปฌ่ชๅทฑ็DockerFileๆๅปบๆไปฌ่ชๅฎไน็้ๅๆไปถใ
ๆๅ๏ผ็ธๅ
ณ็ฌ่ฎฐๅทฒ็ปๅๆญฅๅผๆบ่ณGithub:
ๆ้่ฆ็ๅๅญฆๅฏไปฅๅๅปไธ่ฝฝ๏ผ
<file_sep>## Springbootไน่ชๅฎไนๅ
จๅฑๅผๅธธๅค็
ๆฌๆ้ฆๅ่ณjavaๆๆฏๅๅฎข[**็ ไธ**]๏ผhttp://jdkcb.com/
## ๅ่จ๏ผ
ๅจๅฎ้
็ๅบ็จๅผๅไธญ๏ผๅพๅคๆถๅๅพๅพๅ ไธบไธไบไธๅฏๆง็ๅ ็ด ๅฏผ่ด็จๅบๅบ็ฐไธไบ้่ฏฏ๏ผ่ฟไธชๆถๅๅฐฑ่ฆๅๆถๆๅผๅธธไฟกๆฏๅ้ฆ็ปๅฎขๆท็ซฏ๏ผไพฟไบๅฎขๆท็ซฏ่ฝๅคๅๆถๅฐ่ฟ่กๅค็๏ผ่้ๅฏนไปฃ็ ๅฏผ่ด็ๅผๅธธ๏ผๆไปฌไธ่ฌๆไธค็งๅค็ๆนๅผ๏ผไธ็งๆฏthrows็ดๆฅๆๅบ๏ผไธ็งๆฏไฝฟ็จtry..catchๆ่ท๏ผไธ่ฌ็่ฏ๏ผๅฆๆ้ป่พ็ๅผๅธธ๏ผ้่ฆ็ฅ้ๅผๅธธไฟกๆฏ๏ผๆไปฌๅพๅพ้ๆฉๅฐๅผๅธธๆๅบ๏ผๅฆๆๅชๆฏ่ฆไฟ่ฏ็จๅบๅจๅบ้็ๆ
ๅตไธ ไพ็ถๅฏไปฅ็ปง็ปญ่ฟ่ก๏ผๅไฝฟ็จtry..catchๆฅๆ่ทใ
ไฝๆฏtry..catchไผๅฏผ่ดไปฃ็ ้็ๅขๅ ,่ฎฉๅๆๆไปฌ็ไปฃ็ ๅๅพ่่ฟไธ้พไปฅ็ปดๆคใๅฝ็ถ๏ผspringbootไฝไธบไธไธชๅฆๆญคไผ็ง็ๆกๆถ๏ผ่ฏๅฎไธไผๅ่งไธ็ฎก็๏ผ้่ฟspringboot่ชๅธฆ็ๆณจ่งฃ๏ผๆไปฌๅฏไปฅๆนไพฟ็่ชๅฎไนๆไปฌ็ๅ
จๅฑๅผๅธธๅค็ๅจ๏ผๅนถไธไปฅjsonๆ ผๅผ่ฟๅ็ปๆไปฌ็ๅฎขๆท็ซฏใ
## ไปฃ็ ๅฎๆ๏ผ
### ๆ่ทๅ
จๅฑๅผๅธธ๏ผ
้ฆๅ
ๅข๏ผๆไปฌๆฐๅปบๆไปฌ่ด่ดฃๅ
จๅฑๅผๅธธๆๆๅค็็็ฑป:MyControllerAdvice๏ผไปฃ็ ๅฆไธ:
```java
@ControllerAdvice
public class MyControllerAdvice {
@ResponseBody
@ExceptionHandler(value = Exception.class)
public Map<String,Object> exceptionHandler(Exception ex){
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",100);
map.put("msg",ex.getMessage());
//่ฟ้ๅฏไปฅๅ ไธๆไปฌๅ
ถไป็ๅผๅธธๅค็ไปฃ็ ๏ผๆฏๅฆๆฅๅฟ่ฎฐๅฝ๏ผ๏ผ๏ผ
return map;
}
}
```
### ๆณจ่งฃ่ฏดๆ๏ผ
@ControllerAdvice ้่ฟAOP็ๆนๅผ้
ๅ@ExceptionHandler()ๆณจ่งฃๆ่ทๅจControllerๅฑ้ขๅ็็ๅผๅธธใๅฆๆ้่ฆๆซๆ่ชๅฎ่ทฏๅพไธ็Controller๏ผๆทปๅ basePackagesๅฑๆง
```java
@ControllerAdvice(basePackages ="com.example.demo.controller")
```
@RestControllerAdvice : ๅ@ControllerAdviceไฝ็จ็ธๅ๏ผๅฏไปฅ็่งฃไธบ @ResponseBody+@ControllerAdvice ็็ปๅไฝฟ็จใ
@ExceptionHandler()๏ผ่ฏฅๆณจ่งฃไฝ็จไธป่ฆๅจไบๅฃฐๆไธไธชๆๅคไธช็ฑปๅ็ๅผๅธธ๏ผๅฝ็ฌฆๅๆกไปถ็Controllerๆๅบ่ฟไบๅผๅธธไนๅๅฐไผๅฏน่ฟไบๅผๅธธ่ฟ่กๆ่ท๏ผ็ถๅๆ็
งๅ
ถๆ ๆณจ็ๆนๆณ็้ป่พ่ฟ่กๅค็๏ผไป่ๆนๅ่ฟๅ็่งๅพไฟกๆฏใ
### ๆต่ฏ๏ผ
```java
@RestController
public class UserController {
@GetMapping("/test")
public String test(){
int num = 1/0;
return "Hello World";
}
}
```
### ็ปๆ๏ผ
```json
{"msg":"/ by zero","code":100}
```
## ๆ่ท่ชๅฎไนๅผๅธธ๏ผ
่ชๅฎไนๆไปฌ็ๅผๅธธไฟกๆฏ็ฑปMyException ๅนถ็ปงๆฟRuntimeException๏ผ
```java
public class MyException extends RuntimeException {
private String errorCode;
private String errorMsg;
public MyException(String errorCode, String errorMsg) {
this.errorCode = errorCode;
this.errorMsg = errorMsg;
}
public String getErrorCode() {
return errorCode;
}
public void setErrorCode(String errorCode) {
this.errorCode = errorCode;
}
public String getErrorMsg() {
return errorMsg;
}
public void setErrorMsg(String errorMsg) {
this.errorMsg = errorMsg;
}
}
```
ไฟฎๆนๆไปฌ็MyControllerAdvice๏ผๅฐMyExceptionๆทปๅ ่ฟๅป๏ผ
```java
@ResponseBody
@ExceptionHandler(value = MyException.class)
public Map<String,Object> myExceptionHandler(MyException mex){
Map<String,Object> map = new HashMap<String,Object>();
map.put("code",mex.getErrorCode());
map.put("msg",mex.getErrorMsg());
//ๅ
ถไปไธๅกไปฃ็ ...
return map;
}
```
### ๆต่ฏ๏ผ
```java
@GetMapping("/test1")
public String test1(){
String name = null;
if(name == null){
throw new MyException("101","็จๆทๅไธบ็ฉบ");
}
return "Hello World";
}
```
### ่พๅบ๏ผ
```json
{"msg":"็จๆทๅไธบ็ฉบ","code":"101"}
```
ๅฎๆ~๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ๏ผๅผใ
<file_sep># Springboot ไนmybatisๅคๆฐๆฎๆบ้
็ฝฎ
## ๅ่จ:
้็ๅบ็จ็จๆท้็ๅขๅ ๏ผ็ธๅบ็ๅนถๅ้ไนไผ่ท็ไธๆญๅขๅ ๏ผ้ๆธ็๏ผๅไธชๆฐๆฎๅบๅทฒ็ปๆฒกๆๅๆณๆปก่ถณๆไปฌ้ข็น็ๆฐๆฎๅบๆไฝ่ฏทๆฑไบ๏ผๆไบๅบๆฏไธ๏ผๆไปฌๅฏ่ฝไผ้่ฆ้
็ฝฎๅคไธชๆฐๆฎๆบ๏ผๅจๆๅๆขๆฐๆฎๆบๆฅ็ผ่งฃ็ณป็ป็ๅๅ็ญ๏ผๅๆ ท็๏ผSpringbootๅฎๆนๆไพไบ็ธๅบ็ๅฎ็ฐๆฅๅธฎๅฉๅผๅ่
ไปฌ้
็ฝฎๅคๆฐๆฎๆบ๏ผไธ่ฌๅไธบไธค็งๆนๅผ(ๆ็ฅ้็)๏ผๅๅ
ๅAOP๏ผๅ
ถไธญๅฉ็จAOPๅฎ็ฐๅจๆๅคๆฐๆฎๆบๅฐๆถๅไผๅฆๅผไธ็ฏๆ็ซ ๆฅๅใ่่ๅฐmybatisๆฏjavaๅผๅ่
ไปฌไฝฟ็จ่พไธบ้ข็น็ๆฐๆฎๅบๆกๆถ๏ผๆไปฅๆฌ็ฏๆ็ซ ไฝฟ็จSpringboot+Mybatisๆฅๅฎ็ฐๅคๆฐๆฎๆบ็้
็ฝฎใ
ๅบ่ฏไธๅค่ฏด๏ผ่ตฐ่ตทใ
## 1. ๆฐๆฎๅบๅๅค:
ๆข็ถๆฏ้
็ฝฎๅคๆฐๆฎๆบ๏ผ้ฃไนๆไปฌๅฐฑ่ฆๅ
ๆ็ธๅบ็ๆฐๆฎๆบ็ปๅๅคๅฅฝ๏ผ่ฟ้ๅข๏ผๆๆฌๅฐๆฐๅปบไบไธคไธชๆฐๆฎๅบ๏ผๅฆไธ่กจ๏ผ
| ๆฐๆฎๅบ | testdatasource1 | testdatasource2 |
| ------ | -------------------------- | --------------- |
| ๆฐๆฎ่กจ | sys_user | sys_user2 |
| ๅญๆฎต | user_id user_name user_age | ๅ |
ๅนถๅๅซๆๅ
ฅไธคๆก่ฎฐๅฝ๏ผไธบไบๆนไพฟๅฏนๆฏ๏ผๅ
ถไธญtestdatasource1ไธบๅผ ไธ๏ผ testdatasource2ไธบๆๅ
## 2.็ฏๅขๅๅค
้ฆๅ
ๆฐๅปบไธไธชSpringboot้กน็ฎ๏ผๆ่ฟ้็ๆฌๆฏ2.1.7.RELEASE๏ผๅนถๅผๅ
ฅ็ธๅ
ณไพ่ต๏ผๅ
ณ้ฎไพ่ตๅฆไธ:
```xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>1.3.2</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
```
ๅฐ่ฟ้ๆไปฌ็็ฏๅขๅทฒ็ปๅบๆฌ้
็ฝฎๅฎๆไบใ
## 3.ไปฃ็ ้จๅ
### 1. ๅคๆฐๆฎๆบ้
็ฝฎ
้ฆๅ
ๅข๏ผๅจๆไปฌSpringboot็้
็ฝฎๆไปถไธญ้
็ฝฎๆไปฌ็datasourse๏ผๅไปฅๅพไธไธๆ ท็ๆฏ๏ผ่ฟๆฌกๆไปฌ่ฆ้
็ฝฎไธคไธช๏ผๆไปฅ่ฆๆๅฎๅ็งฐ๏ผๅฆไธ:
```java
#้
็ฝฎไธปๆฐๆฎๅบ
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/testdatasource1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.primary.username=root
spring.datasource.primary.password=<PASSWORD>
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
##้
็ฝฎๆฌกๆฐๆฎๅบ
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/testdatasource2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.secondary.username=root
spring.datasource.secondary.password=<PASSWORD>
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
```
> ้่ฆๆไปฌๆณจๆ็ๆฏ๏ผSpringboot2.0 ๅจ้
็ฝฎๆฐๆฎๅบ่ฟๆฅ็ๆถๅ้่ฆไฝฟ็จjdbc-url๏ผๅฆๆๅชไฝฟ็จurl็่ฏไผๆฅ
>
> jdbcUrl is required with driverClassName.้่ฏฏใ
ๆฐๅปบไธไธช้
็ฝฎ็ฑปPrimaryDataSourceConfig๏ผ็จไบ้
็ฝฎๆไปฌ็ไธปๆฐๆฎๅบ็ธๅ
ณ็bean๏ผไปฃ็ ๅฆไธ:
```java
@Configuration
@MapperScan(basePackages = "com.jdkcb.mybatisstuday.mapper.one", sqlSessionFactoryRef = "PrimarySqlSessionFactory")
public class PrimaryDataSourceConfig {
@Bean(name = "PrimaryDataSource")
// ่กจ็คบ่ฟไธชๆฐๆฎๆบๆฏ้ป่ฎคๆฐๆฎๆบ
@Primary
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource getPrimaryDateSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "PrimarySqlSessionFactory")
@Primary
public SqlSessionFactory primarySqlSessionFactory(@Qualifier("PrimaryDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/one/*.xml"));
return bean.getObject();// ่ฎพ็ฝฎmybatis็xmlๆๅจไฝ็ฝฎ
}
@Bean("PrimarySqlSessionTemplate")
// ่กจ็คบ่ฟไธชๆฐๆฎๆบๆฏ้ป่ฎคๆฐๆฎๆบ
@Primary
public SqlSessionTemplate primarySqlSessionTemplate(
@Qualifier("PrimarySqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
}
```
ๆณจ่งฃ่ฏดๆ:
**@MapperScan** ๏ผ้
็ฝฎmybatis็ๆฅๅฃ็ฑปๆพ็ๅฐๆน
**@Primary** :่กจ็คบไฝฟ็จ็ๆฏ้ป่ฎคๆฐๆฎๅบ๏ผ่ฟไธชไธไธช่ฆๅ ๏ผๅฆๅไผๅ ไธบไธ็ฅ้ๅชไธชๆฐๆฎๅบๆฏ้ป่ฎคๆฐๆฎๅบ่ๆฅ้
**@ConfigurationProperties**๏ผ่ฏปๅapplication.propertiesไธญ็้
็ฝฎๅๆฐๆ ๅฐๆไธบไธไธชๅฏน่ฑก๏ผๅ
ถไธญprefix่กจ็คบๅๆฐ็ๅ็ผ
ๅคงๅๅๆ~ ~ ไบๅ๏ผๅนถๆฒกๆ๏ผ็ถๅ้
็ฝฎๆไปฌ็็ฌฌไบไธชๆฐๆฎๆบ็้
็ฝฎ็ฑป,ไปฃ็ ๅฆไธ๏ผ
```java
@Configuration
@MapperScan(basePackages = "com.jdkcb.mybatisstuday.mapper.two", sqlSessionFactoryRef = "SecondarySqlSessionFactory")
public class SecondaryDataSourceConfig {
@Bean(name = "SecondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource getSecondaryDataSource() {
return DataSourceBuilder.create().build();
}
@Bean(name = "SecondarySqlSessionFactory")
public SqlSessionFactory secondarySqlSessionFactory(@Qualifier("SecondaryDataSource") DataSource datasource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(datasource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/two/*.xml"));
return bean.getObject();
}
@Bean("SecondarySqlSessionTemplate")
public SqlSessionTemplate secondarySqlSessionTemplate(
@Qualifier("SecondarySqlSessionFactory") SqlSessionFactory sessionfactory) {
return new SqlSessionTemplate(sessionfactory);
}
```
ๅฉไธ็ๅฐฑๆฏ็ผๅๆไปฌ็ธๅบ็xmlๆไปถๅๆฅๅฃ็ฑปไบ๏ผไปฃ็ ๅฆไธ:
```java
@Component
@Mapper
public interface PrimaryUserMapper {
List<User> findAll();
}
@Component
@Mapper
public interface SecondaryUserMapper {
List<User> findAll();
}
```
xmlๆไปถๅฆไธ:
```java
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jdkcb.mybatisstuday.mapper.one.PrimaryUserMapper">
<select id="findAll" resultType="com.jdkcb.mybatisstuday.pojo.User">
select * from sys_user;
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jdkcb.mybatisstuday.mapper.two.SecondaryUserMapper">
<select id="findAll" resultType="com.jdkcb.mybatisstuday.pojo.User">
select * from sys_user2;
</select>
</mapper>
```
> ๆณจ:ๅ
ถไธญxmlๆไปถๅจๆฌๅฎไพไธญ็ฎๅฝไธบ๏ผresources/mapping
### 2.ๆต่ฏ
็ผๅไธไธชController็จไบๆต่ฏ๏ผๅ ไธบๆฏๆต่ฏๅฎไพไธไปฃ็ ็ธๅฏนๆฅ่ฏด่พไธบ็ฎๅ๏ผๆไปฅ่ฟ้ๅฐฑไธๅServiceๅฑไบใ
ไปฃ็ ๅฆไธ:
```java
@RestController
public class UserController {
@Autowired
private PrimaryUserMapper primaryUserMapper;
@Autowired
private SecondaryUserMapper secondaryUserMapper;
@RequestMapping("primary")
public Object primary(){
List<User> list = primaryUserMapper.findAll();
return list;
}
@RequestMapping("secondary")
public Object secondary (){
List<User> list = secondaryUserMapper.findAll();
return list;
}
}
```
ๅจๆต่งๅจๅๅซ่พๅ
ฅ:http://127.0.0.1:8080/primary ๅ http://127.0.0.1:8080/secondary
็ปๆๅฆไธ:
```json
[{"user_id":1,"user_name":"ๅผ ไธ","user_age":25}] //primary
[{"user_id":1,"user_name":"ๆๅ","user_age":30}] //secondary
```
ๅฐๆญค๏ผSpringboot็ปๅmybatis้
็ฝฎๅคๆฐๆฎๆบๅฐฑๅคงๅๅๆๅฆใ
ๆๅ็ๆๅ๏ผๅคงๅฎถๅฅฝ๏ผๆๆฏ้ฉๆฐ๏ผๅผ๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ(ๅ่
ฐ)ใ
่ฎฐๅพ็นไธช่ตๅ่ตฐๅฆ~
็ญไธไธ๏ผ
> ็ธๅ
ณๆบ็ ๆฌข่ฟๅปๆ็githubไธ่ฝฝ(ๆฌข่ฟstar)๏ผ
>
>
<file_sep># HanShu-Note
ๅฎๅฎๅฎ้๏ผ้ฉๆฐ็ๅญฆไน ็ฌ่ฎฐ(ๅๅฆAๆขฆ้
้ณ)
ๅคงๅฎถๅฅฝ๏ผๆๆฏ้ฉๆฐ๏ผ่ฟ้ๆถๅฝไบๆ็ๅคงๅคๆฐๅญฆไน ็ฌ่ฎฐ๏ผๅ
ๆฌNginx๏ผJAVA,Springboot๏ผSpringCloud๏ผDocker็ญๅ็ซฏๅธธ็จ็ๆๆฏ๏ผๅคงๅคๆฐๆ็ซ ้ฝ็ป่ฟmarkdown็ฒพๅฟๆ็๏ผๆปไนๅ
ซไธชๅญ๏ผ
**ๆ่ทฏๆธ
ๅฅ๏ผๅๆณ้ฃ้ช**
ๅ็ปญ้ขๅ:
Spark ๅคงๆฐๆฎๅ็บงๆ็จ
้ขๅๅ็ซฏ็Dockerๆๅๆ็จ:้ซ็บง็ฏ
้ขๅๅ็ซฏ็Mysqlๅ็บงๅ
ฅ้จๆ็จ็ญ
**ๅ็ปๅ็ซฏ็Nginxๅ็บงๅ
ฅ้จๆ็จ**:
[ๅ็ปๅ็ซฏ็Nginxๅ็บงๅ
ฅ้จๆ็จ:ๅบ็ก็ฏ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Nginx%E5%88%9D%E7%BA%A7%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B/%E5%86%99%E7%BB%99%E5%90%8E%E7%AB%AF%E7%9A%84Nginx%E5%88%9D%E7%BA%A7%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%E5%9F%BA%E7%A1%80%E7%AF%87.md)
[ๅ็ปๅ็ซฏ็Nginxๅ็บงๅ
ฅ้จๆ็จ:ๅฎๆ็ฏ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Nginx%E5%88%9D%E7%BA%A7%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B/%E5%86%99%E7%BB%99%E5%90%8E%E7%AB%AF%E7%9A%84Nginx%E5%88%9D%E7%BA%A7%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%E5%AE%9E%E6%88%98%E7%AF%87.md)
**้ขๅๅ็ซฏ็Dockerๅ็บงๅ
ฅ้จๆ็จ:**
[้ขๅๅ็ซฏ็Dockerๅ็บงๅ
ฅ้จๆ็จ:ๅบ็ก็ฏ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Docker%E5%88%9D%E7%BA%A7%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B/%E9%9D%A2%E5%90%91%E5%88%9D%E5%AD%A6%E8%80%85%E7%9A%84docker%E5%AD%A6%E4%B9%A0%E6%95%99%E7%A8%8B%EF%BC%9A%E5%9F%BA%E7%A1%80%E7%AF%87.md)
[Docker ไธ่ฆ็ด ๏ผ้ๅใๅฎนๅจๅไปๅบ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Docker%E5%88%9D%E7%BA%A7%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B/Docker%20%E4%B8%89%E8%A6%81%E7%B4%A0%20%EF%BC%9A%E9%95%9C%E5%83%8F%E3%80%81%E5%AE%B9%E5%99%A8%E5%92%8C%E4%BB%93%E5%BA%93.md)
[้ขๅๅ็ซฏ็Dockerๅ็บงๅ
ฅ้จๆ็จ๏ผๅฎๆ็ฏ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Dockerๅ็บงๅ
ฅ้จๆ็จ/้ขๅๅ็ซฏ็Dockerๅ็บงๅ
ฅ้จๆ็จ๏ผๅฎๆ็ฏ(ไธ).md)
[้ขๅๅ็ซฏ็Dockerๅ็บงๅ
ฅ้จๆ็จ๏ผDockerFile ๅฝไปค่ฏฆ่งฃ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Docker%E5%88%9D%E7%BA%A7%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B/%E5%86%99%E7%BB%99%E5%90%8E%E7%AB%AF%E7%9A%84Docker%E5%88%9D%E7%BA%A7%E5%85%A5%E9%97%A8%E6%95%99%E7%A8%8B%EF%BC%9ADockerFile%20%E5%91%BD%E4%BB%A4%E8%AF%A6%E8%A7%A3.md)
**Spring Boot็ณปๅ็ฌ่ฎฐ๏ผ**
[SpringBoot +Mybatis ๅฎ็ฐๅคๆฐๆฎๆบ้
็ฝฎ๏ผไธค็ฏ๏ผ](https://github.com/hanshuaikang/HanShu-Note/tree/master/SpringBoot/mybatis%E5%A4%9A%E6%95%B0%E6%8D%AE%E6%BA%90%E9%85%8D%E7%BD%AE)
[Springboot ไนๅฎไนๅ
จๅฑๅผๅธธๅค็](https://github.com/hanshuaikang/HanShu-Note/tree/master/SpringBoot/%E5%85%A8%E5%B1%80%E5%BC%82%E5%B8%B8%E5%A4%84%E7%90%86)
[SpringBoot ๅตๅ
ฅๅผWeb ๅฎนๅจ](https://github.com/hanshuaikang/HanShu-Note/tree/master/SpringBoot/%E5%B5%8C%E5%85%A5%E5%BC%8Fweb%E5%AE%B9%E5%99%A8)
[Springboot ไน่ชๅฎไนstarter](https://github.com/hanshuaikang/HanShu-Note/tree/master/SpringBoot/%E8%87%AA%E5%AE%9A%E4%B9%89starter)
[Springboot ไน่ชๅฎไนๆณจ่งฃๆซๆๅจ](https://github.com/hanshuaikang/HanShu-Note/blob/master/SpringBoot/%E8%87%AA%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3%E6%89%AB%E6%8F%8F%E5%99%A8/Spring%20Boot%E4%B9%8B%E5%AE%9A%E4%B9%89%E6%B3%A8%E8%A7%A3%E6%89%AB%E6%8F%8F%E5%99%A8.md)
**SpringCloud็ณปๅ็ฌ่ฎฐ:**
[Hystrix ๅฟซ้ๅ
ฅ้จ](https://github.com/hanshuaikang/HanShu-Note/tree/master/SpringCloud/Hystrix)
[ไธๅญ้ฟๆๆต
ๆๅพฎๆๅกRibbon่ด่ฝฝๅ่กกๆบ็ ](https://github.com/hanshuaikang/HanShu-Note/tree/master/SpringCloud/Ribbon)
**JVM็ณปๅ็ฌ่ฎฐ**:
[ไธไธชๅฏน่ฑก็ๆญปไบก่ฏๆ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Jvm/%E4%B8%80%E4%B8%AAJava%E5%AF%B9%E8%B1%A1%E7%9A%84%E6%AD%BB%E4%BA%A1%E8%AF%81%E6%98%8E.md)
[jvmๅ
ๅญๅๆถ็ปๆๅฅฅไน๏ผๅๅพๆถ้็ฎๆณ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Jvm/jvm%E5%86%85%E5%AD%98%E5%9B%9E%E6%94%B6%E7%BB%88%E6%9E%81%E5%A5%A5%E4%B9%89%EF%BC%9A%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E7%AE%97%E6%B3%95.md)
[Jvmๅ
ๅญๅๆถ็ปๆๅฅฅไน:ๅๅพๅๆถๅจ](https://github.com/hanshuaikang/HanShu-Note/blob/master/Jvm/Jvm%E5%86%85%E5%AD%98%E5%9B%9E%E6%94%B6%E7%BB%88%E6%9E%81%E5%A5%A5%E4%B9%89%E5%9E%83%E5%9C%BE%E6%94%B6%E9%9B%86%E5%99%A8.md)
**JAVA็ณปๅ็ฌ่ฎฐ๏ผ**
[ๅฐๅบไปไนๆฏๅบ็จไธไธๆ๏ผ](https://github.com/hanshuaikang/HanShu-Note/blob/master/java/%E5%88%B0%E5%BA%95%E4%BB%80%E4%B9%88%E6%98%AF%E5%BA%94%E7%94%A8%E4%B8%8A%E4%B8%8B%E6%96%87%EF%BC%9F.md)
<file_sep>## Spring Bootไนๅฎไนๆณจ่งฃๆซๆๅจ@XXXScan
## ๅ่จ:
ๆ่ฟๅจๅญฆไน Netty็่ฟ็จไธญ๏ผ่ท็ๅ่พไปฌ็ๆ่ทฏ็จNettyไฝไธบๅบๅฑ้ไฟกๅผๅไบไธไธช้ๅธธ็้ผ๏ผๅฎๅฎ็ฌฌไธ(ๅฎ้
่ถ
็บงๅๅพ)็Netty Rpc DemoใไธบๅฅไธๅซๆกๆถๅซDemoๅข๏ผไธไธชๅฅฝ็ๆกๆถๆฏ้่ฆ้ๅธธ้ฟๆถ้ด็ๅผๅๅไผๅ็๏ผ็ฆปไธๅผๅคงไฝฌไปฌ็ๅ
จๆ
ๆๅ
ฅ๏ผๆ่ฟ็ง็บงๅซ็่้ธ๏ผๅ
ๅ
ถ้ๅซdemoใๅฅฝ๏ผๅบ่ฏไธๅค่ฏด๏ผๅๆฌ็ๆ่ทฏๅข๏ผๆฏ้่ฆๆๅจ้
็ฝฎไธไธชๆฅๅฃไธๅฎ็ฐ็ฑป็ๆ ๅฐmap,็ฑปไผผไบไธ้ข่ฟๆ ท:
```java
@Bean("handlerMap")
public Map<String, Object> handlerMap(){
Map<String, Object> handlerMap = new ConcurrentHashMap<String, Object>();
handlerMap.put("com.jdkcb.mystarter.service.PersonService",new PersonServiceImpl());
return handlerMap;
}
```
ๅคงไฝฌไปฌๅฟๅท๏ผๅฝๆ่ชไฟกๆปกๆปก็ๆไปฃ็ ไบค็ปๅ่พไปฌ็็ๆถๅ๏ผๅ่พ้ๅธธ่ๅฟ(ไธ็ๆ
้ข)ๅฐๆๅบไบๆ่ฟๆ ทๅ็้ฎ้ขใ็็กฎ๏ผๅจๆฅๅฃ็ฑปๆฐ้้ๅธธๅค็ๆถๅ๏ผๅ
้
็ฝฎMapๅฐฑๆฏไธไปถ้ๅธธ้บป็ฆ็ไบๆ
ไบ๏ผไบๆฏๆๅๅปๅฅๆ่ฆๆณ,็ก็็น้ฆ๏ผไธไธๅๅไนๅ้ไนๅ๏ผ่่ข้็ตๅ
ไน็ฐ๏ผๆณๅฐไบๅๅคฉๅMybatis้
็ฝฎๅคๆฐๆฎๆบๆถๅ่งๅฐ็ไธไธชๆณจ่งฃ๏ผ@MapperScan
ohohohohohohoh,่ฟๅฐฑๆฏๆ็ฌไบซ็moment๏ผๅฐฑๅณๅฎๆฏไฝ ๅฆใ
ๆฅไธๆฅ๏ผๆไปฌๅฐๆจกไปฟMybatis็ๅฎ็ฐ๏ผๆฅๅไธไธชๆณจ่งฃๆซๆๅจ๏ผๅฐๆไปฌ่ชๅฎไน็ๆณจ่งฃๆซๆๅนถๆณจๅๆไธบSpring็ฎก็็Beanใ
ๆๅฃซไธๆๅบ๏ผ็ดๆฅๅผๅงๅนฒใ(ๅฅฝๅง๏ผ่ฟๅ
ถๅฎๆฏไธไธชๆข๏ผๆ็ๅพๅคไบบ้ฝgetไธๅฐ)
## ไปฃ็ ๅฎๆ๏ผ
ๆข็ถๆฏ่ฆๆซๆๆไปฌ่ชๅฎไน็ๆณจ่งฃ๏ผ้ฃ้ฆๅ
ๆไปฌๅพๆไธช่ชๅฎไน็ๆณจ่งฃๆ่กใๆฅ๏ผๅฐไบ๏ผไธ่ชๅฎไน็ๆณจ่งฃ๏ผ็ปๅๆไธชไบบ็้ๆฑ๏ผๆๅฐๅฎ่ชๅฎไนไธบNRpcServer ,ไปฃ็ ๅฆไธ:
```java
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface NRpcServer {
//ๆๅก็ๅ็งฐ,็จๆฅRPC็ๆถๅ่ฐ็จๆๅฎๅ็งฐ็ ๆๅก
String name() default "";
String value() default "";
}
```
ๅฏๆฏ๏ผๆๆไธช้ฎ้ข๏ผไฝ ๆฏๆไน็ฅ้ๅ @Target({ElementType.TYPE, ElementType.METHOD})่ฟๅ ไธชๆณจ่งฃ็ๅข?
hhh๏ผ็ๆฅ่ฟๆฏ่ขซไฝ ๅ็ฐไบ๏ผไธไผๅ๏ผๆ่ฟไธไผๆๅ๏ผๆข็ถๆฏๆจกไปฟ@MapperScan()่ฟไธชๆณจ่งฃ๏ผ้ฃ็ดๆฅ็นๅผ@Mapperๆณจ่งฃ,็็ๅฎๅ ไบไปไนๆณจ่งฃไธๅฐฑ่กไบๅ๏ผๅฟๅฟ
```java
@Documented
@Inherited
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
public @interface Mapper {
}
```
Nice,ๅปๆๆไปฌไธ้่ฆ็ๆณจ่งฃ๏ผ็จไธๅฐ็ๅฑๆง๏ผๆนไธชๅๅญๅฐฑๆฏๆไปฌ่ชๅทฑ็ๆณจ่งฃไบใ(ๆป็จฝ)
้ฃ@Mapperๆฏๆไนๆ ท่ขซๆซๆๅฐ็ๅข๏ผ้่ฟ@MapperScan่ฟไธชๆณจ่งฃ๏ผๆๆณ๏ผๅจ่ฟ้ๆไปฌไผฐ่ฎกๅฏไปฅ่พพๆไธ่ดไบ๏ผ**ๆไธไธช**,็ฏๅน
ๆ้๏ผๅ้ขๆๅฐฑไธ่ดดMybatis็ไปฃ็ ไบ๏ผ้่ฆไบ่งฃ็ๆๅๅฏไปฅๆๅผmybatis็ๆบ็ ๆฅ็ใ
```java
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
//springไธญ็ๆณจ่งฃ,ๅ ่ฝฝๅฏนๅบ็็ฑป
@Import(NRpcScannerRegistrar.class)//่ฟไธชๆฏๆไปฌ็ๅ
ณ้ฎ๏ผๅฎ้
ไธไนๆฏ็ฑ่ฟไธช็ฑปๆฅๆซๆ็
@Documented
public @interface NRpcScan {
String[] basePackage() default {};
}
```
ๅฝ็ถ๏ผ่ฟไธชๆณจ่งฃๆฌ่บซๆฏๆฒกไปไนไธ่ฅฟ็๏ผๆๆ ธๅฟ็ๅฐๆนๅจๅชๅข๏ผ็ญๆกๆฏNRpcScannerRegistrar่ฟไธช็ฑปไธ๏ผๅฎ้
ไธๆไปฌๆณจ่งฃ็ๆซๆ่ฟๆปคไธป่ฆๆฏไบค็ป่ฟไธช็ฑปๆฅๅฎ็ฐ็ใ
ๆฐๅปบไธไธชไปฃ็ NRpcScannerRegistrar ็ฑปๅนถ็ปงๆฟImportBeanDefinitionRegistrar, ResourceLoaderAware ่ฟไธคไธชๆฅๅฃใ
ๅ
ถไธญ๏ผ ResourceLoaderAwareๆฏไธไธชๆ ่ฎฐๆฅๅฃ๏ผ็จไบ้่ฟApplicationContextไธไธๆๆณจๅ
ฅResourceLoader
**ไปฃ็ ๅฆไธ:**
```java
public class NRpcScannerRegistrar implements ImportBeanDefinitionRegistrar, ResourceLoaderAware{
ResourceLoader resourceLoader;
@Override
public void setResourceLoader(ResourceLoader resourceLoader) {
this.resourceLoader = resourceLoader;
}
@Override
public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
//่ทๅๆๆๆณจ่งฃ็ๅฑๆงๅๅผ
AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(NRpcScan.class.getName()));
//่ทๅๅฐbasePackage็ๅผ
String[] basePackages = annoAttrs.getStringArray("basePackage");
//ๅฆๆๆฒกๆ่ฎพ็ฝฎbasePackage ๆซๆ่ทฏๅพ,ๅฐฑๆซๆๅฏนๅบๅ
ไธ้ข็ๅผ
if(basePackages.length == 0){
basePackages = new String[]{((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass().getPackage().getName()};
}
//่ชๅฎไน็ๅ
ๆซๆๅจ
FindNRpcServiceClassPathScanHandle scanHandle = new FindNRpcServiceClassPathScanHandle(beanDefinitionRegistry,false);
if(resourceLoader != null){
scanHandle.setResourceLoader(resourceLoader);
}
//่ฟ้ๅฎ็ฐ็ๆฏๆ นๆฎๅ็งฐๆฅๆณจๅ
ฅ
scanHandle.setBeanNameGenerator(new RpcBeanNameGenerator());
//ๆซๆๆๅฎ่ทฏๅพไธ็ๆฅๅฃ
Set<BeanDefinitionHolder> beanDefinitionHolders = scanHandle.doScan(basePackages);
}
}
```
่ฟ้ๆถๅๅฐไธไธช FindNRpcServiceClassPathScanHandle็ฑป๏ผๆฏๆไปฌ่ชๅฎไน็ๅ
ๆซๆๅจ๏ผๆไปฌๅฏไปฅๅจ่ฟไธชๆซๆๅจไธญๆทปๅ ๆไปฌ็่ฟๆปคๆกไปถใ
```java
public class FindNRpcServiceClassPathScanHandle extends ClassPathBeanDefinitionScanner {
public FindNRpcServiceClassPathScanHandle(BeanDefinitionRegistry registry, boolean useDefaultFilters) {
super(registry, useDefaultFilters);
}
@Override
protected Set<BeanDefinitionHolder> doScan(String... basePackages) {
//ๆทปๅ ่ฟๆปคๆกไปถ๏ผ่ฟ้ๆฏๅชๆทปๅ ไบ@NRpcServer็ๆณจ่งฃๆไผ่ขซๆซๆๅฐ
addIncludeFilter(new AnnotationTypeFilter(NRpcServer.class));
//่ฐ็จspring็ๆซๆ
Set<BeanDefinitionHolder> beanDefinitionHolders = super.doScan(basePackages);
return beanDefinitionHolders;
}
}
```
็ๅฐ่ฟ้ๅพๅค่ฏป่
ๅ ไน้ฝไผๅ็ฐ๏ผๆๅ
ถๅฎๅนถๆฒกๆๅไปไนไธ่ฅฟ๏ผๆๆๆ ธๅฟ็้ชๆไฝ้ฝๆฏ็ฑspringๆไพ็ๅฎ็ฐๆฅๅฎๆ็๏ผๅ
ถๅฎๆฏ็๏ผๆๆ ธๅฟ็ไปฃ็ ๅ
ถๅฎๅฐฑๅจ
super.doScan(basePackages);
่ฟไธๅฅ๏ผๆไปฌๆๅ็๏ผๅ
ถๅฎๅฐฑๆฏๆ นๆฎSpring็ๆซๆ็ปๆๅไธไธไบๆฌก็ๅค็๏ผๅจๆ็demoไธญ๏ผไนๅๆๅฐ็mapๅ
ถๅฎๅฐฑๆฏๅจ่ฟไธๆญฅ่ชๅจ็ๆ็๏ผ็ฑไบ่ฟๆฌกไธป่ฆ่ฎฒๅ
ๆซๆๅจ็ๅฎ็ฐ๏ผๆไปฅๅฐฑๆ้ฃ้จๅ้ป่พ็ปๅปๆไบใ
ๅๆถๅข๏ผไธ้ขไปฃ็ ไธญ็RpcBeanNameGenerator่ฟไธช็ฑปๅๆฏๅฎ็ฐไบๆ นๆฎๆไปฌ็ๅ็งฐๆฅๆณจๅ
ฅๆๅฎbean๏ผ่ฟ้ๅ
ถๅฎๅ็ๅฐฑๆฏ่ทๅๅฐๆณจ่งฃ้้ขๅฑๆงๆ่ฎพ็ฝฎ็ๅผใไปฃ็ ๅฆไธ:
```java
public class RpcBeanNameGenerator extends AnnotationBeanNameGenerator {
@Override
public String generateBeanName(BeanDefinition definition, BeanDefinitionRegistry registry) {
//ไป่ชๅฎไนๆณจ่งฃไธญๆฟname
String name = getNameByServiceFindAnntation(definition,registry);
if(name != null && !"".equals(name)){
return name;
}
//่ตฐ็ถ็ฑป็ๆนๆณ
return super.generateBeanName(definition, registry);
}
private String getNameByServiceFindAnntation(BeanDefinition definition, BeanDefinitionRegistry registry) {
String beanClassName = definition.getBeanClassName();
try {
Class<?> aClass = Class.forName(beanClassName);
NRpcServer annotation = aClass.getAnnotation(NRpcServer.class);
if(annotation == null){
return null;
}
//่ทๅๅฐๆณจ่งฃname็ๅผๅนถ่ฟๅ
return annotation.name();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
return null;
}
}
```
ๅฐ่ฟ้๏ผๅ ไนๅฐฑๅทฒ็ปๅคงๅๅๆไบใ
## ๆต่ฏ๏ผ
้ฆๅ
ๆไปฌๅๅคไธไธชPersonService็ฑป๏ผๅนถๆไธๆไปฌ็@NRpcServerๆณจ่งฃ๏ผไปฃ็ ๅฆไธ:
```java
@NRpcServer(name="PersonService")
public class PersonService {
public String getName(){
return "helloword";
}
}
```
็ถๅๅจSpringbootๅฏๅจ็ฑปไธๆทปๅ @NRpcScanๆณจ่งฃ๏ผๅนถๆๅฎๆไปฌ้่ฆๆซๆ็ๅ
```java
@NRpcScan(basePackage = {"com.jdkcb.mybatisstuday.service"})
```
ๆฐๅปบไธไธชController๏ผ็จไบๆต่ฏ๏ผไปฃ็ ๅฆไธ:
```java
@RestController
public class TestController {
@Autowired
@Qualifier("PersonService")
private PersonService personService;
@RequestMapping("test")
public String getName(){
return personService.getName();
}
}
```
ๅจๆต่งๅจไธญ่พๅ
ฅhttp://127.0.0.1:8080/test
่พๅบ็ปๆ:
```java
helloword
```
ๅฐๆญค๏ผๅฐฑ็ฎ็ๆญฃ็ๅคงๅๅๆๅฆใ
ๆๅ็ๆๅ๏ผๅคงๅฎถๅฅฝ๏ผๆๆฏ้ฉๆฐ๏ผๅผ๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ(ๅ่
ฐ)ใ
่ฎฐๅพ็นไธช่ตๅ่ตฐๅฆ~
็ญไธไธ๏ผ
> ็ธๅ
ณๆบ็ ๆฌข่ฟๅปๆ็githubไธ่ฝฝ(ๆฌข่ฟstar)๏ผ
>
> <https://github.com/hanshuaikang/Spring-Note>
<file_sep># ๅ็ปๅ็ซฏ็Nginxๅ็บงๅ
ฅ้จๆ็จ:ๅบ็ก็ฏ
## Nginxๆฏไปไน๏ผ
Nginx ("engine x") ๆฏไธไธช้ซๆง่ฝ็ HTTP ๅๅๅไปฃ็ๆๅกๅจ,็น็นๆฏๅ ๆๅ
ๅญๅฐ๏ผๅนถๅ่ฝๅๅผบ๏ผไบๅฎไธ nginx ็ๅนถๅ่ฝๅ็กฎๅฎๅจๅ็ฑปๅ็็ฝ้กตๆๅกๅจไธญ่กจ็ฐ่พๅฅฝ๏ผๆๆฅๅ่กจๆ่ฝๆฏๆ้ซ ่พพ 50,000 ไธชๅนถๅ่ฟๆฅๆฐใๅฝๅ
ไบฌไธ๏ผๆทๅฎ๏ผ้ฟ้๏ผๆฐๆตช็ๆไฝฟ็จNginxใ
Nginx้ๅธธ่ขซ็จๆฅๅฎ็ฐ**ๆญฃๅไปฃ็**,**ๅๅไปฃ็๏ผ่ด่ฝฝๅ่กก๏ผไปฅๅๅจ้ๅ็ฆป**่ฟๅไธชๅ่ฝใ
ๆฌ็ฏๆ็ซ ไฝไธบๅบ็ก็ฏ๏ผๅฐไธป่ฆ่ฎฒ่งฃ่ฟๅไธชNginxๅบ็จไธญๆๅบ็ก็ๆฆๅฟต๏ผๅธฎๅฉๅคงๅฎถๆดๅฅฝ็็่งฃ๏ผไป่ไธบไธไธ็ซ ็ไปฃ็ ้
็ฝฎๅๅๅค๏ผ
ไธๅบ่ฏ๏ผ็ดๆฅไธๅนฒ่ดงใ
## ๆญฃๅไปฃ็:
ๅจ่ฏดไปไนๆฏๅๅไปฃ็ไนๅ๏ผๆไปฌ้่ฆๅ
ไบ่งฃไธไธไปไนๆฏๆญฃๅไปฃ็๏ผๆญฃๅฆๅคงๅฎถๆ็ฅ๏ผ็ฑไบๆไบไธๅฏๆๆ็ๅ ็ด ๏ผๆไปฌๆฒกๆๅๆณๅจไธญๅฝๅคง้็ดๆฅ่ฎฟ้ฎGoogle็ญ็ฝ็ซ๏ผๆ่
่ฏด่ฎฟ้ฎGitHub่ฟไบๅฝๅค็ฝ็ซ็ฝ้ๆฏ่พๆ
ข๏ผไธ่ฎบๆฏๆญฃๅไปฃ็่ฟๆฏๅๅไปฃ็๏ผ้ฝๅ
ถๅฎๅฏไปฅ็ไฝๆฏไปฃ็ๆจกๅผ็่ก็็ๆฌใไธ้ขๆไปฌ้่ฟไธไธชๅฐๆ ๅญๆฅ็่งฃๆญฃๅไปฃ็ๅจ่ฟ้้ข่ตท็ไฝ็จ๏ผ
้ฟๅ่ฟๅ ๅคฉๆ็่ฆ่ธ็๏ผๅทฅไฝไธญๆไบไธๅก้่ฆ็จๅฐ่ฐทๆญ้ฎ็ฎฑ๏ผๅฏๆฏ็ฐๅจๅซ่ฏด่ฐทๆญ้ฎ็ฎฑไบ๏ผ่ฐทๆญ้ฝๆไธๅผ๏ผ่ฟๅฏๆฅๅไบ้ฟๅ๏ผๆญฃๅฝ้ฟๅไธ็ญน่ซๅฑไน้
๏ผ็ช็ถๆณๅฐไบๅๅ่ขซๅ
ฌๅธๆดพๅปไฟ็ฝๆฏๅๆๅๆจ้ๅฐ็ฎฑไบ๏ผ่ชๅทฑไธไธไบ่ฐทๆญ๏ผไฝๆฏไบๅ่ฝไธๅ๏ผ่ไธไบๅ็็ต่ๅนถๆฒกๆ่ขซ้ๅถ่ฎฟ้ฎ๏ผไบๆฏ้ฟๅๅฐฑๆณๅบไบไธไธชๅคฉๆ็ๅๆณ๏ผ้ฟๅๅจๅ
ฌๅธ่ฟ็จๆงๅถไบๅ็็ต่่ฎฟ้ฎGoogle้ฎ็ฎฑ๏ผ่ฟไนไธๆฅ้ฎ้ขไพฟๅพๅฐไบๅฎ็พ่งฃๅณใ
่่ฟไธชไพๅญไธญ็่ฏทๆฑ่ทฏๅพๆฏ่ฟๆ ท็๏ผ**ๆไปฌๅ
ๅ้่ฏทๆฑๅฐๆไปฌ็ไปฃ็ๆๅกๅจ๏ผ็ถๅไปฃ็ๆๅกๅจๅๅป่ฏทๆฑGoogle็ๆๅกๅจ๏ผๆๅๅฐ่ฏทๆฑๅฐ็ๅ
ๅฎน่ฟๅ็ปๆไปฌๆฌๆบ**ใ่่ฟๆ ทไธ็งๆจกๅผๅข๏ผๆไปฌๅฐฑ็งฐไนไธบๆญฃๅไปฃ็ใๅฆๅพๆ็คบ(ๅพ็ป็ไธ๏ผไธๆฌก่ฟไธ):

## ๅๅไปฃ็:
ๅจไบ่งฃไบไปไนๆฏๆญฃๅไปฃ็ไนๅ๏ผๅๅไปฃ็ๅฐฑๅฎนๆ็่งฃๅคไบใๆญฃๅไปฃ็ไธญๆไปฌ็ไปฃ็ๆๅกๅจๆฏไฝไธบไธไธชๆถ่ดน่
ๅญๅจ็๏ผ่ๅๅไปฃ็ไธญๆไปฌๅๅฏนๅคๆไพๆๅก๏ผๆไปฌๆฅ็ไธ้ข่ฟไธชไพๅญ:
ไบๅไปไฟ็ฝๆฏๅๆฅไนๅ๏ผไธ็ปฉไธๆฏไธๆ ๆ่ท๏ผๅฅฝๅจๅ
ฌๅธไธ่ณไบๅคช่ฟ็ปๆ
๏ผไบๆฏ็ปไบไบๅไธๆฌกๅฐๅ่กฅ่ฟ็ๆบไผใๅทฅไฝๅ
ๅฎนไนๅพ็ฎๅ๏ผ่ฆๆฑไบๅๅป็ป็ปไธไธชๆๆฐไบไธ้จไธบๅฐๆฅ้ๆดฒ็ๆๆฐไธๅกๅๅๅค๏ผ่ฟๅฝ็ถๆฒก้ฎ้ข๏ผๅๅผๅง็ๆถๅ๏ผไบๅๆ่ง่ฟๅฅฝ๏ผๅ ไธบๅ
ฌๅธ้จ้จไธๅค๏ผๆไปฅๅฏไปฅๅพๆนไพฟๅซๆไธชไบบ็็ผๅทๅปๅฎๆๅทฅไฝ๏ผๆฏๅฆ8080๏ผไฝ ๅปๅค็่ฟไธช่ฏทๆฑ๏ผ8081ไฝ ๅปๅค็่ฟไธช๏ผ8082ไฝ ๅป้ฎ้ฎ้ๆดฒไบบๆฐ็ๆ่งๆไนๆ ท๏ผๅฏๆฏๆ
ขๆ
ข้็ๅ
ฌๅธๅจๆญค้กน็ฎไธๆๅ
ฅ็่ถๆฅ่ถๅค๏ผ้จ้จๅๅทฅไนๆๅฐไบ10000ๅค๏ผ่ฟไธไบๅ่ฟ่ฆ่ฎฐไฝๆฏไธชไบบ็็ผๅทๅฐฑไธๅคช็ฐๅฎไบ๏ผ**ไบๆฏไบๅ่ฎพ็ซไบไธๅฐไปฃ็ๆๅกๅจ๏ผ่ฎฉไปฃ็ๆๅกๅจๅป่ฎฐไฝ่ฟไบไบบ็็ผๅทๅๅ่ฝ๏ผ่ไบๅๅช้่ฆ่ฎฐไฝไปฃ็ๆๅกๅจ็็ผๅทๅฐฑ่กไบ๏ผไบๆฏๆดไธช้จ้จๅจไบๅ็ผ้ๆ
ขๆ
ขๅๆไบไธไธชๆดไฝ๏ผ่ๅ
ทไฝๆๅคๅฐไบบไบๅๅๆฏๅฎๅ
จไธๅ
ณๅฟไบ๏ผ็่ณไบๅ้ฝไธ้่ฆ็ฅ้้จ้จไธญ้ฝๆๅชไบๅๅทฅ๏ผ**ๅฆๅพๆ็คบ:

่ๅๅไปฃ็ๅๆญฃๅไปฃ็ๆๅคง็ๅบๅซๅฐฑๆฏ**ๅฎขๆท็ซฏๅฎๅ
จๆ็ฅไธๅฐไปฃ็็ๅญๅจ**๏ผๆฏๅฆๆไปฌๆญฃๅไปฃ็่ฎฟ้ฎGoogle๏ผๅฏ่ฝ้่ฆๅจๆฌๅฐ่ฝฏไปถๆฏๅฆๅฐ้ฃๆบไธ่ฎพ็ฝฎ็ธๅบ็ไปฃ็ๆๅกๅจ็ๅฐๅๅ็ซฏๅฃ๏ผ่ๅๅไปฃ็ๅๅฎๅ
จไธ้่ฆ่ฎพ็ฝฎ๏ผ**ๆฏๅฆๆทๅฎ๏ผๅฝๅฎขๆท็ซฏๅป่ฎฟ้ฎๆทๅฎ็ๆถๅ๏ผๅฏๅฎๅ
จไธ็ฅ้ๆทๅฎๅผไบๅคๅฐๅฐๆๅกๅจ๏ผๆฏไธชๆๅกๅจ็ๅฐๅๆฏๅคๅฐ๏ผๅช้่ฆๅๅพๅธธไธๆ ทๅจๆต่งๅจไธญ่พๅ
ฅ๏ผtaobao.comๅฐฑ่ก๏ผ่ณไบๅๅไธๅฐ่ณ๏ผ้ฟ้ๅ้ขๅคๅผไบๅคๅฐๅฐๆๅกๅจ๏ผๅฎขๆท็ซฏๅๆฏๅฎๅ
จๆ็ฅไธๅฐ็**๏ผๆๆ็่ฏทๆฑๅๆฏ้่ฟไปฃ็ๆๅกๅจ้่ฟ่ด่ฝฝๅ่กก็ๆนๅผๅๅๅฐไธๅ็ๆๅกๅจไธญไบใ
ไธๅฅ่ฏๆป็ป:
**ๅๅไปฃ็ๆๅกๅจๅ็ฎๆ ๆๅกๅจๅฏนๅคๅฐฑๆฏไธไธชๆๅกๅจ๏ผๆด้ฒ็ๆฏไปฃ็ๆๅกๅจ ๅฐๅ๏ผ้่ไบ็ๅฎๆๅกๅจ IP ๅฐๅใ**
## ่ด่ฝฝๅ่กก:
่ด่ฝฝๅ่กก๏ผๅ
ถๅฎไธ็ฎๆฏไธไธชๆฐ็ๆฆๅฟต๏ผ่ด่ฝฝๅ่กกๅ
ถๅฎๆฏๅจๅๅไปฃ็ๅบ็กไนไธๅฎ็ฐ็๏ผๅฆๆ่ฏดๅๅไปฃ็็็ฎ็ๆฏไธบไบ้่็ๅฎๆๅกๅจ็IPๅฐๅ็่ฏ๏ผ**่ด่ฝฝๅ่กกๅๆฏๆไพไบไธ็ป็ญ็ฅๆฅๅฐ่ฏทๆฑไปไปฃ็ๆๅกๅจไธๅๅๅฐ่ฟไบ็ๅฎ็ๆๅกๅจไธๅป**ใ
ๅจNginxไธญ๏ผไธๅ
ฑๆไพไบไธ็ง่ด่ฝฝๅ่กก็ญ็ฅไพๅผๅ่
็ตๆดป้ๆฉ๏ผ
- **่ฝฎ่ฏข(้ป่ฎคๆนๅผ):** ๆฏไธช่ฏทๆฑๆๆถ้ด้กบๅบ้ไธๅ้
ๅฐไธๅ็ๅ็ซฏๆๅกๅจ๏ผๅฆๆๅ็ซฏๆๅกๅจ down ๆ๏ผ่ฝ่ชๅจๅ้คใ
- **ๆ้(weight):** weight ไปฃ่กจๆ้,้ป่ฎคไธบ 1,ๆ้่ถ้ซ่ขซๅ้
็ๅฎขๆท็ซฏ่ถๅค,ๆ้่ถๅคง๏ผ่ฝๅ่ถๅคง๏ผ่ดฃไปป่ถๅคง๏ผๅค็็่ฏทๆฑๅฐฑ่ถๅคใ
- **ip_hash**๏ผๆฏไธช่ฏทๆฑๆ่ฎฟ้ฎ ip ็ hash ็ปๆๅ้
๏ผ่ฟๆ ทๆฏไธช่ฎฟๅฎขๅบๅฎ่ฎฟ้ฎไธไธชๅ็ซฏๆๅกๅจ๏ผๅฏไปฅ่งฃๅณ session ็้ฎ้ขใ
ไธๅฅ่ฏๆป็ป:
**ๅขๅ ๆๅกๅจ็ๆฐ้๏ผ็ถๅๅฐ่ฏทๆฑๅๅๅฐๅไธชๆๅกๅจไธ๏ผๅฐๅๅ
่ฏทๆฑ้ไธญๅฐๅไธชๆๅกๅจไธ็ๆ
ๅตๆนไธบๅฐ่ฏทๆฑๅๅๅฐๅคไธชๆๅกๅจไธ๏ผๅฐ่ด่ฝฝๅๅๅฐไธๅ็ๆๅกๅจ๏ผไนๅฐฑๆฏๆไปฌๆ่ฏด็่ด่ฝฝๅ่กก**
## ๅจ้ๅ็ฆป:
ๅฝๆไปฌ็ๅบ็จๅๅ
ท่งๆจก๏ผๆๅกๅจๅ็ซฏ้่ฆ้ขๅฏนๅคง้่ฏทๆฑ็่ฏ๏ผๅๆฅ็ๅจ้ๆททๅๆๅ
ๅๅธ็ๆนๅผๅฐฑไธๅ้ฃไน้็จไบ๏ผๅ ไธบๆไปฌๆๅกๅจไธ่พน้่ฆๅปๅค็ๅฎขๆท็ซฏๅ่ฟๆฅ็ๅจๆ่ฏทๆฑ๏ผๆฏๅฆๆฐๆฎๅบ็ๆฅ่ฏข๏ผ่ฎก็ฎ็ญ๏ผๅๅๆถ่ฆๅค็ๅฎขๆท็ซฏๅ่ฟๆฅ็้ๆ่ฏทๆฑ๏ผๆฏๅฆๅพ็๏ผcssๆ ทๅผ็ญ้ๆๆไปถ๏ผๅคง้็่ฏทๆฑๆฏซๆ ็้ฎไผๅขๅ ๆไปฌๅ็ซฏ็ๅๅ๏ผๆคๅ ๆไปฌ็จไบๅค็ๅจๆ่ฏทๆฑ็ๆง่ฝ๏ผไธบไบ่งฃๅณ่ฟไธช้ฎ้ขๅข๏ผไบๆฏๅฐฑๆไบๅจ้ๅ็ฆป่ฟ็ง้จ็ฝฒ็ๆนๅผใ
ๅจ้ๅ็ฆปๅฐฑๆฏๆๅพๅฐไผๅ็ไฟฎๆน็่ฏธๅฆๅพๅ๏ผ่ง้ข๏ผcssๆ ทๅผ็ญ้ๆ่ตๆบๆไปถๆพ็ฝฎๅจๅ็ฌ็ๆๅกๅจไธ๏ผ่ๅจๆ่ฏทๆฑๅ็ฑๅฆๅคไธๅฐๆๅกๅจไธ่ฟ่ก๏ผ่ฟๆ ทไธๆฅ๏ผ่ด่ดฃๅจๆ่ฏทๆฑ็ๆๅกๅจๅๅฏไปฅไธๆณจๅจๅจๆ่ฏทๆฑ็ๅค็ไธ๏ผไป่ๆ้ซไบๆไปฌ็จๅบ็่ฟ่กๆ็๏ผไธๆญคๅๆถ๏ผๆไปฌไนๅฏไปฅ้ๅฏนๆไปฌ็้ๆ่ตๆบๆๅกๅจๅไธๅฑ็ไผๅ๏ผๅขๅ ๆไปฌ้ๆ่ฏทๆฑ็ๅๅบ้ๅบฆใ
Nginx ๅจ้ๅ็ฆป็ฎๅๆฅ่ฏดๅฐฑๆฏๆๅจๆ่ท้ๆ่ฏทๆฑๅๅผ๏ผไธ่ฝ็่งฃๆๅชๆฏๅ็บฏ็ๆๅจๆ้กต้ขๅ้ๆ้กต้ข็ฉ็ๅ็ฆปใไธฅๆ ผๆไนไธ่ฏดๅบ่ฏฅๆฏๅจๆ่ฏทๆฑ่ท้ๆ่ฏทๆฑๅๅผ๏ผๅฏไปฅ็่งฃๆไฝฟ็จ Nginx ๅค็้ๆ้กต้ข๏ผTomcat ๅค็ๅจๆ้กต้ขใๅจ้ๅ็ฆปไป็ฎๅๅฎ็ฐ่งๅบฆๆฅ่ฎฒๅคง่ดๅไธบไธค็ง๏ผ
**ไธ็งๆฏ็บฏ็ฒนๆ้ๆๆไปถ็ฌ็ซๆๅ็ฌ็ๅๅ๏ผๆพๅจ็ฌ็ซ็ๆๅกๅจไธ๏ผไนๆฏ็ฎๅไธปๆตๆจๅด็ๆนๆก๏ผ**
ๅฆๅคไธ็งๆนๆณๅฐฑๆฏๅจๆ่ท้ๆๆไปถๆททๅๅจไธ่ตทๅๅธ๏ผ้่ฟ nginx ๆฅๅๅผ๏ผๅ
ทไฝๅฆไฝ้
็ฝฎ๏ผๅๆNginxๅฎๆไผ่ฏฆ็ป่ฏดๆใ
ๅฆไธๅพๆ็คบ:

## **ๆป็ป:**
ๆฌ็ฏๆ็ซ ไฝไธบNginx็็ฌฌไธ็ฏ๏ผไธป่ฆไพง้่ฎฒไบไปฅไธNginx็ๅไธชๅบๆฌๆฆๅฟต๏ผไนๆฏๆไปฌๆฅๅธธๅผๅไธญ้ๅฐ็ๆไธบ้ข็น็ๅไธชๅ่ฝ๏ผไธไธ่ๅข๏ผๆไปฌๅไปๅฎ้
็ไปฃ็ ๅ
ฅๆ๏ผ้่ฟ็ผๅ็ธๅบ็ไปฃ็ ๏ผไธๆญฅไธๆญฅ็ๅฎๆๅๅไปฃ็๏ผ่ด่ฝฝๅ่กก๏ผๅจ้ๅ็ฆป็้
็ฝฎใ่ๆญฃๅไปฃ็ๅข๏ผๅฆๆๆๅ
ด่ถฃ็ๅฐไผไผดๅฏไปฅ่ช่กๆฅ้
็ธๅ
ณ่ตๆ๏ผ็ๅคดไฟๅฝ๏ผใ
็ธๅ
ณ็ฌ่ฎฐๅทฒ็ปๅๆญฅๅผๆบ่ณๆฌไบบgithub๏ผๆฌข่ฟstar:
[้ฉๆฐ็ๅผๅ็ฌ่ฎฐ](https://github.com/hanshuaikang/HanShu-Note)
ๆๅ๏ผๆฌข่ฟ็น่ต๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ๏ผๆป็จฝ๏ผ
<file_sep># Hystrixๆบ็ ่งฃๆ(ไธ)๏ผๅฟซ้ไธๆ
## ็ๆฌ๏ผ
> ไฝ่
๏ผ้ฉๆฐ
>
> Github๏ผhttps://github.com/hanshuaikang
>
> ๅฎๆๆฅๆ๏ผ2019-07-01ๆฅ
>
> jdk๏ผ1.8
>
> springboot็ๆฌ๏ผ2.1.3.RELEASE
>
> SpringCould็ๆฌ๏ผGreenwich.SR1
## ๅฃฐๆ๏ผ
่บซไธบไธไธชๅๅ
ฅ้จ็่ฎก็ฎๆบ่ไฝฌ๏ผ้
่ฏปๆบ็ ่ช็ถ็ฆปไธๅผไผ็งๅ่ไนฆ็ฑๅ่ง้ข็ๅผๅฏผ๏ผๆฌ็ฏๆ็ซ ็ๅๆ่ฟ็จไธญ"ไธฅ้"ๅ้ดไบ **็ฟๆฐธ่ถ
** ๅ่พ็ใSpringCloudๅพฎๆๅกๅฎๆใ่ฟๆฌไนฆ็ฑ๏ผๅจ่ฟ้ไนๅๅๅคๅญฆไน ๅพฎๆๅก็ๅฐไผไผดไปฌๅผบ็ๆจ่่ฟๆฌไนฆ๏ผๅคงๅฎถๅฏไปฅๆ่ฟ็ฏๆ็ซ ็่งฃไธบใSpringCloudๅพฎๆๅกๅฎๆใRibbon้จๅ็็ฒพ็ฎ็ๅ็ตๅญ็๏ผๅ ไธบไธชไบบๆฐดๅนณ็ๅๅ ๏ผๅพๅค้ฎ้ขไธๆขๅฆไธๅฎ่ฎบ๏ผไปฅๅ
่ฏฏไบบๅญๅผ๏ผๆๆไนฆไธๅพๅคๅ
ๅฎน้ฝๆฏ็ฒพ็ฎ่ฟๅ็ดๆฅๆพไธๅป็๏ผ็ฑไบSpringCloudๅทฒ็ป่ฟญไปฃๅฐไบGreenwich.SR1็ๆฌ๏ผRibbonไนๅไนฆไธๆไบ็ฅๅพฎ็ๅทฎๅซ๏ผๆฌ็ฏๆ็ซ ็ๆบ็ ้็จ็ๆฏRibbonๆๆฐ็ๆฌ๏ผๅๆถ๏ผๅ ไธบๆถ้ดๅๅ ๏ผๆๅพๅค้ขๅค็ๅญ็ฑปๅฎ็ฐๅนถๆฒกๆๅฎๅ
จ้กพไธ๏ผไพๅฆPredicateBasedRule็ฑป็ZoneAvoidanceRuleๅAvailabilityFilteringRule ๆๅ
ด่ถฃ็่ฏป่
ๅฏไปฅไนฐใSpringCloudๅพฎๆๅกๅฎๆใ่ฟๆฌไนฆ็ป็๏ผๅๆถๅผบ็ๆจ่ๅฐ้ฉฌๅฅ็ๅพฎๆๅก็ดๆญ่ฏพ็ณปๅใๅฐ้ฉฌๅฅๅพฎๆๅกๅฎๆใใ
## ่ด่ฐข๏ผ
**็ฟๆฐธ่ถ
**๏ผๅๅฎขๅฐๅ๏ผ
http://blog.didispace.com/aboutme/
**ๅฐ้ฉฌๅฅ๏ผ Java ๅพฎๆๅกๅฎ่ทต - Spring Boot / Spring Cloud่ดญไนฐ้พๆฅ๏ผ**
https://segmentfault.com/ls/1650000011387052
## ็ตๅญ็ๅ็ธๅ
ณไปฃ็ ไธ่ฝฝ๏ผๆฌข่ฟStar๏ผ
Github๏ผhttps://github.com/hanshuaikang/Spring-Note
ๅพฎไฟกๅ
ฌไผๅท๏ผ็ ไธmarson
## Hystrix็ฎไป:
> ๅจๅๅธๅผ็ฏๅขไธญ๏ผ่ฎธๅคๆๅกไพ่ตๅ
ณ็ณปไธญ็ไธไบๅฟ
็ถไผๅคฑ่ดฅใHystrixๆฏไธไธชๅบ๏ผๅฎ้่ฟๆทปๅ ๅปถ่ฟๅฎนๅฟๅๅฎน้้ป่พๆฅๅธฎๅฉๆจๆงๅถ่ฟไบๅๅธๅผๆๅกไน้ด็ไบคไบใHystrix้่ฟ้็ฆปๆๅกไน้ด็่ฎฟ้ฎ็นใๅๆญข่ทจๆๅก็็บง่ๆ
้ๅนถๆไพๅ้้้กนๆฅๅฎ็ฐ่ฟไธ็น๏ผๆๆ่ฟไบ้้กน้ฝๆ้ซไบ็ณป็ป็ๆปไฝๅผนๆงใ
>
>
## ๅฟซ้ไธๆ:
### 1. ๅผๅ
ฅhystrixไพ่ต
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
</dependency>
```
ๆณจ๏ผๆฌๅฎไพไธญ๏ผ้คHystrixไนๅค๏ผEureka,RibbonๅConfigๅๅทฒๆๆฐ้
็ฝฎๅฎๆ๏ผๅฆๆไธ็ฅ้ๅฆไฝ้
็ฝฎEurekaๅRibbon็ๅฐไผไผด๏ผๅฏไปฅๅ่ๆไนๅ็็ธๅ
ณ็ฌ่ฎฐใ้จๅ็ปไปถ้
็ฝฎๅฆไธใ
**Eureka้
็ฝฎ:**
```properties
## Spring Cloud Eureka ๆๅกๅจๅบ็จๅ็งฐ
spring.application.name = eureka-server
## Spring Cloud Eureka ๆๅกๅจๆๅก็ซฏๅฃ
server.port = 10001
## ็ฎก็็ซฏๅฃๅฎๅ
จๅคฑๆ
management.endpoints.web.exposure.include=*
## Spring Cloud Eureka ๆๅกๅจไฝไธบๆณจๅไธญๅฟ
## ้ๅธธๆ
ๅตไธ๏ผไธ้่ฆๅๆณจๅๅฐๅ
ถไปๆณจๅไธญๅฟๅป
## ๅๆถ๏ผๅฎไนไธ้่ฆ่ทๅๅฎขๆท็ซฏไฟกๆฏ
### ๅๆถๅๆณจๅไธญๅฟๆณจๅ
eureka.client.register-with-eureka = false
### ๅๆถๅๆณจๅไธญๅฟ่ทๅๆณจๅไฟกๆฏ๏ผๆๅกใๅฎไพไฟกๆฏ๏ผ
eureka.client.fetch-registry = false
## ่งฃๅณ Peer / ้็พค ่ฟๆฅ้ฎ้ข
eureka.instance.hostname = localhost
eureka.client.serviceUrl.defaultZone = http://${eureka.instance.hostname}:${server.port}/eureka
```
**Ribbon้
็ฝฎ**
```properties
# ๆๅก็ซฏๅฃ
server.port = 8080
## ็จๆท Ribbon ๅฎขๆท็ซฏๅบ็จ
spring.application.name = user-robbon-client
## ้
็ฝฎๅฎขๆท็ซฏๅบ็จๅ
ณ่็ๅบ็จ
## spring.cloud.config.name ๆฏๅฏ้็
## ๅฆๆๆฒกๆ้
็ฝฎ๏ผ้็จ ${spring.application.name}
spring.cloud.config.name = user-service
## ๅ
ณ่ profile
spring.cloud.config.profile = default
## ๅ
ณ่ label
spring.cloud.config.label = master
## ๆฟๆดป Config Server ๆๅกๅ็ฐ
spring.cloud.config.discovery.enabled = true
## Config Server ๆๅกๅจๅบ็จๅ็งฐ
spring.cloud.config.discovery.serviceId = config-server
## Spring Cloud Eureka ๅฎขๆท็ซฏ ๆณจๅๅฐ Eureka ๆๅกๅจ
eureka.client.serviceUrl.defaultZone = http://localhost:10001/eureka
spring.cloud.config.uri = http://127.0.0.1:7070/
## ๆฉๅฑ IPing ๅฎ็ฐ
user-service-provider.ribbon.NFLoadBalancerPingClassName = \
com.jdkcb.user.ribbon.client.ping.MyPing
```
**config้
็ฝฎ:**
```properties
## Spring Cloud Config Server ๅบ็จๅ็งฐ
spring.application.name = config-server
## ๆๅกๅจๆๅก็ซฏๅฃ
server.port = 7070
## ็ฎก็็ซฏๅฃๅฎๅ
จๅคฑๆ
management.endpoints.web.exposure.include=*
## Spring Cloud Eureka ๅฎขๆท็ซฏ ๆณจๅๅฐ Eureka ๆๅกๅจ
eureka.client.serviceUrl.defaultZone = http://localhost:10001/eureka
### ้
็ฝฎๆๅกๅจๆไปถ็ณป็ปgit ไปๅบ
### ${user.dir} ๅๅฐๅนณๅฐๆไปถ็ณป็ป็ไธไธ่ด
### ็ฎๅ ${user.dir}/config-server/src/main/resources/configs
spring.cloud.config.server.git.uri = ${user.dir}/config-server/src/main/resources/configs
```
**user-services.properties**:
```properties
## ๆไพๆนๆๅกๅ็งฐ
provider.service.name = user-service-provider
## ๆไพๆนๆๅกไธปๆบ
provider.service.host = localhost
## ๆไพๆนๆๅก็ซฏๅฃ
provider.service.port = 9090
user.service.name = ${provider.service.name}
```
### 2.้่ฟ@EnableHystrixๆณจ่งฃๆฟๆดปๆๅกๆไพๆน็ญ่ทฏ
```java
@SpringBootApplication
@EnableHystrix
@EnableDiscoveryClient
public class UserServiceProviderApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceProviderApplication.class, args);
}
}
```
### 3.้่ฟ`@HystrixCommand`ๅฎ็ฐๆๅกๆไพๆน็ญ่ทฏใ
ไฟฎๆนๆๅกๆไพๆน(user-service-provider)้กน็ฎ็ UserServiceProviderController็findAll()ๆนๆณ๏ผๅจๆนๆณไธๆทปๅ @HystrixCommandๆณจ่งฃ๏ผๅนถ่ฎพ็ฝฎๅๆฐๅฆไธ๏ผ
```java
@HystrixCommand(
commandProperties = { // Command ้
็ฝฎ
// ่ฎพ็ฝฎๆไฝๆถ้ดไธบ 100 ๆฏซ็ง
@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds", value = "100")
},
fallbackMethod = "fallbackForGetUsers" // ่ฎพ็ฝฎ fallback ๆนๆณ
)
// ้่ฟๆนๆณ็ปงๆฟ๏ผURL ๆ ๅฐ ๏ผ"/user/find/all"
@Override
public List<User> findAll() {
return userService.findAll();
}
/**
* {@link #getUsers()} ็ fallback ๆนๆณ
*
* @return ็ฉบ้ๅ
*/
public List<User> fallbackForGetUsers() {
return Collections.emptyList();
}
```
ๅ่ฝ:ๅฝๆๅก่ฏทๆฑๆนๅๆฅไธไธช่ฏทๆฑๆถ๏ผๅฆๆfindAll่ทฏ็ฑๅๅบๆถ้ดๅจ100ๆฏซ็งๅ
๏ผๅ่ฟๅfindAll็ๅ
ๅฎน๏ผๅฆๆ100ๆฏซ็งๅๅ็ฐ่ฟๆฏๆฒกๆๅๆถๅๅบ๏ผๅ่ฟๅๆไปฌไนๅๆ่ฎพ็ฝฎๅฅฝ็fallbackForGetUsersๆนๆณๆๆไพ็ๅ
ๅฎนใ
### 4.ไฝฟ็จ`@EnableCircuitBreaker` ๅฎ็ฐๆๅก่ฐ็จๆน็ญ่ทฏ๏ผ
```java
@RibbonClient("user-service-provider") // ๆๅฎ็ฎๆ ๅบ็จๅ็งฐ
@EnableCircuitBreaker // ไฝฟ็จๆๅก็ญ่ทฏ
@EnableFeignClients(clients = UserService.class)
@EnableDiscoveryClient
@SpringBootApplication
@EnableBinding(UserMessage.class)
public class UserRibbonClientApplication {
public static void main(String[] args) {
SpringApplication.run(UserRibbonClientApplication.class, args);
}
/**
ๆฟๆดปๅ
ทๆ่ด่ฝฝ่ฝๅ็RestTemplate
*/
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
//่ชๅฎไนRule
@Bean
public IRule myRule() {
return new MyRule();
}
}
```
### 5. ๆๅก่ฐ็จ๏ผ
```java
/**
* ่ฐ็จ user-service-provider "/user/list" REST ๆฅๅฃ๏ผๅนถไธ็ดๆฅ่ฟๅๅ
ๅฎน
* ๅขๅ ็ญ่ทฏๅ่ฝ
*/
@GetMapping("/user-service-provider/user/list")
public Collection<User> getUsersList() {
return restTemplate.getForObject("http://" + providerServiceName + "/user/list", Collection.class);
}
```
่ฟ่ก็จๅบ๏ผๆไปฌๅฏไปฅ็ๅฐ๏ผๅฝๆไปฌ่ฎฟ้ฎๆๅก่ฐ็จๆน็**/user-service-provider/user/list**่ทฏ็ฑๆถ๏ผๅฆๆ**user-service-provider**็**/user/list**ไธ็พๆฏซ็งๅ
ๅฎๆๅๅบ๏ผๅไผ่ฟๅไธไธชๆไปฌไนๅๆๆทปๅ ๅ
ๅฎน็้ๅ๏ผๅฆๅ๏ผ่ฟๅไธไธช็ฉบ็้ๅใ
### 6.ไฝฟ็จ็ผ็จๆนๅผ่ชๅฎไน็ญ่ทฏๅฎ็ฐ๏ผ
```java
public class UserRibbonClientHystrixCommand extends HystrixCommand<Collection> {
//ๅฎไนproviderServiceName:ๆๅกๅ
private final String providerServiceName;
//ๅฎไน RestTemplateๅ้่ฏทๆฑ
private final RestTemplate restTemplate;
//ๆ้ ๅฝๆฐ
public UserRibbonClientHystrixCommand(String providerServiceName, RestTemplate restTemplate) {
super(HystrixCommandGroupKey.Factory.asKey(
"User-Ribbon-Client"),
100);//่ฎพ็ฝฎ่ถ
ๆถๆถ้ด
this.providerServiceName = providerServiceName;
this.restTemplate = restTemplate;
}
/**
* ไธป้ป่พๅฎ็ฐ
*
* @return
* @throws Exception
*/
@Override
protected Collection run() throws Exception {
return restTemplate.getForObject("http://" + providerServiceName + "/user/list", Collection.class);
}
/**
* Fallback ๅฎ็ฐ
*
* @return ็ฉบ้ๅ
*/
protected Collection getFallback() {
return Collections.emptyList();
}
}
```
้่ฟ็ผ็จๆนๆณๅฎ็ฐ็ญ่ทฏ็ๆถๅ๏ผๅๅฐ่ฐ็จ็ๆนๅผไน่ฆ็ธๅบ็ๅๅบ่ฐๆด:
```java
@GetMapping("/user-service-provider/user/list")
public Collection<User> getUsersList() {
return new UserRibbonClientHystrixCommand(providerServiceName, restTemplate).execute();
}
```
### 7.ๆๅก็ๆงHystrix Dashboardไปช่กจ็๏ผ
ๅ่ฝ:็จๆฅ็ๆงHystrix็ๅ้กนๆๆ ไฟกๆฏ๏ผ้่ฟHystrix Dashboardๅ้ฆ็ๅฎๆถไฟกๆฏ,ๅธฎๅฉๆไปฌๆดๅฎนๆๆพๅฐ็จๅบไธญ็้ฎ้ข๏ผ่ฏฅ็ปไปถ็ฎๅๅทฒ็ป่ขซๅผ็จใ
ๆฐๅปบไธไธช้กน็ฎ**"hystrix-ashboard"**
#### 1.ๅผๅ
ฅไพ่ต๏ผ
```xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-netflix-hystrix-dashboard</artifactId>
</dependency>
```
#### 2.ไฝฟ็จ@EnableHystrixDashboardๆณจ่งฃๆฟๆดปHystrix Dashboardไปช่กจ็
```java
@SpringBootApplication
@EnableHystrixDashboard
public class HystrixDashboardApplication {
public static void main(String[] args) {
SpringApplication.run(HystrixDashboardApplication.class, args);
}
}
```
#### 3.้
็ฝฎ่ฏฅ้กน็ฎ๏ผ
```properties
## Hystrix Dashboard ๅบ็จ
spring.application.name = hystrix-dashboard
## ๆๅก็ซฏๅฃ
server.port = 10000
```
hystrixไฝไธบไธไธชๆๅกๅฎน้ไฟๆค็ปไปถ๏ผๅฏไปฅ้ฟๅ
ๅ ไธบ่ฏทๆฑๅพไธๅฐๅๆถๅๅบ่ๅฏ่ฝๅบ็ฐ็ๅคง้่ฏทๆฑๆคๅ๏ผ็่ณๅผๅ้ชๅดฉๆๅบ็ๆ
ๅต๏ผ้ๅพไธไธชๆๅกไธๅฏ็จไนๅ็ดๆฅ็ๆญๆๅก๏ผ่ไธ่ณไบๅฏผ่ดๆดไธชๅๅธๅผๅบ็จ้ฝๅๅฐๅฝฑๅใ
<file_sep>package com.jdkcb.demo.event;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
public class TestController {
@Autowired
private NotifyPublisher notifyPublisher;
@GetMapping("/sayHello")
public String sayHello(){
notifyPublisher.publishEvent(1, "ๆๅๅธไบไธไธชไบไปถ");
return "Hello Word";
}
}
<file_sep># ๅฐๅบไปไนๆฏๅบ็จไธไธๆ๏ผ
## ๅ่จ:
ๆฅๅธธๅผๅๆปๆฏไผ็ๅฐไธไธๆไธไธชๅญ๏ผๅบ็จไธไธๆ๏ผๆง่กไธไธๆ็ญ็ญ๏ผๅๅผๅง็ๆถๅ็ๅฐ่ฟไธไธชๅญๅ
ถๅฎไนๆฒกไปไนๆ่ง๏ผๅฐฑ่ทๅนณๅธธๅ้ฅญ็ก่งไธๆ ทๆ นๆฌไธไผๅคๆณ
็ดๅฐๆไธๅคฉ๏ผไธไธชๅฏๆ็ๅฟตๅคด็ช็ถๅบ็ฐๅจไบๆ็่ๆตทไธญ
**ๅฐๅบไปไนๆฏๅบ็จไธไธๆ๏ผ**

๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ
ๅฝๆถๆๅฐฑ่ทๆฉไธๅ่ตทๅบ้ฃ็ถๆไธๆ ท๏ผ็ฏ้กพๅๅจ๏ผ็ผ็้ๅ
ๆปกไบ็ๆๅ่ฟท่ซ๏ผไธไธๆ้ฃไธไธชๅญๅฐฑๅ่ฟท้พไธญ็ไธไธชๅฝฑๅญ๏ผๆๅฅฝๅ็ฅ้้ฃๆฏไธชๅฅ๏ผไฝๆฏๆไธ็ฅ้้ฃ็ฉถ็ซๆฏไธชๅฅ๏ผไฝๆฏๆๆๆพไธๅฐๅซ็้ฃไธชๅฅๅป่งฃ้่ฟไธชๅฅใ
nb๏ผๆฑๅญๆๅๅๅคง็ฒพๆทฑใ
ๅฏ่ฝๆฏ่ชๅทฑๅนณๆถๆฒกๆไบ่งฃ่ฟ่ฟๅ็ฅ่ฏๅง๏ผไบๆฏๆ้ฎไบ้ฎ่บซ่พน็ๅฐไผไผดไปฌไปไนๆฏๅบ็จไธไธๆ
๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ
ๅฐฑๆฏ๏ผไธไธๆ๏ผๅฐฑๆฏ๏ผ๏ผ้ฃ็ง๏ผ่ฏญๅขๅ๏ผๅพๆฎ้็ไธไธชๆฆๅฟตใ
ๅฏนไธ่ตท๏ผๅ๏ผๆๆณ่ตทๆฅๅฅฝ็ฌ็ไบๆ
๏ผ**่ดๆฌ็พไบบ้ฑผๆข**๏ผ
ไบๆฏ่ๅญ้ไธๅขๆฏ็บฟ็็ๆๅธฆ็ๆทฑๆทฑ็้ฎๅฏๅธๆไบ็พๅบฆ๏ผไผๅพๅจๅญ้่ก้ดๅ็ฐjava็ผ็จ็็่ฐใ
> ไธไธๆ๏ผๅณ่ฏญๅขใ่ฏญๆ๏ผๆฏ่ฏญ่จๅญฆ็ง๏ผ่ฏญ่จๅญฆใ็คพไผ่ฏญ่จๅญฆใ็ฏ็ซ ๅๆใ่ฏญ็จๅญฆใ็ฌฆๅทๅญฆ็ญ๏ผ็ๆฆๅฟตใ
> ่ฏญๆๅๆ๏ผsemantic analysis๏ผๆๆฏ็ณปๆๅฐไธ้ฟไธฒ็ๆๅญๆๅ
ๅฎน๏ผไปๅ
ถไธญๅๆๅบ่ฏฅไธชๆฎต่ฝ็ๆ่ฆไปฅๅๅคงๆ๏ผ็่ณๆด่ฟไธๆญฅ๏ผๅฐๆด็ฏๆ็ซ ็ๆๆๆด็ๅบๆฅใๆญค้กนๆๆฏๅฏไปฅๅบ็จๅจ่งฃ่ฏปๅฝฑ็ใ้ณ่ฎฏ็ญๆกฃๆก๏ผไฝฟๅพๆ็ดขๅผๆ่ฝๅคๆๅฏปๅฐๆๅญไปฅๅค็็ฉไปถ๏ผๆนไพฟไฝฟ็จ่
็ๅปๅคง้ๆถ้ด่ง็ๅฝฑ็ใ่ๅฌ้ณ่ฎฏ๏ผๅๆถไนๅฏไปฅๅธฎๅฉไฝฟ็จ่
ๆๅไบ่งฃๅฝฑ็ไธ้ณ่ฎฏ็ๅ
ๅฎนใ
ๆ๏ผ%#๏ฟฅโฆโฆ๏ฟฅ๏ฟฅ#๏ฟฅ@#%๏ฟฅ๏ฟฅ%โฆโฆ#๏ฟฅ#@

ๆไปฅๅฐๅบไปไนๆฏไธไธๆ๏ผๅฎๅจ็ผ็จไธญ็ๅ
ทไฝ่ตทไปไนไฝ็จ๏ผไบๆฏๅธฆ็่ฟไธช้ฎ้ข๏ผๆ่ธไธไบๅฏปๆพ็ญๆก็ๆผซ้ฟ็ๆ
้ไธญ๏ผ็ปไบ๏ผ่ๅคฉไธ่ดๆๅฟไบบ๏ผๆ่ฟๆฏๆฒกๆๆพๅฐๅ
ทไฝ็่งฃ้ใ
ๅฅฝๅง๏ผไปๅคฉๅๆ็ซ ๅฐฑๅฐ่ฟ้็ปๆไบ๏ผ่ฝ็ถไธๆไธญ่ฏดไบๅพๅค็ๅบ่ฏ๏ผไฝๆฏ่ฟไปถไบๆ
้ๆธๆฒกๆไบไธๆใ
็ญ็ญ๏ผไฝ ๅๆ่ฏดไบไธๆๅฏนๅง๏ผๅ่ฏดไบไธๆๅฏนๅง๏ผ่ดๆฌjojoๆข๏ผ
ๆฏๅ๏ผๅไธ่ตทไธๅฐฑๆฏไธไธๆๅ๏ผ
ๅงๆงฝ
ๆไปฅ๏ผไธไธๆไปฃ่กจ็ๅ
ถๅฎๆฏไธไธชๆดไฝ็็ฏๅข๏ผๅฐฑๆฏๅฆ่ฏด่ฟ็ฏๆ็ซ ๏ผๆไปฌๅฏไปฅ่ฏด**ไธๆไธญ**๏ผ่ฎฟ้ฎๅฐไธๆๆ้่ฟฐ็ๅ
ๅฎน๏ผไนๅฏไปฅ่ฏด**ไธๆไธญ**๏ผ่ฎฟ้ฎๅฐไธๆไธญ็ๅ
ๅฎน๏ผ่ๆไปฌ่ฟ็ฏๆ็ซ ไธญๆฏไธๆฎตๆๅญๆไปฃ่กจ็ๆๆ๏ผๆฏ่ฆๆ นๆฎๆไปฌ็ไธไธๆๆฅๅณๅฎ็๏ผๅ ไธบไฝ ้ไพฟๆฟๅบๆฅไธๅฅ่ฏไธๅป็ปๅๆดไฝ็่ฏญๅขๅป็่งฃๅบๆฅ็ๆๆ่ฏๅฎไธๆฏๅ็กฎ็๏ผๆไปฅ๏ผๆไปฌ่ฟ็ฏๆ็ซ ็ไธไธๆๅฐฑๆฏๆไปฌๆด็ฏ็ไธญๅฟๆๆณใ
ไธพไธชไพๅญ๏ผๆฏๅฆๆไปฌๅจSpringไธญ็ๆฐๆฎๆบ๏ผๅฐฑๆฏๅญๅจๅจไธไธๆไธญ็๏ผ่ฟไธชๆถๅ๏ผไธ่ฎบๆฏๅช้็ไปฃ็ ๏ผ้ฝๆฏๅฏไปฅ้่ฟไธไธๆ่ทๅๅฐๆฐๆฎ่ฟๆฅๅนถ่ฟ่ก็ธๅ
ณ็ๆไฝ็๏ผๅๆ ท็๏ผๆไปฌๅฏไปฅๅจไปปไฝๅฐๆน้่ฟspringไธญ็ไธไธๆ่ทๅๅฐbeanๅๅ
ถไป็้
็ฝฎไฟกๆฏ๏ผๅฝ็ถ๏ผ่ฟ้็ไปปไฝๅฐๆนๆฏๆไปฌSpringๅๅงๅๅทฅไฝๅฎๆไนๅ็ๅฐๆนใ
ไธไธๆไธญ้ๅธธๆ็ๆฏๆไปฌๅฝๆถ่ฟ่ก็็ฏๅข๏ผๆฏๅฆ่ฏดๅๆ ทๆฏbreak่ฏญๅฅ๏ผๅจif้้ขๅๅจswitch้้ขไฝ็จๅดไธไธๆ ท๏ผ้พ้ๆฏbreak่ฟไธช่ฏญๅฅๅไบๅ๏ผๅฝ็ถๆฏๆฒกๆ๏ผๆฏๅฎๅฝๆถ็็ฏๅขๅ้ไบๅๅ๏ผไนๅฐฑๆฏไธไธๆ็ฏๅขๅ็ไบๅๅใ
ๅ่
๏ผๆฏๅฆๆไปฌๅบ็จ่ฟ่ก็บฟ็จๅๆข็ๆถๅ๏ผๅๆขๅ้ฝไผๆ็บฟ็จ็็ถๆไฟกๆฏๆๆถๅจๅญๅจๅฏๅญๅจไธญ๏ผ่ฟ้็ไธไธๆๅฐฑๅ
ๆฌไบๅฝๆถๅฏๅญๅจ็ๅผ๏ผๆๅฏๅญๅจ็ๅผ้ฝไฟๅญ่ตทๆฅ๏ผ็ญไธๆฌก่ฏฅ็บฟ็จๅๅพๅฐCPUๆถ้ด็ๆถๅๅๆขๅคๅฏๅญๅจ็ๅผ๏ผ่ฟๆ ท็บฟ็จๆ่ฝๆญฃ็กฎ็่ฟ่กใ
ๅๅฐ็ฐๅจ๏ผๆๅ็ฐๆ็ๆ่ทฏๅนถๆฒกๆๆธ
ๆฐๅคๅฐ๏ผไฝๆฏๅฏนไธไธๆๅทฒ็ปๆไบๆดไฝ็็่งฃ
**ไธไธๆ๏ผไธไธๆไปฃ่กจไบ็จๅบๅฝไธๆ่ฟ่ก็็ฏๅข๏ผ่็ณปไฝ ๆดไธชapp็็ๅฝๅจๆไธ่ตๆบ่ฐ็จ๏ผๆฏ็จๅบๅฏไปฅ่ฎฟ้ฎๅฐ็ๆๆ่ตๆบ็ๆปๅ๏ผ่ตๆบๅฏไปฅๆฏไธไธชๅ้๏ผไนๅฏไปฅๆฏไธไธชๅฏน่ฑก็ๅผ็จใ**
่ฟๅคงๆฆๅฐฑๆฏๆๅฏนไธไธๆ็็่งฃไบ๏ผๅฆๆๅคงๅฎถๆไธๅ็็่งฃ๏ผๆฌข่ฟ็่จๅจๆฌ็ฏๆ็ซ ไธๆนใ
ๆๆฏ้ฉๆฐ๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ~
<file_sep># SpringBoot + Mybatisไฝฟ็จAOPๅๆณจ่งฃๅฎ็ฐๅจๆๅๆขๆฐๆฎๆบ้
็ฝฎ
## ๅ่จ:
้็ๅบ็จ็จๆทๆฐ้็ๅขๅ ๏ผ็ธๅบ็ๅนถๅ่ฏทๆฑ็ๆฐ้ไนไผ่ท็ไธๆญๅขๅ ๏ผๆ
ขๆ
ขๅฐ๏ผๅไธชๆฐๆฎๅบๅทฒ็ปๆฒกๆๅๆณๆปก่ถณๆไปฌ้ข็น็ๆฐๆฎๅบๆไฝ่ฏทๆฑไบ๏ผๅจๆไบๅบๆฏไธ๏ผๆไปฌๅฏ่ฝไผ้่ฆ้
็ฝฎๅคไธชๆฐๆฎๆบ๏ผไฝฟ็จๅคไธชๆฐๆฎๆบ(ไพๅฆๅฎ็ฐๆฐๆฎๅบ็่ฏปๅๅ็ฆป)ๆฅ็ผ่งฃ็ณป็ป็ๅๅ็ญ๏ผๅๆ ท็๏ผSpringbootๅฎๆนๆไพไบ็ธๅบ็ๅฎ็ฐๆฅๅธฎๅฉๅผๅ่
ไปฌ้
็ฝฎๅคๆฐๆฎๆบ๏ผไธ่ฌๅไธบไธค็งๆนๅผ(็ฎๅๆๆไบ่งฃๅฐ็)๏ผๅๅ
ๅAOP๏ผ่ๅจไธไธ็ฏๆ็ซ [Springboot +Mybatisๅฎ็ฐๅคๆฐๆฎๆบ้
็ฝฎ](https://juejin.im/post/5d773babe51d4561ba48fe68)ไธญ๏ผๆไปฌๅฎ็ฐไบ้ๆๅคๆฐๆฎๆบ็้
็ฝฎ๏ผไฝๆฏ่ฟ็งๆไน่ฏดๅข๏ผๅจๅฎ้
็ไฝฟ็จไธญไธๅค็ตๆดป๏ผไธบไบ่งฃๅณ่ฟไธช้ฎ้ขๅข๏ผๆไปฌๅฏไปฅไฝฟ็จไธๆๆๅฐ็็ฌฌไบ็งๆนๆณ,ๅณไฝฟ็จAOP้ขๅๅ้ข็ผ็จ็ๆนๅผๆฅๅฎ็ฐๅจไธๅๆฐๆฎๆบไน้ดๅจๆๅๆข็็ฎ็ใ
## 1. ๆฐๆฎๅบๅๅค๏ผ
ๆฐๆฎๅบๅๅคไป็ถๅไนๅ็ไพๅญ็ธๅ๏ผๅ
ทไฝๅปบ่กจsql่ฏญๅฅๅไธๅ่ฏฆ็ป่ฏดๆ๏ผ่กจๆ ผๅฆไธ๏ผ
| ๆฐๆฎๅบ | testdatasource1 | testdatasource2 |
| ------ | ------------------------------------------------ | --------------- |
| ๆฐๆฎ่กจ | sys_user | sys_user2 |
| ๅญๆฎต | user_id(int), user_name(varchar) user_age๏ผint๏ผ | ๅ |
ๅนถๅๅซๆๅ
ฅไธคๆก่ฎฐๅฝ๏ผไธบไบๆนไพฟๅฏนๆฏ๏ผๅ
ถไธญtestdatasource1ไธบ่ณๅนด25ๅฒ็ๅผ ไธ๏ผ testdatasource2ไธบ่ณๅนด30ๅฒ็ๆๅใ
## 2. ็ฏๅขๅๅค๏ผ
้ฆๅ
ๆฐๅปบไธไธชSpringboot้กน็ฎ๏ผๆ่ฟ้็ๆฌๆฏ2.1.7.RELEASE๏ผๅนถๅจpomๆไปถไธญๅผๅ
ฅ็ธๅ
ณไพ่ต๏ผๅไธๆฌก็ธๆฏ๏ผ่ฟๆฌกไธป่ฆ้ขๅคๆฐๅขไบaop็ธๅ
ณ็ไพ่ต๏ผๅฆไธ:
```xml
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>5.1.5.RELEASE</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.2</version>
</dependency>
```
## 3.ไปฃ็ ้จๅ
้ฆๅ
ๅข๏ผๅจๆไปฌSpringboot็้
็ฝฎๆไปถไธญ้
็ฝฎๆไปฌ็datasourse๏ผๅไปฅๅพไธไธๆ ท็ๆฏ๏ผๅ ไธบๆไปฌๆไธคไธชๆฐๆฎๆบ๏ผๆไปฅ่ฆๆๅฎ็ธๅ
ณๆฐๆฎๅบ็ๅ็งฐ๏ผๅ
ถไธญไธปๆฐๆฎๆบไธบprimary๏ผๆฌกๆฐๆฎๆบไธบsecondaryๅฆไธ:
```properties
#้
็ฝฎไธปๆฐๆฎๅบ
spring.datasource.primary.jdbc-url=jdbc:mysql://localhost:3306/testdatasource1?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.primary.username=root
spring.datasource.primary.password=<PASSWORD>
spring.datasource.primary.driver-class-name=com.mysql.cj.jdbc.Driver
##้
็ฝฎๆฌกๆฐๆฎๅบ
spring.datasource.secondary.jdbc-url=jdbc:mysql://localhost:3306/testdatasource2?useUnicode=true&characterEncoding=UTF-8&serverTimezone=UTC&useSSL=false
spring.datasource.secondary.username=root
spring.datasource.secondary.password=<PASSWORD>
spring.datasource.secondary.driver-class-name=com.mysql.cj.jdbc.Driver
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
```
> ้่ฆๆไปฌๆณจๆ็ๆฏ๏ผSpringboot2.0 ๅจ้
็ฝฎๆฐๆฎๅบ่ฟๆฅ็ๆถๅ้่ฆไฝฟ็จjdbc-url๏ผๅฆๆๅชไฝฟ็จurl็่ฏไผๆฅ
>
> jdbcUrl is required with driverClassName.้่ฏฏใ
ๆฐๅปบไธไธช้
็ฝฎๆไปถ๏ผDynamicDataSourceConfig ็จๆฅ้
็ฝฎๆไปฌ็ธๅ
ณ็bean,ไปฃ็ ๅฆไธ
```java
@Configuration
@MapperScan(basePackages = "com.mzd.multipledatasources.mapper", sqlSessionFactoryRef = "SqlSessionFactory") //basePackages ๆไปฌๆฅๅฃๆไปถ็ๅฐๅ
public class DynamicDataSourceConfig {
// ๅฐ่ฟไธชๅฏน่ฑกๆพๅ
ฅSpringๅฎนๅจไธญ
@Bean(name = "PrimaryDataSource")
// ่กจ็คบ่ฟไธชๆฐๆฎๆบๆฏ้ป่ฎคๆฐๆฎๆบ
@Primary
// ่ฏปๅapplication.propertiesไธญ็้
็ฝฎๅๆฐๆ ๅฐๆไธบไธไธชๅฏน่ฑก
// prefix่กจ็คบๅๆฐ็ๅ็ผ
@ConfigurationProperties(prefix = "spring.datasource.primary")
public DataSource getDateSource1() {
return DataSourceBuilder.create().build();
}
@Bean(name = "SecondaryDataSource")
@ConfigurationProperties(prefix = "spring.datasource.secondary")
public DataSource getDateSource2() {
return DataSourceBuilder.create().build();
}
@Bean(name = "dynamicDataSource")
public DynamicDataSource DataSource(@Qualifier("PrimaryDataSource") DataSource primaryDataSource,
@Qualifier("SecondaryDataSource") DataSource secondaryDataSource) {
//่ฟไธชๅฐๆนๆฏๆฏ่พๆ ธๅฟ็targetDataSource ้ๅๆฏๆไปฌๆฐๆฎๅบๅๅๅญไน้ด็ๆ ๅฐ
Map<Object, Object> targetDataSource = new HashMap<>();
targetDataSource.put(DataSourceType.DataBaseType.Primary, primaryDataSource);
targetDataSource.put(DataSourceType.DataBaseType.Secondary, secondaryDataSource);
DynamicDataSource dataSource = new DynamicDataSource();
dataSource.setTargetDataSources(targetDataSource);
dataSource.setDefaultTargetDataSource(primaryDataSource);//่ฎพ็ฝฎ้ป่ฎคๅฏน่ฑก
return dataSource;
}
@Bean(name = "SqlSessionFactory")
public SqlSessionFactory SqlSessionFactory(@Qualifier("dynamicDataSource") DataSource dynamicDataSource)
throws Exception {
SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
bean.setDataSource(dynamicDataSource);
bean.setMapperLocations(
new PathMatchingResourcePatternResolver().getResources("classpath*:mapping/*/*.xml"));//่ฎพ็ฝฎๆไปฌ็xmlๆไปถ่ทฏๅพ
return bean.getObject();
}
}
```
่ๅจ่ฟๆๆ็้
็ฝฎไธญ๏ผๆๆ ธๅฟ็ๅฐๆนๅฐฑๆฏDynamicDataSource่ฟไธช็ฑปไบ๏ผDynamicDataSourceๆฏๆไปฌ่ชๅฎไน็ๅจๆๅๆขๆฐๆฎๆบ็็ฑป๏ผ่ฏฅ็ฑป็ปงๆฟไบAbstractRoutingDataSource ็ฑปๅนถ้ๅไบๅฎ็determineCurrentLookupKey()ๆนๆณใ
AbstractRoutingDataSource ็ฑปๅ
้จ็ปดๆคไบไธไธชๅไธบtargetDataSources็Map๏ผๅนถๆไพ็setterๆนๆณ็จไบ่ฎพ็ฝฎๆฐๆฎๆบๅ
ณ้ฎๅญไธๆฐๆฎๆบ็ๅ
ณ็ณป๏ผๅฎ็ฐ็ฑป่ขซ่ฆๆฑๅฎ็ฐๅ
ถdetermineCurrentLookupKey()ๆนๆณ๏ผ็ฑๆญคๆนๆณ็่ฟๅๅผๅณๅฎๅ
ทไฝไปๅชไธชๆฐๆฎๆบไธญ่ทๅ่ฟๆฅใๅๆถAbstractRoutingDataSource็ฑปๆไพไบ็จๅบ่ฟ่กๆถๅจๆๅๆขๆฐๆฎๆบ็ๆนๆณ๏ผๅจdao็ฑปๆๆนๆณไธๆ ๆณจ้่ฆ่ฎฟ้ฎๆฐๆฎๆบ็ๅ
ณ้ฎๅญ๏ผ่ทฏ็ฑๅฐๆๅฎๆฐๆฎๆบ๏ผ่ทๅ่ฟๆฅใ
DynamicDataSourceไปฃ็ ๅฆไธ:
```java
public class DynamicDataSource extends AbstractRoutingDataSource {
@Override
protected Object determineCurrentLookupKey() {
DataSourceType.DataBaseType dataBaseType = DataSourceType.getDataBaseType();
return dataBaseType;
}
}
```
DataSourceType็ฑป็ไปฃ็ ๅฆไธ:
```java
public class DataSourceType {
//ๅ
้จๆไธพ็ฑป๏ผ็จไบ้ๆฉ็นๅฎ็ๆฐๆฎ็ฑปๅ
public enum DataBaseType {
Primary, Secondary
}
// ไฝฟ็จThreadLocalไฟ่ฏ็บฟ็จๅฎๅ
จ
private static final ThreadLocal<DataBaseType> TYPE = new ThreadLocal<DataBaseType>();
// ๅพๅฝๅ็บฟ็จ้่ฎพ็ฝฎๆฐๆฎๆบ็ฑปๅ
public static void setDataBaseType(DataBaseType dataBaseType) {
if (dataBaseType == null) {
throw new NullPointerException();
}
TYPE.set(dataBaseType);
}
// ่ทๅๆฐๆฎๆบ็ฑปๅ
public static DataBaseType getDataBaseType() {
DataBaseType dataBaseType = TYPE.get() == null ? DataBaseType.Primary : TYPE.get();
return dataBaseType;
}
// ๆธ
็ฉบๆฐๆฎ็ฑปๅ
public static void clearDataBaseType() {
TYPE.remove();
}
}
```
ๆฅไธๆฅ็ผๅๆไปฌ็ธๅ
ณ็Mapperๅxmlๆไปถ๏ผไปฃ็ ๅฆไธ:
```java
@Component
@Mapper
public interface PrimaryUserMapper {
List<User> findAll();
}
@Component
@Mapper
public interface SecondaryUserMapper {
List<User> findAll();
}
```
```xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jdkcb.mybatisstuday.mapper.one.PrimaryUserMapper">
<select id="findAll" resultType="com.jdkcb.mybatisstuday.pojo.User">
select * from sys_user;
</select>
</mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jdkcb.mybatisstuday.mapper.two.SecondaryUserMapper">
<select id="findAll" resultType="com.jdkcb.mybatisstuday.pojo.User">
select * from sys_user2;
</select>
</mapper>
```
็ธๅ
ณๆฅๅฃๆไปถ็ผๅๅฅฝไนๅ๏ผๅฐฑๅฏไปฅ็ผๅๆไปฌ็aopไปฃ็ ไบ:
```java
@Aspect
@Component
public class DataSourceAop {
//ๅจprimaryๆนๆณๅๆง่ก
@Before("execution(* com.jdkcb.mybatisstuday.controller.UserController.primary(..))")
public void setDataSource2test01() {
System.err.println("Primaryไธๅก");
DataSourceType.setDataBaseType(DataSourceType.DataBaseType.Primary);
}
//ๅจsecondaryๆนๆณๅๆง่ก
@Before("execution(* com.jdkcb.mybatisstuday.controller.UserController.secondary(..))")
public void setDataSource2test02() {
System.err.println("Secondaryไธๅก");
DataSourceType.setDataBaseType(DataSourceType.DataBaseType.Secondary);
}
}
```
็ผๅๆไปฌ็ๆต่ฏ UserController: ไปฃ็ ๅฆไธ:
```java
@RestController
public class UserController {
@Autowired
private PrimaryUserMapper primaryUserMapper;
@Autowired
private SecondaryUserMapper secondaryUserMapper;
@RequestMapping("primary")
public Object primary(){
List<User> list = primaryUserMapper.findAll();
return list;
}
@RequestMapping("secondary")
public Object secondary(){
List<User> list = secondaryUserMapper.findAll();
return list;
}
}
```
## 4. ๆต่ฏ:
ๅฏๅจ้กน็ฎ๏ผๅจๆต่งๅจไธญๅๅซ่พๅ
ฅhttp://127.0.0.1:8080/primary ๅhttp://127.0.0.1:8080/primary ๏ผ็ปๆๅฆไธ:
```java
[{"user_id":1,"user_name":"ๅผ ไธ","user_age":25}]
[{"user_id":1,"user_name":"ๆๅ","user_age":30}]
```
## 5.็ญ็ญ
็ญ็ญ๏ผๅงๅงๅง๏ผๆ็ไฝ ่ฟไธ่กๅ๏ผ่ฟไธๅค็ตๆดป๏ผๅ ไธช่ๅ๏ผๅๆ่ฟๆ ท๏ผ่ฟๅฐฑ็ฎ็ตๆดปไบ๏ผ
้ฃ่ฏๅฎไธ่ฝ็๏ผaopไนๆaop็ๅฅฝๅค๏ผๆฏๅฆไธคไธชๅ
ไธ็ไปฃ็ ๅๅซ็จไธคไธชไธๅ็ๆฐๆฎๆบ๏ผๅฐฑๅฏไปฅ็ดๆฅ็จaop่กจ่พพๅผๅฐฑๅฏไปฅๅฎๆไบ๏ผไฝๆฏ๏ผๅฆๆๆณๆฌไพไธญๆนๆณ็บงๅซ็ๆฆๆช๏ผๅฐฑๆพๅพไผ็นไธๅคช็ตๆดปไบ๏ผ่ฟไธช้ๅๅฐฑ้่ฆๆไปฌ็ๆณจ่งฃไธๅบไบใ
## 6.้
ๅๆณจ่งฃๅฎ็ฐ
้ฆๅ
่ชๅฎไนๆไปฌ็ๆณจ่งฃ @DataSource
```java
/**
* ๅๆขๆฐๆฎๆณจ่งฃ ๅฏไปฅ็จไบ็ฑปๆ่
ๆนๆณ็บงๅซ ๆนๆณ็บงๅซไผๅ
็บง > ็ฑป็บงๅซ
*/
@Target({ElementType.METHOD, ElementType.TYPE, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
String value() default "primary"; //่ฏฅๅผๅณkeyๅผ๏ผ้ป่ฎคไฝฟ็จ้ป่ฎคๆฐๆฎๅบ
}
```
้่ฟไฝฟ็จaopๆฆๆช๏ผ่ทๅๆณจ่งฃ็ๅฑๆงvalue็ๅผใๅฆๆvalue็ๅผๅนถๆฒกๆๅจๆไปฌDataBaseType้้ข๏ผๅไฝฟ็จๆไปฌ้ป่ฎค็ๆฐๆฎๆบ๏ผๅฆๆๆ็่ฏ๏ผๅๅๆขไธบ็ธๅบ็ๆฐๆฎๆบใ
```java
@Aspect
@Component
public class DynamicDataSourceAspect {
private static final Logger logger = LoggerFactory.getLogger(DynamicDataSourceAspect.class);
@Before("@annotation(dataSource)")//ๆฆๆชๆไปฌ็ๆณจ่งฃ
public void changeDataSource(JoinPoint point, DataSource dataSource) throws Throwable {
String value = dataSource.value();
if (value.equals("primary")){
DataSourceType.setDataBaseType(DataSourceType.DataBaseType.Primary);
}else if (value.equals("secondary")){
DataSourceType.setDataBaseType(DataSourceType.DataBaseType.Secondary);
}else {
DataSourceType.setDataBaseType(DataSourceType.DataBaseType.Primary);//้ป่ฎคไฝฟ็จไธปๆฐๆฎๅบ
}
}
@After("@annotation(dataSource)") //ๆธ
้คๆฐๆฎๆบ็้
็ฝฎ
public void restoreDataSource(JoinPoint point, DataSource dataSource) {
DataSourceType.clearDataBaseType();
}
}
```
## 7 .ๆต่ฏ:
ไฟฎๆนๆไปฌ็mapper๏ผๆทปๅ ๆไปฌ็่ชๅฎไน็@DataSouseๆณจ่งฃ๏ผๅนถๆณจ่งฃๆๆไปฌDataSourceAop็ฑป้้ข็ๅ
ๅฎนใๅฆไธ:
```java
@Component
@Mapper
public interface PrimaryUserMapper {
@DataSource
List<User> findAll();
}
@Component
@Mapper
public interface SecondaryUserMapper {
@DataSource("secondary")//ๆๅฎๆฐๆฎๆบไธบ:secondary
List<User> findAll();
}
```
ๅฏๅจ้กน็ฎ๏ผๅจๆต่งๅจไธญๅๅซ่พๅ
ฅhttp://127.0.0.1:8080/primary ๅhttp://127.0.0.1:8080/primary ๏ผ็ปๆๅฆไธ:
```java
[{"user_id":1,"user_name":"ๅผ ไธ","user_age":25}]
[{"user_id":1,"user_name":"ๆๅ","user_age":30}]
```
ๅฐๆญค๏ผๅฐฑ็ฎ็ๆญฃ็ๅคงๅๅๆๅฆใ
ๆๅ็ๆๅ๏ผๅคงๅฎถๅฅฝ๏ผๆๆฏ้ฉๆฐ๏ผๅผ๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ(ๅ่
ฐ)ใ
่ฎฐๅพ็นไธช่ตๅ่ตฐๅฆ~
็ญไธไธ๏ผ
> ็ธๅ
ณๆบ็ ๆฌข่ฟๅปๆ็githubไธ่ฝฝ(ๆฌข่ฟstar)๏ผ
>
> <https://github.com/hanshuaikang/Spring-Note>
<file_sep>## Springboot ไนๅๅปบ่ชๅฎไนstarter
## ๅ่จ๏ผ
Springboot็ๅบ็ฐๆๅคง็็ฎๅไบๅผๅไบบๅ็้
็ฝฎ๏ผ่่ฟไนไธญ็ไธๅคงๅฉๅจไพฟๆฏspringboot็starter๏ผstarterๆฏspringboot็ๆ ธๅฟ็ปๆ้จๅ๏ผspringbootๅฎๆนๅๆถไนไธบๅผๅไบบๅๅฐ่ฃ
ไบๅ็งๅๆ ทๆนไพฟๅฅฝ็จ็starterๆจกๅ๏ผไพๅฆ๏ผ
- spring-boot-starter-web//spring MVC็ธๅ
ณ
- spring-boot-starter-aop //ๅ้ข็ผ็จ็ธๅ
ณ
- spring-boot-starter-cache //็ผๅญ็ธๅ
ณ
starter็ๅบ็ฐๆๅคง็ๅธฎๅฉๅผๅ่
ไปฌไป็น็็ๆกๆถ้
็ฝฎไธญ่งฃๆพๅบๆฅ๏ผไป่ๆดไธๆณจไบไธๅกไปฃ็ ๏ผ่springboot่ฝๅ็ไธไป
ไป
ๅ็ไบๆญค๏ผๅฝ้ขๅฏนไธไบ็นๆฎ็ๆ
ๅตๆถ๏ผๆไปฌๅฏไปฅไฝฟ็จๆไปฌ่ชๅฎไน็**springboot starter**ใ
ๅจๅๅปบๆไปฌ่ชๅฎไน็starterไนๅๅข๏ผๆไปฌๅ
็็ๅฎๆนๆฏๆไน่ฏด็๏ผ
- **ๆจกๅ**
ๅจspringbootๅฎๆนๆๆกฃไธญ๏ผ็นๅซๆๅฐ๏ผๆไปฌ้่ฆๅๅปบไธคไธชmodule ๏ผๅ
ถไธญไธไธชๆฏ**autoconfigure module** ไธไธชๆฏ **starter module** ๏ผๅ
ถไธญ starter module ไพ่ต autoconfigure module
ไฝๆฏ๏ผ็ฝไธไป็ถๆๅพๅคblogๅจ่ฏด่ฟๅ็ๆถๅๅ
ถๅฎไผๅ็ฐไปไปฌๅ
ถๅฎๅช็จไบไธไธชmodule๏ผ่ฟๅฝ็ถๅนถๆฒกๆ้๏ผ่ฟ็นๅฎๆนไนๆ่ฏดๆ๏ผ
```text
You may combine the auto-configuration code and the dependency management in a single module if you do not need to separate those two concerns
//ๅฆๆไธ้่ฆๅฐ่ชๅจ้
็ฝฎไปฃ็ ๅไพ่ต้กน็ฎก็ๅ็ฆปๅผๆฅ๏ผๅๅฏไปฅๅฐๅฎไปฌ็ปๅๅฐไธไธชๆจกๅไธญใ
```
- **ๅฝๅ่ง่**
springboot ๅฎๆนๅปบ่ฎฎspringbootๅฎๆนๆจๅบ็starter ไปฅspring-boot-starter-xxx็ๆ ผๅผๆฅๅฝๅ๏ผ็ฌฌไธๆนๅผๅ่
่ชๅฎไน็starterๅไปฅxxxx-spring-boot-starter็่งๅๆฅๅฝๅ๏ผไบๅฎไธ๏ผๅพๅคๅผๅ่
ๅจ่ชๅฎไนstarter็ๆถๅๅพๅพไผๅฟฝ็ฅ่ฟไธชไธ่ฅฟ(ๅ ไธบไธ็ๅฎๆนๆๆกฃๅพ้พ็ฅ้่ฟไปถไบๆ
ใๅๆถไนไธไผ้ ๆๅ
ถไป็ๅๆ๏ผไธป่ฆๆฏๆพๅพไธๅคไธไธ)ใ
## ็็ๅฎๆน็starter
ไบ่งฃไบ่ฟไธค็นไนๅ๏ผ้ฃไนไธ้ข่ฎฉๆไปฌไธๅๅปๆข็ดขspingboot starter็ๅฅฅ็งๅงใ
ๆ็
งspringbootๅฎๆน็ป็ๆ่ทฏ๏ผstarter็ๆ ธๅฟmoduleๅบ่ฏฅๆฏautoconfigure๏ผๆไปฅๆไปฌ็ดๆฅๅป็spring-boot-autoconfigure้้ข็ๅ
ๅฎนใ
ๅฝSpring Bootๅฏๅจๆถ๏ผๅฎไผๅจ็ฑป่ทฏๅพไธญๆฅๆพๅไธบspring.factories็ๆไปถใ่ฏฅๆไปถไฝไบMETA-INF็ฎๅฝไธญใๆๅผspring.factoriesๆไปถ๏ผๆไปถๅ
ๅฎนๅคชๅคไบ๏ผไธบไบ้ฟๅ
ๆๆฐด็ฏๅน
๏ผๆไปฌๅช็ๅ
ถไธญ็ไธ้จๅ๏ผ
```factories
# Auto Configure
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\
org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\
org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\
org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\
org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\
```
ๆไปฌๅฏไปฅๅ็ฐไธไบๆฏ่พ็ผ็็ๅ่ฏ๏ผๆฏๅฆAop๏ผRabbit๏ผCache ๏ผๅฝspringbootๅฏๅจ็ๆถๅ๏ผๅฐไผๅฐ่ฏๅ ่ฝฝ่ฟไบ้
็ฝฎ็ฑป๏ผๅฆๆ่ฏฅ่ทฏๅพไธๅญๅจ่ฏฅ็ฑป็่ฏ๏ผๅๅฐ่ฟ่กๅฎ๏ผๅนถๅๅงๅไธ่ฏฅ้
็ฝฎ็ฑป็ธๅ
ณ็beanใ
็นๅผไธไธช็็๏ผ
```java
@Configuration
@ConditionalOnClass({RabbitTemplate.class, Channel.class})
@EnableConfigurationProperties({RabbitProperties.class})
@Import({RabbitAnnotationDrivenConfiguration.class})
public class RabbitAutoConfiguration {
//...ไปฃ็ ็ฅ..
}
```
ๆไปฌๅ
ๆฅไบ่งฃไธไธ่ฟๅ ไธชๆณจ่งฃ:
**@ConditionalOnClass** :ๆกไปถๆณจ่งฃ๏ผๅฝclasspathไธๅ็ฐ่ฏฅ็ฑป็ๆ
ๅตไธ่ฟ่ก่ชๅจ้
็ฝฎใ
**@EnableConfigurationProperties**๏ผๅค้จๅ้
็ฝฎ
**@Import** ๏ผๅผๅ
ฅๅ
ถไป็้
็ฝฎ็ฑป
ๅฝ็ถ๏ผ่ฟๅนถไธๆฏไธ็ง้็จ็ๅฅ่ทฏ๏ผๆฅ็ๅ
ถไป็้
็ฝฎ็ฑป๏ผๆไปฌไผๅ็ฐๅ
ถๆ ๆณจ็ๆณจ่งฃๅพๅพไนๆฏๆๆๅบๅซ็ใ
## ่ชๅฎไน่ชๅทฑ็starter
้ฆๅ
ๆไปฌๆฐๅปบไธไธชmaven้กน็ฎ๏ผๅผๅ
ฅไปฅไธไพ่ต๏ผ
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-autoconfigure</artifactId>
</dependency>
</dependencies>
<dependencyManagement>
<!-- ๆไปฌๆฏๅบไบSpringboot็ๅบ็จ -->
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-dependencies</artifactId>
<version>2.1.0.RELEASE</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
```
็ถๅๆไปฌๅๅปบไธไธชperson็ฑป๏ผ็จไฝๅๆๆไปฌๆต่ฏ็bean
```java
public class Person {
//ๅฑๆง
private int age;
private String name;
private String gender;
/*ๆญคๅค็็ฅgetter and setter and toStering*/
}
```
็ถๅๆไปฌไนๅๅปบไธไธชPersonConfigPropertiesๆฅๅฎๆๆไปฌๅฑๆง็ๆณจๅ
ฅ
```java
@ConfigurationProperties(prefix = "mystarter.config.student")
public class PersonConfigProperties {
private String name;
private int age;
private String gender;
/*
ๅ
ถไป็้
็ฝฎไฟกๆฏใใใใ
*/
/*ๆญคๅค็็ฅgetter and setter and toStering*/
}
```
ๆๅๅๅปบๆไปฌ็่ชๅจ้
็ฝฎ็ฑปMyStarterAutoConfiguration.java
```java
@Configuration
@EnableConfigurationProperties(PersonConfigProperties.class)
@ConditionalOnClass(Person.class)
public class MyStarterAutoConfiguration {
@Bean
@ConditionalOnProperty(prefix = "mystarter.config", name = "enable", havingValue = "true")
public Person defaultStudent(PersonConfigProperties personConfigProperties) {
Person person = new Person();
person.setAge(personConfigProperties.getAge());
person.setName(personConfigProperties.getName());
person.setGender(personConfigProperties.getGender());
return person;
}
}
```
ๆๆ่ง่ฟๆฏไธๆฏๅๅฅฝไบ๏ผ
**ๆไธ่ฆไฝ ่งๅพ๏ผๆ่ฆๆ่งๅพ**
ๆๅๆไปฌๆ้่ฆ็ไธๆญฅ๏ผ
ๅจresourecsๆไปถ็ฎๅฝไธๅๅปบMETA-INF๏ผๅนถๅๅปบๆไปฌ่ชๅทฑ็spring.factories๏ผๅนถๆๆไปฌ็ MyStarterAutoConfigurationๆทปๅ ่ฟๅป
```text
org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
com.jdkcb.mystarter.config.MyStarterAutoConfiguration
```
ๆๅๆๅ
ๆjarๅ
๏ผๅจๆไปฌๆฐ็้กน็ฎ้้ขๆต่ฏ๏ผ
## ๆต่ฏ๏ผ
ๅผๅ
ฅๆไปฌ็starter๏ผๅฝ็ถไนๅฏไปฅๅจๆฌๅฐ็ดๆฅๅผๅ
ฅๆไปฌ็my-spring-boot-starter้กน็ฎ
```xml
<dependency>
<groupId>com.jdkcb</groupId>
<artifactId>my-spring-boot-starter</artifactId>
<version>0.0.1-SNAPSHOT</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/my-spring-boot-starter-0.0.1-SNAPSHOT.jar</systemPath>
</dependency>
```
ๅจapplication.properties้
็ฝฎๆไปถไธญๆทปๅ ๆไปฌ็ธๅบ็้
็ฝฎ
```properties
mystarter.config.enable=true
mystarter.config.person.name=ๅฐๆ
mystarter.config.person.age=5
mystarter.config.person.gender=็ท
```
ๆฐๅปบไธไธชๆต่ฏ็Controller๏ผ
```java
@RestController
public class TestController {
@Autowired
private Person person;
@RequestMapping("/getPerson")
private Person getStudent() {
return person;
}
}
```
ๅฏๅจ้กน็ฎ๏ผๅจๆต่งๅจๅฐๅๆ ่พๅ
ฅ http://127.0.0.1:8080/getPerson ,็ปๆๅฆไธ
```json
{"age":5,"name":"ๅฐๆ","gender":"็ท"}
```
ๅคงๅๅๆ~
ๆๅ็ๆๅ๏ผๅคงๅฎถๅฅฝ๏ผๆๆฏ้ฉๆฐ๏ผๅผ๏ผๅ
ณๆณจๆ๏ผๆไฝ ๅฅฝๆๅญๅ(ๅ่
ฐ)ใ
่ฎฐๅพ็นไธช่ตๅ่ตฐๅฆ~<file_sep>package com.jdkcb.demo.config;
import com.jdkcb.demo.exception.CommonResult;
import com.jdkcb.demo.exception.MyException;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@Configuration
public class ExceptionConfig {
@RestControllerAdvice("com.jdkcb.demo.api")
static class UnifiedExceptionHandler{
@ExceptionHandler(MyException.class)
public CommonResult<Void> handleBusinessException(MyException be){
return CommonResult.errorResult(be.getErrorCode(), be.getErrorMsg());
}
}
}
<file_sep># ้ขๅๅ็ซฏ็Dockerๅ็บงๅ
ฅ้จๆ็จ๏ผDockerFile ๅฝไปค่ฏฆ่งฃ
ๅจไธไธ็ฏๆ็ซ [้ขๅๅ็ซฏ็Dockerๅ็บงๅ
ฅ้จๆ็จ๏ผๅฎๆ็ฏ](https://juejin.im/post/5dabb85ff265da5b6e0a48e7)ๆๅๆไปฌๆๆๅฐ็จDockerFileๆฅๆๅปบๅๅฎๅถๅฑไบๆไปฌ่ชๅทฑ็้ๅ๏ผๅ ไธบๆถ้ดๅ็ฏๅน
้ฎ้ข๏ผไธไธ็ฏๆ็ซ ๅฏนDockerFileๅชๅไบไธไธช็ฎๅ็ไป็ปๅไฝฟ็จ๏ผๅนถๆฒกๆๅฏนDockerFileๅ
ทไฝ็ๆไปค่ฟ่ก่ฏฆ็ป็ไป็ปๅ่งฃ้๏ผๆฌ็ฏ๏ผไฝไธบไธไธ็ฏๅฎๆ็ฏ็้ขๅค่กฅๅ
็ฏ๏ผๆไปฌๅฐไปDockerFileๅบ็ก็ๅฝไปคๅ
ฅๆ๏ผไธๆญฅไธๆญฅ็ๅปๆๅปบไธไธชๅฑไบๆไปฌ่ชๅทฑ็้ๅๅบๆฅใ
## DockerFileไป็ป:
Dockerfileๆฏ็ฑไธ็ณปๅๅฝไปคๅๅๆฐๆๆ็่ๆฌ๏ผไธไธชDockerfile้้ขๅ
ๅซไบๆๅปบๆดไธชimage็ๅฎๆดๅฝไปคใDocker้่ฟdocker buildๆง่กDockerfileไธญ็ไธ็ณปๅๅฝไปค่ชๅจๆๅปบimageใ
## ๅฎไพ๏ผ
่ฟ้ๆไปฌไป็ถ้ๆฉๆไปฌไธไธ็ฏไฝฟ็จ็ๅจcentosๅบ็กไธๅฎๅถๆไปฌ่ชๅทฑ็้ๅไธบๆฌ็ซ ็ไปฃ็ ๅฎไพ๏ผไปฃ็ ๅฆไธ:
```shell
FROM centos //็ปงๆฟ่ณcentos
ENV mypath /tmp //่ฎพ็ฝฎ็ฏๅขๅ้
WORKDIR $mypath //ๆๅฎๅทฅไฝ็ฎๅฝ
RUN yum -y install vim //ๆง่กyumๅฝไปคๅฎ่ฃ
vim
RUN yum -y install net-tools //ๆง่กyumๅฝไปคๅฎ่ฃ
net-tools
EXPOSE 80 //ๅฏนๅค้ป่ฎคๆด้ฒ็็ซฏๅฃๆฏ80
CMD /bin/bash //CMD ๅฎนๅจๅฏๅจๅฝไปค๏ผๅจ่ฟ่กๅฎนๅจ็ๆถๅไผ่ชๅจๆง่ก่ฟ่กๅฝไปค๏ผๆฏๅฆๅฝๆไปฌ docker run -it centos ็ๆถๅ๏ผๅฐฑไผ็ดๆฅ่ฟๅ
ฅbash
```
ไนๅๅ้่ฟdocker build ๅฝไปค็ผ่ฏ่ฏฅDockerFileไพฟๅฏไปฅๅพๅฐไธไธชๅฑไบ่ชๅทฑ็้ๅไบใ
```shell
็ถๅ็ผ่ฏ่ฏฅ้ๅ
docker build -f ./DockerFile -t mycentos:1.3.
-t ๆฐ้ๅๅๅญ:็ๆฌ
-f ๆไปถ -d ๆไปถๅคน
```
่ฟ่ก่ฏฅ้ๅไผๅ็ฐvimๅnet-toolsๅจๆไปฌๆฐ็ๅฎนๅจไธญๅทฒ็ปๅฏไปฅๆญฃๅธธไฝฟ็จไบใ
ๆฅไธๆฅๅข๏ผๆไปฌๅฐไปFROMๅฝไปคๅผๅง้่กไป็ป๏ผๆ็ปๅฎๆๅฏนDockerFileๅธธ็จๅฝไปค็ไบ่งฃๅๆๆกใ
## ๅธธ็จๅฝไปค๏ผ
### FROMๅฝไปค:
ๆข็ถๆไปฌๆฏๅจๅๆ็centos้ๅ็ๅบ็กไธๅๅฎๅถ๏ผ้ฃไนๆไปฌ็ๆฐ้ๅไนไธๅฎๆฏ้่ฆไปฅcentos่ฟไธช้ๅไธบๅบ็ก็๏ผ่FROMๅฝไปคๅไปฃ่กจไบ่ฟไธชๆๆ๏ผๅจDockerFileไธญ๏ผๅบ็ก้ๅๆฏๅฟ
้กปๆๅฎ็๏ผFROMๆไปค็ไฝ็จๅฐฑๆฏๆๅฎๅบ็ก้ๅ๏ผๅ ๆญคไธไธชDockerFileไธญ,FROMๆฏๅฟ
ๅค็ๆไปค๏ผ่ไธๅฐฑๅjava๏ผpython็importๅ
ณ้ฎๅญไธๆ ท๏ผๅจDockerFileไธญ๏ผ**FROMๆไปคๅฟ
้กปๆพๅจ็ฌฌไธๆกๆไปค็ไฝ็ฝฎ**
ๅฝ็ถ๏ผ่ฟไธชๆถๅๅฏ่ฝๆๆๅไผ้ฎไบ๏ผๆ่ฆๆฏไธๆณๅจๅ
ถไป็้ๅไธๅฎๅถ้ๅๆไนๅๅข๏ผๆฒก้ฎ้ขๅ๏ผDocker ๆไพไบscratch ่ฟไธช่ๆ้ๅ๏ผๅฆๆไฝ ้ๆฉ FROM scratch ็่ฏ๏ผๅๆๅณ็ไฝ ไธไปฅไปปไฝ้ๅไธบๅบ็ก๏ผๆฅไธๆฅๆๅ็ๆไปคๅฐไฝไธบ้ๅ็็ฌฌไธๅฑๅผๅงๅญๅจ๏ผๅฝ็ถ๏ผๅจๆไบๆ
ๅตไธ๏ผๆฏๅฆlinuxไธ้ๆ็ผ่ฏ็็จๅบ๏ผ่ฟ่ก็ๆถๅไธ้่ฆๆไฝ็ณป็ปๆไพ่ฟ่กๆถ็ๆฏๆ๏ผ่ฟไธชๆถๅFROM scratch ๆฏๆฒกๆ้ฎ้ข็๏ผๅ่ไผๅคงๅน
้ไฝๆไปฌ็้ๅไฝ็งฏใ
### ENVๆไปค
ๅ่ฝ๏ผ**่ฎพ็ฝฎ็ฏๅขๅ้**
ๅๆ ท็๏ผDockerFileไนๆไพไบไธค็งๆ ผๅผ๏ผ
- ENV key value
- ENV key1=value1 key2=value2
่ฟไธชๆไปคๅพ็ฎๅ๏ผๅฐฑๆฏ่ฎพ็ฝฎ็ฏๅขๅ้่ๅทฒ๏ผๆ ่ฎบๆฏๅ้ข็ๅ
ถๅฎๆไปค๏ผๅฆ RUN๏ผ ่ฟๆฏ่ฟ่กๆถ็ๅบ็จ๏ผ้ฝๅฏไปฅ็ดๆฅไฝฟ็จ่ฟ้ๅฎไน็็ฏๅขๅ้ใ
ๅฏไปฅ็ๅฐๆไปฌ็คบไพไธญไฝฟ็จENV่ฎพ็ฝฎmypathๅ้ไนๅ๏ผๅจไธไธ่กWORKDIRๅไฝฟ็จๅฐไบmypath่ฟไธชๅ้
```shell
ENV mypath /tmp //่ฎพ็ฝฎ็ฏๅขๅ้
WORKDIR $mypath //ๆๅฎๅทฅไฝ็ฎๅฝ
```
### WORKDIR ๆไปค๏ผ
ๅ่ฝ๏ผ**ๆๅฎๅทฅไฝ็ฎๅฝ**
ๆ ผๅผไธบ๏ผWORKDIR ๅทฅไฝ็ฎๅฝ่ทฏๅพ๏ผๅฆๆ่ฟไธช็ฎๅฝไธๅญๅจ็่ฏ๏ผWORKDIRๅไผๅธฎๅฉๆไปฌๅๅปบ่ฟไธช็ฎๅฝใ
่ฎพ็ฝฎ่ฟๅทฅไฝ็ฎๅฝไนๅ๏ผๅฝๆไปฌๅฏๅจๅฎนๅจ๏ผไผ็ดๆฅ่ฟๅ
ฅ่ฏฅๅทฅไฝ็ฎๅฝ
```shell
[root@8081304919c9 tmp]#
```
### RUNๅฝไปค:
**RUN ๆไปคๆฏ็จๆฅๆง่กๅฝไปค่กๅฝไปค็**ใ็ฑไบๅฝไปค่ก็ๅผบๅคง่ฝๅ๏ผRUN ๆไปคไนๆฏๅจๅฎๅถ้ๅๆถๆฏ่พไธบๅธธ็จ็ๆไปคไนไธใ
RUNๅฝไปค็ๆ ผๅผไธๅ
ฑๆไธค็ง๏ผๅๅซๆฏ:
- Shell ๆ ผๅผ
RUN ๅฝไปค๏ผๅฐฑๅ็ดๆฅๅจๅฝไปค่กไธญ่พๅ
ฅๅฝไปคไธๆ ท๏ผๆฏๅฆRUN yum -y install vimๅฐฑๆฏไฝฟ็จ็่ฟ็งๆ ผๅผ
- exec ๆ ผๅผ
RUN["ๅฏๆง่กๆไปถ","ๅๆฐ1","ๅๆฐ2"]๏ผๆ่งๅฐฑๅ่ฐ็จๅฝๆฐไธๆ ท
ๅฐฑๅๆไปฌๅจไธไธ็ฏๆ็ซ ไธญ่ฏด่ฟ็้ฃๆ ท๏ผDockerFileไธญๆฏไธๆกๆไปค้ฝไผๅปบ็ซไธๅฑ๏ผๆฏๅฆๆไปฌไธ้ขๆง่ก่ฟไธ้ข่ฟๆกๅฝไปค
```shell
RUN yum -y install vim
```
ๆง่ก็ปๆไนๅ๏ผๅ่ฐ็จcommitๆไบค่ฟไธๅฑ็ไฟฎๆน๏ผไฝฟไนๆๆไธไธชๆฐ็้ๅ๏ผๆไนๆ ท๏ผๆฏไธๆฏ่ฑ็ถๅผๆไบๅขใ
ๅนถๆฒกๆ
้ฃๅฅฝๅง
ๅๆ ท็๏ผDockerfile ๆฏๆ Shell ็ฑป็่กๅฐพๆทปๅ \ ็ๅฝไปคๆข่กๆนๅผ๏ผไปฅ ๅ่ก้ฆ # ่ฟ่กๆณจ้็ๆ ผๅผใ่ฏๅฅฝ็ๆ ผๅผ๏ผๆฏๅฆๆข่กใ็ผฉ่ฟใๆณจ้็ญ๏ผไผ่ฎฉ็ปดๆคใๆ้ๆดไธบๅฎนๆ๏ผ่ฟๆฏไธไธชๆฏ่พๅฅฝ็ไน ๆฏใ
> ๆ็คบ๏ผ
>
> ๅฆๆไฝฟ็จaptๆนๅผๅฎ่ฃ
็่ฏ๏ผๆๅไธ่ฆๅฟ่ฎฐๆธ
็ๆ้ขๅคไบง็็apt็ผๅญๆไปถ๏ผๅฆๆไธๆธ
็็่ฏไผ่ฎฉๆไปฌ็้ๅๆพๅพ้ๅธธ่่ฟใๅ ไธบDockerFile็ๆไธๅฑๆฐ็้ๅ็ๆถๅ๏ผๅนถไธไผๅ ้คไธไธๅฑ้ๅๆๆฎ็็ๆไปถใ
### EXPOSEๆไปค๏ผ
ๅ่ฝ๏ผ**ๅฃฐๆ็ซฏๅฃ**
ๆ ผๅผ๏ผ EXPOSE ็ซฏๅฃ1 ็ซฏๅฃ2
EXPOSE ๆไปคๆฏๅฃฐๆ่ฟ่กๆถๅฎนๅจๆไพๆๅก็ซฏๅฃ๏ผ่ฟๅฝ็ถๅชๆฏไธไธชๅฃฐๆ๏ผๅจ่ฟ่กๆถๅนถไธไผๅ ไธบ่ฟไธชๅฃฐๆๅบ็จๅฐฑไผๅผๅฏ่ฟไธช็ซฏๅฃ็ๆๅกใ่ฟๆ ทๅฃฐๆไธป่ฆๆฏไธบไบๆนไพฟๅๆๆไปฌ้
็ฝฎ็ซฏๅฃๆ ๅฐใ
### CMDๆไปค๏ผ
ไนๅไป็ปๅฎนๅจ็ๆถๅๆพ็ป่ฏด่ฟ๏ผDocker ไธๆฏ่ๆๆบ๏ผๅฎนๅจๅฐฑๆฏ่ฟ็จใๆข็ถๆฏ่ฟ็จ๏ผ้ฃไนๅจๅฏๅจๅฎนๅจ็ๆถๅ๏ผ้่ฆๆๅฎๆ่ฟ่ก็็จๅบๅๅๆฐใCMD ๆไปคๅฐฑๆฏ็จไบๆๅฎ้ป่ฎค็ๅฎนๅจไธป่ฟ็จ็ๅฏๅจๅฝไปค็ใ
ๅๆ ท็๏ผDockerFileไนไธบๆไปฌๆไพไบไธค็งๆ ผๅผๆฅไฝฟ็จCMDๅฝไปค:
- shell ๆ ผๅผ๏ผCMD ๅฝไปค
- exec ๆ ผๅผ๏ผCMD ["ๅฏๆง่กๆไปถ", "ๅๆฐ 1", "ๅๆฐ 2"...]
็คบไพไธญ๏ผๆไปฌไฝฟ็จ็ๆฏ็ฌฌไธ็ง๏ผ
```shell
CMD /bin/bash
```
่ฟๆกๆไปคๅธฆๆฅ็ๆๆๅฐฑๆฏ๏ผ**ๅฝๆไปฌ้่ฟrun -it ๅฏๅจๅฝไปค็ๆถๅ๏ผๅฎนๅจไผ่ชๅจๆง่ก/bin/bash๏ผcentos้ป่ฎคไนๆฏCMD /bin/bash๏ผๆไปฅๅฝๆไปฌ่ฟ่กcentos้ๅ็ๆถๅ๏ผไผ่ชๅจ่ฟๅ
ฅbash็ฏๅข้้ขใ**
ๅฝ็ถ๏ผๆไปฌไนๅฏไปฅ้่ฟ่ฟ่กๆถๆๅฎๅฝไปค็ๆนๅผๆฅไฝๆข้ป่ฎค็ๅฝไปค๏ผๆฏๅฆ:
```shell
docker run -it centos cat /etc/os-release
```
่ฟๆ ทๅฝๆไปฌ่ฟ่ก้ๅ็ๆถๅ๏ผcat /etc/os-releaseๅฐฑไผๆฟไปฃ้ป่ฎค็CMD /bin/bash ่พๅบ็ณป็ป็็ๆฌไฟกๆฏไบใ
ๅฆๆไฝฟ็จ shell ๆ ผๅผ็่ฏ๏ผ ๅฎ้
็ๅฝไปคไผ่ขซๅ
่ฃ
ไธบ sh -c ็ๅๆฐ็ๅฝขๅผ่ฟ่กๆง่กใ
ๆฏๅฆ๏ผ
```shell
CMD echo $HOME
```
ๅจๅฎ้
ๆง่กไธญ๏ผไผๅฐๅ
ถๅๆดไธบ
```shell
CMD [ "sh", "-c", "echo $HOME" ]
```
ๅฝ็ถ่ฟๆๅพๅคๅๅญฆ่
็นๅซๅฎนๆ็ฏ็้ฎ้ข๏ผๅฐฑๆฏๅปๅฏๅจๅๅฐๆๅก๏ผๆฏๅฆ:
```shell
CMD service nginx start
```
่ฟๆ ทๅญๅป็จ๏ผไผๅ็ฐๅฎนๅจ่ฟ่กไบไธไผๅฐฑ่ชๅจ้ๅบไบใ
ๆไปฅ๏ผ๏ผ๏ผ๏ผ๏ผ๏ผ
ๆไปฌไนๅไธๆญขไธๆฌก็ๆ้่ฟ๏ผ**ๅฎนๅจไธๆฏ่ๆๆบ๏ผๅฎนๅจๅฐฑๆฏ่ฟ็จ**๏ผๅฎนๅจๅ
็ๅบ็จ้ฝๅบ่ฏฅไปฅๅๅฐ่ฟ่ก๏ผ่ไธๆฏๅ่ๆๆบ๏ผ็ฉ็ๆบ้ฃๆ ทๅป่ฟ่กๅๅฐๆๅก๏ผๅฎนๅจๅฐฑๆฏไธบไบไธป่ฟ็จ่ๅญๅจ็๏ผไธป่ฟ็จ้ๅบ๏ผๅฎนๅจๅฐฑๅคฑๅปไบๅญๅจ็ๆไน๏ผไป่้ๅบ๏ผๅ
ถๅฎ่พ
ๅฉ่ฟ็จไธๆฏๅฎ้่ฆๅ
ณๅฟ็ไธ่ฅฟใ
ๆไน็่งฃๅข๏ผๆณๆณๅถๅๅง๏ผๅฎนๅจๆฏๅฅณไธป่ง๏ผไธป่ฟ็จๆฏ็ทไธป่ง
ไฝ ่ตฐไบ๏ผๆไนไธๆดปไบ๏ผๆๅฟ่ฃ่บๅคงๅญ๏ผ๏ผๅคงๆฆๅฐฑๆฏ่ฟไนไธชๆๆใ
ๆญฃๅฆๆไปฌๅ้ขๆๆๅบ็๏ผๅฎ้
ไธCMD service nginx start ๆ็ปไผ่ขซ็่งฃไธบ๏ผ
```shell
CMD [ "sh", "-c", "service nginx start"]
```
ๅจ่ฟ้๏ผๆไปฌไธป่ฟ็จๅฎ้
ๅฐฑๆฏsh๏ผๅฝๆไปฌservice nginx startๆง่กๅฎๆฏไนๅ๏ผ้ฃไนsh่ช็ถๅฐฑไผ้ๅบไบ๏ผไธป่ฟ็จ้ๅบ๏ผๅฎนๅจ่ช็ถๅฐฑไผ็ธๅบ็ๅๆญขใไบๅ็ๅๆณๆฏ็ดๆฅๆง่กnginxๅฏๆง่กๆไปถ๏ผๅนถไธๅฃฐๆไปฅๅๅฐ็ๅฝขๅผ่ฟ่ก:
```shell
CMD ["nginx", "-g", "daemon off;"]
```
ๅฐ่ฟ้๏ผๆไปฌ็คบไพไธญๆๆถๅๅฐ็ๅฝไปคๅทฒ็ป่ฎฒๅฎไบ๏ผๅฝ็ถ๏ผ่ฟๅนถไธๅค๏ผDockerไธญไป็ถๆๅพๅคๅฝไปคๆฏๆไปฌไฝฟ็จๆฏ่พ้ข็น็๏ผไธ้ขๆไปฌ็้จๅไฝไธบ่กฅๅ
๏ผ่ฎฒไธไธๅ
ถไปๅธธ็จ็DockerFileๅฝไปคใ
### **COPY** ๅฝไปค:
ๅ่ฝ:**ๅคๅถๆไปถ**
Dockerไพๆงๆไพไบไธค็งๆ ผๅผไพๆไปฌ้ๆฉ:
- COPY [--chown=<user>:<group>] <ๆบ่ทฏๅพ>... <็ฎๆ ่ทฏๅพ>
- COPY [--chown=<user>:<group>] ["<ๆบ่ทฏๅพ 1>",... "<็ฎๆ ่ทฏๅพ>"]
ๅฐ่ฟ้ๅคงๅฎถๅ
ถๅฎไผๅ็ฐ๏ผDockerๆไพ็ไธค็งๆ ผๅผๅ
ถๅฎ้ฝๆฏๅทฎไธๅค็็จๆณ๏ผไธ็ง็ฑปไผผไบๅฝไปค่ก๏ผไธ็งๅ็ฑปไผผไบๅฝๆฐ่ฐ็จใ
็ฌฌไธ็งไพๅฆ(ๅฐpackage.jsonๆท่ดๅฐ/usr/src/app/็ฎๅฝไธ):
```shell
COPY package.json /usr/src/app/
```
ๅ
ถๆฌก๏ผ็ฎๆ ่ทฏๅพ ๅฏไปฅๆฏๅฎนๅจๅ
็็ปๅฏน่ทฏๅพ๏ผไนๅฏไปฅๆฏ็ธๅฏนไบๅทฅไฝ็ฎๅฝ็็ธๅฏน่ทฏๅพ ๏ผๅทฅไฝ็ฎๅฝๅฏไปฅ็จ WORKDIR ๆไปคๆฅๆๅฎ๏ผๅฆๆ้่ฆๆนๅๆไปถๆๅฑ็็จๆทๆ่
็จๆท็ป๏ผๅฏไปฅๅ ไธ--chown ้้กนใ
> ้่ฆๆณจๆ็ๆฏ๏ผไฝฟ็จ COPY ๆ ไปค๏ผๆบๆไปถ็ๅ็งๅ
ๆฐๆฎ้ฝไผไฟ็ใๆฏๅฆ่ฏปใๅใๆง่กๆ้ใๆไปถๅๆดๆถ้ด็ญใ่ฟ ไธช็นๆงๅฏนไบ้ๅๅฎๅถๅพๆ็จใ
### ADDๅฝไปค๏ผ
ADDๅฝไปคๅฏไปฅ็่งฃไธบCOPYๅฝไปค็้ซ็บง็๏ผๆ ผๅผๅ็จๆณไธCOPYๅ ไนไธ่ด๏ผADDๅจCOPY็ๅบ็กไธๅขๅ ไบไธไบๅ่ฝ๏ผๆฏๅฆๆบ่ทฏๅพๅฏไปฅๆฏไธไธชURL้พๆฅ๏ผๅฝไฝ ่ฟไน็จ็ๆถๅ๏ผDockerไผๅฐ่ฏ็ๅ
ๅฐ่ฏฅURLไปฃ่กจ็ๆไปถไธ่ฝฝไธๆฅ๏ผ็ถๅๅคๅถๅฐ็ฎๆ ็ฎๅฝไธๅป๏ผๅ
ถไป็ๅๆฏๅจCOPY็ๅบ็กไธๅขๅ ไบ่งฃๅ็ผฉไน็ฑป็ๆไฝ๏ผ็ ๅญ็ ็ๆ็ผ๏ผ้่ฆไบ่งฃ็ๆๅๅฏไปฅๅปๅฎ็ฝๆฅ็็ธๅ
ณ็ๆๆกฃ๏ผ่ฟ้ๆๅฐฑไธๅปถ็ณไบใ
### VOLUME ๅฎไนๅฟๅๅท:
ๅจไธไธ็ฏไธญ๏ผๆไปฌๆ่ฎฒๅฎนๅจๅท่ฟไธชๆฆๅฟต๏ผไธบไบ้ฒๆญข่ฟ่กๆถ็จๆทๅฟ่ฎฐ ๅฐๅจๆๆไปถๆไฟๅญ็ฎๅฝๆ่ฝฝไธบๅท๏ผๅจ Dockerfile ไธญ๏ผๆไปฌๅฏไปฅไบๅ
ๆๅฎๆไบ ็ฎๅฝๆ่ฝฝไธบๅฟๅๅท๏ผ่ฟๆ ทๅจ่ฟ่กๆถๅฆๆ็จๆทไธๆๅฎๆ่ฝฝ๏ผๅ
ถๅบ็จไนๅฏไปฅๆญฃๅธธ่ฟ ่ก๏ผไธไผๅๅฎนๅจๅญๅจๅฑๅๅ
ฅๅคง้ๆฐๆฎใ
ไพๅฆ:
```shell
VOLUME /data
```
่ฟ่กๆถ้่ฟ-vๅๆฐๅณๅฏไปฅ่ฆ็้ป่ฎค็ๅฟๅๅท่ฎพ็ฝฎใ
### USER ๅฝไปค:
ๅ่ฝ:**ๆๅฎๅฝๅ็จๆท**
ๆ ผๅผ:**USER ็จๆทๅ:็จๆท็ป**
USER ๆไปคๅ WORKDIR ็ธไผผ๏ผ้ฝๆฏๆนๅ็ฏๅข็ถๆๅนถๅฝฑๅไปฅๅ็ๅฑใWORKDIR ๆฏๆนๅๅทฅไฝ็ฎๅฝ๏ผUSER ๅๆฏๆนๅไนๅๅฑ็ๆง่ก RUN, CMD ไปฅๅ ENTRYPOINT ่ฟ็ฑปๅฝไปค็่บซไปฝใๅฝ็ถ๏ผๅ WORKDIR ไธๆ ท๏ผUSER ๅชๆฏๅธฎๅฉไฝ ๅๆขๅฐๆๅฎ็จๆท ่ๅทฒ๏ผ่ฟไธช็จๆทๅฟ
้กปๆฏไบๅ
ๅปบ็ซๅฅฝ็๏ผๅฆๅๆ ๆณๅๆขใ
ๅฝ็ถ่ฟไธชๅคงๅๆๆฏ๏ผไฝ ็User็จๆทๆฏไบๅ
ๅญๅจๅฅฝ็ใ
## ๅฎ็ปๆ่ฑ๏ผ
ไธ็ฅไธ่ง้ด๏ผDocker็ณปๅๅ็บงๅ
ฅ้จๆ็จๅทฒ็ปๅๅฐไบ็ฌฌๅ็ฏ๏ผ็ฏๅน
ไนๅฐไบไธไธๅคๅญ๏ผๅไธ็ฏๆ็ซ ๅ ่ตทๆฅๅจๆ้ไธๆ
ขๆ
ขๆไบๅคงๆฆ1500ๅทฆๅณ็้
่ฏป้๏ผๆ็ฅ้่ฟ็นๅฏนไบๅพๅคๆ้ๅคงไฝฌๆฅ่ฏดๅชๆฏๅพฎไธ่ถณ้็ไธ็น๏ผไฝๅฏนไบ็ฐ้ถๆฎต็ๆๆฅ่ฏดๅทฒ็ป้ๅธธๆปก่ถณไบ๏ผไปๆฅๆฒกๆๆณๅฐ่ฟๆไธๅคฉ่ชๅทฑไนๅฏไปฅ้่ฟๅไบซๅปๅธฎๅฉๅฐๅซไบบ๏ผๆญฃๅฆๆไนๅ้่ฟๅซไบบ็ๆๆฏๅๅฎขๅญฆไน ้ฃๆ ทใ
่ฟไธช็ณปๅๅฎ็ปไบๅ๏ผๆๆณๅ็บง็ฏๅบ่ฏฅๆฏๅฎ็ปไบ๏ผไฝๆฏNginx็ๅ็บงๅ
ฅ้จๆ็จ๏ผๅณๅฐๅฐๆฅ็Mysql๏ผNetty็ญ็ญๅนถๆฒกๆ๏ผ็ฑไบ็ฎๅๅฐๆชๆฏไธ๏ผ่ฟๆฒกๆๆฅๅ่ฟๅทฅไฝ็ๆฏๆ๏ผๆไปฅๅช่ฝๅฐฝ่ชๅทฑ็่ฝๅๅปๅไธไบๅบ็ก็ๅ
ฅ้จๆ็จ๏ผๆไปฅๅฎ็ปไบๅ๏ผๅนถๆฒกๆ๏ผๆๆฏไน่ทฏๆฐธๆ ๆญขๅข๏ผๅช่ฆๆไปฌไธ็ดๅจๅๆๅญฆไน ๏ผๆๆณ๏ผๆไปฌๅฏไปฅไธ็ด็ปง็ปญไธๅปใ
ๆ่ฐขๆ้๏ผๅคงๅฎถๅฅฝ๏ผๆๆฏ้ฉๆฐ๏ผๆไปฌไธๆๆ็ซ ๅ่ง๏ผ
ๆๅ๏ผ็ธๅ
ณ็ฌ่ฎฐๅทฒ็ปๅๆญฅๅผๆบ่ณGithub(**ๆฌข่ฟstar**)๏ผ
https://github.com/hanshuaikang/HanShu-Note
ไธๅฎ่ฆ่ฎฐๅพ็ปไธชstarๅฆใ
|
25317f7cc797271aee90f278cc3ca012e30f09f0
|
[
"Markdown",
"Java",
"INI"
] | 24 |
Markdown
|
zhangmengme/HanShu-Note
|
df400bd7de6073f4e6a611a4b58cb5af032c1812
|
24fa40b048736117886ce71c78d0b337493f48e1
|
refs/heads/master
|
<repo_name>coolalien/Running-Total<file_sep>/src/uk/co/coolalien/RunningTotal/MainFragment.java
package uk.co.coolalien.RunningTotal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Locale;
import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
public class MainFragment extends Fragment{
private EditText priceEntry;
private EditText itemEntry;
private EditText totalDisplay;
private EditText budgetDisplay;
private TextView budgetLine1;
private TextView budgetLine2;
private TextView budgetLine3;
private ListView addedPrices;
private MyAdapter aa;
//holds all the countries which use Euros
private String[] euroCountries = {"AD", "AT", "BE", "CY", "EE", "FI", "FR", "DE", "GR", "IE", "IT", "LU", "MT", "MC", "ME", "NL", "PT", "SM", "SK", "SI", "ES", "VA"};
//holds all the countries which use dollars
private String[] dollarCountries = {"US", "CA"};
private ArrayList<String> inputs = new ArrayList<String>();
private double total = 0.00;
private DecimalFormat decimal = new DecimalFormat("0.00");
private String country = Locale.getDefault().getCountry();
private String currencyType = "";
//holds the users budget amount
private Double budget;
private boolean overBudget = false;
private Activity activity;
private View view;
private boolean setBudgetCall;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.fragment_main, container, false);
setBudgetCall = false;
if(savedInstanceState != null){
this.total = savedInstanceState.getDouble("Total");
if(savedInstanceState.containsKey("Budget")){
this.budget = savedInstanceState.getDouble("Budget");
}else{
this.budget = null;
}
this.inputs = savedInstanceState.getStringArrayList("Values");
}else{
setBudgetCall = true;
}
setHasOptionsMenu(true);
setUp();
return view;
}
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
inflater.inflate(R.menu.main_menu, menu);
super.onCreateOptionsMenu(menu, inflater);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.resetMenu:
reset();
return true;
case R.id.quitMenu:
System.exit(0);
return true;
case R.id.helpMenu:
//need to create help screen
return true;
case R.id.optionsMenu:
//need to create options screen
return true;
case R.id.budgetMenu:
setBudget();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void setUp(){
//creates all the gui elements
priceEntry = (EditText) view.findViewById(R.id.priceEntry);
itemEntry = (EditText) view.findViewById(R.id.itemEntry);
totalDisplay = (EditText) view.findViewById(R.id.total);
budgetDisplay = (EditText) view.findViewById(R.id.budget);
budgetLine1 = (TextView) view.findViewById(R.id.budgetLine1);
budgetLine2 = (TextView) view.findViewById(R.id.budgetLine2);
budgetLine3 = (TextView) view.findViewById(R.id.budgetColon);
Button plusButton = (Button) view.findViewById(R.id.plusbutton);
addedPrices = (ListView) view.findViewById(R.id.addedPricesListed);
//addedPrices.setBackgroundResource(R.drawable.listbackground);
//array is added to the listview
activity = getActivity();
//hope activity isn't null
//need to put checks in
//aa = new ArrayAdapter<String>(activity,R.layout.mylistview, inputs);
aa = new MyAdapter(activity, inputs);
addedPrices.setAdapter(aa);
totalDisplay.setKeyListener(null);
//sets the currency according to the country the user is in from locale if available other blank
if(country.equals("GB")){
currencyType = "ยฃ";
}else if(Arrays.asList(dollarCountries).contains(country)){
currencyType = "$";
}else if(Arrays.asList(euroCountries).contains(country)){
currencyType = "โฌ";
}
if(setBudgetCall){
setBudget();
}
if(budget == null){
budgetDisplay.setVisibility(View.INVISIBLE);
budgetLine1.setVisibility(View.INVISIBLE);
budgetLine2.setVisibility(View.INVISIBLE);
budgetLine3.setVisibility(View.INVISIBLE);
}else{
if(budget < 0){
overBudget = true;
}
budgetColour();
}
budgetDisplay.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
setBudget();
}
});
//sets the inital total to 0
totalDisplay.setText(currencyType + "0.00");
//when the add button is clicked value will be added to total and listview
plusButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
plusButtonClick();
}
});
//removes the clicked on item from the listview and the total
addedPrices.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
removeItem(position);
}
});
}
public void plusButtonClick(){
final Dialog error = new Dialog(activity, R.style.DialogTransparent);
error.requestWindowFeature(Window.FEATURE_NO_TITLE);
error.setContentView(R.layout.custom_error_dialog);
TextView errorText1 = (TextView) error.findViewById(R.id.errorText1);
Button ok = (Button) error.findViewById(R.id.errorButtonOK);
ok.setTextColor(errorText1.getCurrentTextColor());
//once the user clicks ok on the error message it will retry budget entry
ok.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
error.dismiss();
}
});
//checks the user input a number
if ((priceEntry.getText().length() == 0) || (priceEntry.getText().toString() == " ") || (priceEntry.getText().toString() == "")) {
error.show();
}else {
//adds the number to the total
Double result = 0.0;
try{
result = Double.valueOf(priceEntry.getText().toString().replace(',', '.'));
//new Double(priceDisplay.getText().toString().replace(',', '.'));
}catch(NumberFormatException e){
error.show();
return;
}
total = total + result;
//takes the number away from the budget if a budget was entered and updates the display
if(budget != null){
budget = budget - result;
budgetDisplay.setText(currencyType + decimal.format(budget).replace(',', '.'));
if(budget < 0){
final Dialog overBudgetAlert = new Dialog(activity, R.style.DialogTransparent);
//AlertDialog.Builder overBudgetAlert = new AlertDialog.Builder(activity);
overBudgetAlert.requestWindowFeature(Window.FEATURE_NO_TITLE);
overBudgetAlert.setContentView(R.layout.custom_overbudget_dialog);
TextView textBudget = (TextView) overBudgetAlert.findViewById(R.id.overBudgetText1);
Button okBudget = (Button) overBudgetAlert.findViewById(R.id.overBudgetButtonOK);
okBudget.setTextColor(textBudget.getCurrentTextColor());
okBudget.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
overBudgetAlert.dismiss();
}
});
if(!overBudget){
//overBudgetAlert.setTitle("Over Budget").setMessage("You've gone over your budget").setPositiveButton("OK", null);
overBudgetAlert.show();
overBudget = true;
}
budgetColour();
}
}
String item = itemEntry.getText().toString();
if(!item.equals("")){
item = " - " + item;
}
//adds the number to the results arraylist
inputs.add(currencyType + decimal.format(result).replace(',', '.') + item);
//shows the total in correct format with 2 decimal places
totalDisplay.setText(currencyType + decimal.format(total).replace(',', '.'));
priceEntry.setText("");
itemEntry.setText("");
//updates the listview
aa.notifyDataSetChanged();
priceEntry.requestFocus();
}
}
public void removeItem(int position){
final Dialog deleteAlert = new Dialog(activity, R.style.DialogTransparent);
deleteAlert.requestWindowFeature(Window.FEATURE_NO_TITLE);
deleteAlert.setContentView(R.layout.custom_remove_dialog);
final int positionToRemove = position;
Button yes = (Button) deleteAlert.findViewById(R.id.removeButtonYes);
Button no = (Button) deleteAlert.findViewById(R.id.removeButtonNo);
TextView message = (TextView) deleteAlert.findViewById(R.id.removeText1);
message.setText("Are you sure you want to delete " + inputs.get(position));
yes.setTextColor(message.getCurrentTextColor());
no.setTextColor(message.getCurrentTextColor());
yes.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
String toRemove = inputs.get(positionToRemove).substring(1, 4);
//String toRemove = inputs.get(positionToRemove).replace(currencyType, "");
Double valueToRemove = Double.valueOf(toRemove);
total = total - valueToRemove;
if(budget != null){
budget = budget + valueToRemove;
budgetDisplay.setText(currencyType + decimal.format(budget).replace(',', '.'));
budgetColour();
}
inputs.remove(positionToRemove);
aa.notifyDataSetChanged();
totalDisplay.setText(currencyType + decimal.format(total).replace(',', '.'));
deleteAlert.dismiss();
}
});
no.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
deleteAlert.dismiss();
}
});
deleteAlert.show();
}
/*public void removeItem(int position){
//option message to confirm the user wants to delete value
AlertDialog.Builder deleteAlert=new AlertDialog.Builder(activity);
deleteAlert.setTitle("Delete?");
deleteAlert.setMessage("Are you sure you want to delete " + inputs.get(position));
final int positionToRemove = position;
deleteAlert.setNegativeButton("Cancel", null);
deleteAlert.setPositiveButton("Ok", new AlertDialog.OnClickListener() {
//if they click ok then the value clicked on is removed from the arraylist of inputs
//total is updated and the listview refreshed
//value is added back onto the budget if it was intially entered
@Override
public void onClick(DialogInterface dialog, int which) {
String toRemove = inputs.get(positionToRemove).substring(1, 4);
//String toRemove = inputs.get(positionToRemove).replace(currencyType, "");
Double valueToRemove = Double.valueOf(toRemove);
total = total - valueToRemove;
if(budget != null){
budget = budget + valueToRemove;
budgetDisplay.setText(currencyType + decimal.format(budget).replace(',', '.'));
budgetColour();
}
inputs.remove(positionToRemove);
aa.notifyDataSetChanged();
totalDisplay.setText(currencyType + decimal.format(total).replace(',', '.'));
}});
deleteAlert.show();
}*/
public void setBudget(){
final Dialog error = new Dialog(activity, R.style.DialogTransparent);
error.requestWindowFeature(Window.FEATURE_NO_TITLE);
error.setContentView(R.layout.custom_error_dialog);
TextView errorText1 = (TextView) error.findViewById(R.id.errorText1);
Button ok = (Button) error.findViewById(R.id.errorButtonOK);
ok.setTextColor(errorText1.getCurrentTextColor());
//once the user clicks ok on the error message it will retry budget entry
ok.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
setBudget();
}
});
final Dialog alert = new Dialog(activity, R.style.DialogTransparent);
alert.requestWindowFeature(Window.FEATURE_NO_TITLE);
alert.setContentView(R.layout.custom_dialog);
//alert.setTitle("Budget");
TextView dialogTop = (TextView) alert.findViewById(R.id.dialogText1);
//dialogTop.setText("Enter Budget:");
final EditText input = (EditText) alert.findViewById(R.id.dialogEntry);
input.setTextColor(dialogTop.getCurrentTextColor());
//input.setKeyListener(new DigitsKeyListener(false, true));
final Button positive = (Button) alert.findViewById(R.id.dialogButtonOK);
positive.setTextColor(dialogTop.getCurrentTextColor());
final Button negative = (Button) alert.findViewById(R.id.dialogButtonNoBudget);
negative.setTextColor(dialogTop.getCurrentTextColor());
positive.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View arg0) {
Double budgetEntry = 0.0;
try{
budgetEntry = Double.valueOf(input.getText().toString());
}catch(NumberFormatException e){
error.show();
System.out.println(e.toString());
return;
}
budget = budgetEntry - total;
budgetDisplay.setVisibility(View.VISIBLE);
budgetLine1.setVisibility(View.VISIBLE);
budgetLine2.setVisibility(View.VISIBLE);
budgetLine3.setVisibility(View.VISIBLE);
budgetDisplay.setText(currencyType + decimal.format(budget).replace(',', '.'));
budgetDisplay.setTextColor(getResources().getColor(R.color.giantGoldfish));
budgetColour();
alert.dismiss();
}
});
negative.setOnClickListener(new OnClickListener(){
@Override
public void onClick(View v) {
alert.cancel();
}
});
//alerts the user via a toast if they cancel the budget set up
alert.setOnCancelListener(new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
Toast.makeText(activity, "No Budget Entered", Toast.LENGTH_SHORT).show();
budgetDisplay.setText("No Budget");
budgetDisplay.setVisibility(View.INVISIBLE);
budgetLine1.setVisibility(View.INVISIBLE);
budgetLine2.setVisibility(View.INVISIBLE);
budgetLine3.setVisibility(View.INVISIBLE);
}
});
alert.show();
}
/*public void setBudget(){
//Double temp = budget;
//budget entry alert
AlertDialog.Builder alert = new AlertDialog.Builder(activity);
alert.setTitle("Budget").setMessage("Enter Budget:");
//number format exception alert
final AlertDialog.Builder error = new AlertDialog.Builder(activity);
error.setTitle("Error").setMessage("Please enter a value to add");
//once the user clicks ok on the error message it will retry budget entry
error.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
setBudget();
}
});
// Set an EditText view to get user input only allowing digits and decimal point to be entered
final EditText input = new EditText(activity);
input.setBackgroundColor(R.drawable.edit_text);
input.setKeyListener(new DigitsKeyListener(false, true));
alert.setView(input);
//if they click ok then the budget is set
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int whichButton) {
Double budgetEntry = 0.0;
try{
budgetEntry = Double.valueOf(input.getText().toString());
}catch(NumberFormatException e){
error.show();
System.out.println(e.toString());
return;
}
budget = budgetEntry - total;
budgetDisplay.setVisibility(View.VISIBLE);
budgetLine1.setVisibility(View.VISIBLE);
budgetLine2.setVisibility(View.VISIBLE);
budgetLine3.setVisibility(View.VISIBLE);
budgetDisplay.setText(currencyType + decimal.format(budget).replace(',', '.'));
//budgetDisplay.setTextColor(getResources().getColor(R.color.giantGoldfish));
budgetColour();
return;
}
});
//if they click cancel then it cancels
alert.setNegativeButton("No Budget", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
//alerts the user via a toast if they cancel the budget set up
alert.setOnCancelListener(new DialogInterface.OnCancelListener(){
@Override
public void onCancel(DialogInterface dialog) {
Toast.makeText(activity, "No Budget Entered", Toast.LENGTH_SHORT).show();
budgetDisplay.setText("No Budget");
budgetDisplay.setVisibility(View.INVISIBLE);
budgetLine1.setVisibility(View.INVISIBLE);
budgetLine2.setVisibility(View.INVISIBLE);
budgetLine3.setVisibility(View.INVISIBLE);
}
});
alert.show();
}*/
public void reset(){
priceEntry.setText("");
totalDisplay.setText(currencyType + "0.00");
inputs.clear();
if(budget != null){
budget = budget + total;
budgetDisplay.setText(currencyType + decimal.format(budget).replace(',', '.'));
budgetColour();
}
total = 0.00;
aa.notifyDataSetChanged();
priceEntry.requestFocus();
}
//changes the colour of the budgetDisplay text according to whether over the budget
public void budgetColour(){
if(budget == null){
return;
}
if(budget < 0){
budgetDisplay.setTextColor(Color.RED);
}else{
budgetDisplay.setTextColor(priceEntry.getCurrentTextColor());
overBudget = false;
}
}
@Override
public void onSaveInstanceState (Bundle outState){
super.onSaveInstanceState(outState);
outState.putDouble("Total", total);
if(budget != null){
outState.putDouble("Budget", budget);
}
outState.putStringArrayList("Values", inputs);
}
public class MyAdapter extends BaseAdapter{
private List<String> objects; // obviously don't use object, use whatever you really want
private final Context context;
public MyAdapter(Context context, List<String> objects) {
this.context = context;
this.objects = objects;
}
@Override
public int getCount() {
return objects.size();
}
@Override
public Object getItem(int position) {
return objects.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
Object obj = objects.get(position);
//TextView tv = new TextView(context);
TextView tv = (TextView) View.inflate(context, R.layout.mylistview, null);
tv.setText(obj.toString());
//Typeface font=Typeface.createFromAsset(activity.getAssets(), "fonts/JOURNAL.TTF");
//tv.setTypeface(font);
return tv;
}
}
}
|
49d1d34902763a2fca9211a46dd97573c88cad88
|
[
"Java"
] | 1 |
Java
|
coolalien/Running-Total
|
2a2bbef977188772dba71c7418233375c618e9a6
|
e81fbad568c52b508c2d9acb9ed7efbaa9e1c4b8
|
refs/heads/master
|
<repo_name>Qjao02/TP-EngenhariaSoftware<file_sep>/Project/app/src/main/java/com/ufsj/ies/controlfarma/fragment/CadastroClienteFragment.java
package com.ufsj.ies.controlfarma.fragment;
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.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.ValueEventListener;
import com.ufsj.ies.controlfarma.R;
import com.ufsj.ies.controlfarma.config.ConfiguracaoFirebase;
import com.ufsj.ies.controlfarma.model.Cliente;
public class CadastroClienteFragment extends Fragment {
private EditText nome;
private EditText cpf;
private EditText email;
private Button cadastrar;
private DatabaseReference databaseReference;
private ValueEventListener valueEventListener;
public CadastroClienteFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public void onStart() {
super.onStart();
//databaseReference.addValueEventListener(valueEventListener);
}
@Override
public void onStop() {
super.onStop();
//databaseReference.removeEventListener(valueEventListener);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_cadastro_cliente, container, false);
nome = view.findViewById(R.id.nomeUsuarioEditText);
cpf = view.findViewById(R.id.cpfUsuarioEditText);
email = view.findViewById(R.id.emailUsuarioEditText);
cadastrar = view.findViewById(R.id.usuarioButton);
cadastrar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
String nomeStr, cpfStr, emailStr;
nomeStr = nome.getText().toString();
cpfStr = cpf.getText().toString();
emailStr = email.getText().toString();
if(!nomeStr.isEmpty() && !cpfStr.isEmpty() && !emailStr.isEmpty()){
if(cpfStr.length() == 11){
Cliente cliente = new Cliente();
cliente.setNome(nomeStr);
cliente.setCpf(cpfStr);
cliente.setEmail(emailStr);
verificarDadosRepetidos(cpfStr,cliente);
}else{
Toast.makeText(getActivity(),"Erro: CPF invรกlido.",Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(getActivity(),"Erro: Um dos campos estรก vazio.",Toast.LENGTH_SHORT).show();
}
}
});
return view;
}
private void verificarDadosRepetidos(final String emailStr, final Cliente cliente){
databaseReference = ConfiguracaoFirebase.getFirebase().child("clientes");
databaseReference.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
boolean resultado = true;
for(DataSnapshot dados:dataSnapshot.getChildren()){
Cliente c = dados.getValue(Cliente.class);
if(c.getCpf().equals(emailStr)){
Toast.makeText(getActivity(),"Erro: Esse CPF jรก estรก cadastrado.",Toast.LENGTH_SHORT).show();
resultado = false;
break;
}
}
if(resultado){
databaseReference.child(emailStr).setValue(cliente);
Toast.makeText(getActivity(),"Cliente cadastrado com sucesso.",Toast.LENGTH_SHORT).show();
nome.setText("");
email.setText("");
cpf.setText("");
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
<file_sep>/Project/app/src/main/java/com/ufsj/ies/controlfarma/model/Pedido.java
package com.ufsj.ies.controlfarma.model;
import java.util.ArrayList;
/**
* Created by JV on 16/12/2017.
*/
public class Pedido {
private int numeroPedido;
private float valorTotal;
private String descricao;
private ArrayList<ItemPedido> itemPedidos;
public ArrayList<ItemPedido> getItemPedidos() {
return itemPedidos;
}
public void setItemPedidos(ArrayList<ItemPedido> itemPedidos) {
this.itemPedidos = itemPedidos;
}
public int getNumeroPedido() {
return numeroPedido;
}
public void setNumeroPedido(int numeroPedido) {
this.numeroPedido = numeroPedido;
}
public float getValorTotal() {
return valorTotal;
}
public void setValorTotal(float valorTotal) {
this.valorTotal = valorTotal;
}
public String getDescricao() {
return descricao;
}
public void setDescricao(String descricao) {
this.descricao = descricao;
}
}
<file_sep>/Project/app/src/main/java/com/ufsj/ies/controlfarma/adapter/TabAdapter.java
package com.ufsj.ies.controlfarma.adapter;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import com.ufsj.ies.controlfarma.fragment.CadastroClienteFragment;
import com.ufsj.ies.controlfarma.fragment.CadastroProdutoFragment;
import com.ufsj.ies.controlfarma.fragment.ClientesFragment;
import com.ufsj.ies.controlfarma.fragment.PagamentoFragment;
import com.ufsj.ies.controlfarma.fragment.PedidoFragment;
import com.ufsj.ies.controlfarma.fragment.ProdutosFragment;
import com.ufsj.ies.controlfarma.fragment.RegistroFragment;
/**
* Created by JV on 06/11/17.
*/
public class TabAdapter extends FragmentStatePagerAdapter {
String[] tituloAbas = {"Cadastrar Cliente", "Cadastrar Medicamento","Estoque","Realizar Pedido","Confirmar Pagamento"};
public TabAdapter(FragmentManager fm) {
super(fm);
}
@Override
public Fragment getItem(int position) {
Fragment fragment = null;
switch(position){
case 0:
fragment = new CadastroClienteFragment();
break;
case 1:
fragment = new CadastroProdutoFragment();
break;
case 2:
fragment = new RegistroFragment();
break;
case 3:
fragment = new PedidoFragment();
break;
case 4:
fragment = new PagamentoFragment();
break;
}
return fragment;
}
@Override
public int getCount() {
return tituloAbas.length;
}
@Override
public CharSequence getPageTitle(int position) {
return tituloAbas[position];
}
}
<file_sep>/Project/app/src/main/java/com/ufsj/ies/controlfarma/activity/LoginActivity.java
package com.ufsj.ies.controlfarma.activity;
import android.Manifest;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthInvalidUserException;
import com.google.firebase.database.DatabaseReference;
import com.ufsj.ies.controlfarma.R;
import com.ufsj.ies.controlfarma.config.ConfiguracaoFirebase;
import com.ufsj.ies.controlfarma.helper.Base64Custom;
import com.ufsj.ies.controlfarma.helper.Permissao;
import com.ufsj.ies.controlfarma.helper.Preferencias;
import com.ufsj.ies.controlfarma.model.Funcionario;
public class LoginActivity extends AppCompatActivity {
private EditText email;
private EditText senha;
private Button cadastro;
private Button botao;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private Funcionario funcionario;
private String[] permissoesNecessarias = new String[]{
android.Manifest.permission.INTERNET, Manifest.permission.ACCESS_FINE_LOCATION
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
verificarUsuarioLogado();
Permissao.validarPermissoes(1,this,permissoesNecessarias);
funcionario = new Funcionario();
email = (EditText) findViewById(R.id.emailLoginEditText);
senha = (EditText) findViewById(R.id.senhaLoginEditText);
cadastro = (Button) findViewById(R.id.loginCadastroButton);
botao = (Button) findViewById(R.id.buttonLogin);
botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!email.getText().toString().isEmpty() && !senha.getText().toString().isEmpty()){
funcionario.setEmail(email.getText().toString());
funcionario.setSenha(senha.getText().toString());
try{
validarUsuario();
}catch (Exception e){
Toast.makeText(LoginActivity.this,"Erro ao fazer login.",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}else{
Toast.makeText(LoginActivity.this,"Favor preencher os campos email e senha.",Toast.LENGTH_SHORT).show();
}
}
});
cadastro.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
startActivity(new Intent(LoginActivity.this,CadastroUsuarioActivity.class));
}
});
}
private void abrirMenuPrincipal(){
startActivity(new Intent(LoginActivity.this,MainActivity.class));
finish();
}
private void verificarUsuarioLogado(){
firebaseAuth = ConfiguracaoFirebase.getFirebaseAutenticacao();
if(firebaseAuth.getCurrentUser() != null){
abrirMenuPrincipal();
}
}
public void validarUsuario(){
databaseReference = ConfiguracaoFirebase.getFirebase();
firebaseAuth.signInWithEmailAndPassword(funcionario.getEmail().toString(), funcionario.getSenha().toString()).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
Preferencias preferencias = new Preferencias(LoginActivity.this);
String idUsuario = Base64Custom.codificarBase64(funcionario.getEmail());
preferencias.salvarDados(idUsuario);
abrirMenuPrincipal();
}else{
try {
throw task.getException();
}catch (FirebaseAuthInvalidUserException e){
Toast.makeText(LoginActivity.this, "Erro ao fazer Login: Email nรฃo cadastrado ou inexistente.",Toast.LENGTH_SHORT).show();
}catch (FirebaseAuthInvalidCredentialsException e){
Toast.makeText(LoginActivity.this, "Erro ao fazer Login: Senha incorreta.",Toast.LENGTH_SHORT).show();
}catch (Exception e){
Toast.makeText(LoginActivity.this, "Erro ao fazer Login.",Toast.LENGTH_SHORT).show();
e.printStackTrace();
}
}
}
});
}
}
<file_sep>/Project/app/src/main/java/com/ufsj/ies/controlfarma/activity/CadastroUsuarioActivity.java
package com.ufsj.ies.controlfarma.activity;
import android.content.Intent;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseAuthInvalidCredentialsException;
import com.google.firebase.auth.FirebaseAuthUserCollisionException;
import com.google.firebase.auth.FirebaseAuthWeakPasswordException;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.ufsj.ies.controlfarma.R;
import com.ufsj.ies.controlfarma.config.ConfiguracaoFirebase;
import com.ufsj.ies.controlfarma.helper.Base64Custom;
import com.ufsj.ies.controlfarma.helper.Preferencias;
import com.ufsj.ies.controlfarma.model.Funcionario;
public class CadastroUsuarioActivity extends AppCompatActivity {
private EditText nome;
private EditText email;
private EditText senha;
private EditText sobrenome;
private EditText senha2;
private Button botao;
private Funcionario funcionario;
private ImageView voltar;
private DatabaseReference databaseReference;
private FirebaseAuth firebaseAuth;
private boolean cadastrou;
private Spinner spinner;
private String[] sexos = {"(Escolha seu sexo)","Masculino","Feminino","Outro"};
//Comentario xddd
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cadastro_usuario);
cadastrou=false;
databaseReference = ConfiguracaoFirebase.getFirebase();
nome = (EditText) findViewById(R.id.nomeCadastroEditText);
email = (EditText) findViewById(R.id.emailCadastroEditText);
senha = (EditText) findViewById(R.id.senhaCadastroEditText);
botao = (Button) findViewById(R.id.buttonCadastrar);
sobrenome = (EditText) findViewById(R.id.sobrenomeCadastroEditText);
senha2 = (EditText) findViewById(R.id.reSenhaCadastroEditText);
voltar = (ImageView) findViewById(R.id.setaCadastroImageView);
spinner = (Spinner) findViewById(R.id.cadastroSpinner);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,android.R.layout.simple_spinner_dropdown_item,sexos);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
switch(i){
case 0:break;
case 1:break;
case 2:break;
case 3:break;
}
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});
funcionario = new Funcionario();
botao.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(!nome.getText().toString().isEmpty() && !email.getText().toString().isEmpty() && !senha.getText().toString().isEmpty()
&& !senha2.getText().toString().isEmpty() && !sobrenome.getText().toString().isEmpty() && spinner.getSelectedItemPosition() != 0){
if(senha.getText().toString().equals(senha2.getText().toString())){
funcionario.setNome(nome.getText().toString());
funcionario.setEmail(email.getText().toString());
funcionario.setSenha(senha.getText().toString());
funcionario.setSexo(spinner.getSelectedItem().toString());
funcionario.setSobrenome(sobrenome.getText().toString());
if(!cadastrou) {
cadastrarUsuario();
}
}else{
Toast.makeText(CadastroUsuarioActivity.this,"Erro: Senhas diferentes.",Toast.LENGTH_SHORT).show();
}
}else{
Toast.makeText(CadastroUsuarioActivity.this,"Erro: Existem campos nรฃo preenchidos.",Toast.LENGTH_SHORT).show();
}
}
});
voltar.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
abrirTelaLogin();
}
});
}
private void abrirTelaLogin(){
startActivity(new Intent(CadastroUsuarioActivity.this,LoginActivity.class));
finish();
}
private void cadastrarUsuario(){
firebaseAuth = ConfiguracaoFirebase.getFirebaseAutenticacao();
firebaseAuth.createUserWithEmailAndPassword(funcionario.getEmail(), funcionario.getSenha()).addOnCompleteListener(CadastroUsuarioActivity.this, new OnCompleteListener<AuthResult>() {
@Override
public void onComplete(@NonNull Task<AuthResult> task) {
if(task.isSuccessful()){
FirebaseUser usuarioFirebase = task.getResult().getUser();
String idUsuario = Base64Custom.codificarBase64(funcionario.getEmail());
funcionario.setId(idUsuario);
funcionario.salvarDados();
Preferencias preferencias = new Preferencias(CadastroUsuarioActivity.this);
preferencias.salvarDados(idUsuario);
Toast.makeText(CadastroUsuarioActivity.this,"Usuรกrio cadastrado com sucesso!",Toast.LENGTH_LONG).show();
cadastrou=true;
abrirTelaLogin();
}else{
try {
throw task.getException();
}catch (FirebaseAuthWeakPasswordException e){
Toast.makeText(CadastroUsuarioActivity.this,"Erro ao cadastrar usuรกrio: Senha fraca.",Toast.LENGTH_LONG).show();
}catch (FirebaseAuthInvalidCredentialsException e){
Toast.makeText(CadastroUsuarioActivity.this,"Erro ao cadastrar usuรกrio: Email invรกlido.",Toast.LENGTH_LONG).show();
}catch (FirebaseAuthUserCollisionException e){
Toast.makeText(CadastroUsuarioActivity.this,"Erro ao cadastrar usuรกrio: Esse email jรก estรก cadastrado.",Toast.LENGTH_LONG).show();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(CadastroUsuarioActivity.this,"Erro ao cadastrar usuรกrio.",Toast.LENGTH_LONG).show();
}
}
}
});
}
}
<file_sep>/Project/app/src/main/java/com/ufsj/ies/controlfarma/model/Medicamento.java
package com.ufsj.ies.controlfarma.model;
/**
* Created by JV on 05/12/2017.
*/
public class Medicamento{
private String nome;
private String principioAtivo;
private String especificacoesArmazenamento;
private int numPedidos;
public int getNumPedidos() {
return numPedidos;
}
public void setNumPedidos(int numPedidos) {
this.numPedidos = numPedidos;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getPrincipioAtivo() {
return principioAtivo;
}
public void setPrincipioAtivo(String principioAtivo) {
this.principioAtivo = principioAtivo;
}
public String getEspecificacoesArmazenamento() {
return especificacoesArmazenamento;
}
public void setEspecificacoesArmazenamento(String especificacoesArmazenamento) {
this.especificacoesArmazenamento = especificacoesArmazenamento;
}
}
<file_sep>/Project/app/src/main/java/com/ufsj/ies/controlfarma/model/ItemPedido.java
package com.ufsj.ies.controlfarma.model;
/**
* Created by JV on 16/12/2017.
*/
public class ItemPedido{
private float preco;
private int quantidade;
private Registro registro;
public Registro getRegistro() {
return registro;
}
public void setRegistro(Registro registro) {
this.registro = registro;
}
public float getPreco() {
return preco;
}
public void setPreco(float preco) {
this.preco = preco;
}
public int getQuantidade() {
return quantidade;
}
public void setQuantidade(int quantidade) {
this.quantidade = quantidade;
}
}
|
cc5b10206a7124569bda72f70d03334ba968170a
|
[
"Java"
] | 7 |
Java
|
Qjao02/TP-EngenhariaSoftware
|
a5db20797fd2499574d4edd77d72564c66774022
|
a886f138d157771515b8e1dbefdd9f3888f6ca8d
|
refs/heads/master
|
<file_sep>import window from 'window';
import document from 'document';
function arrayBufferToBase64(buffer) {
let binary = '';
const bytes = [].slice.call(new Uint8Array(buffer));
bytes.forEach((b) => binary += String.fromCharCode(b));
return window.btoa(binary);
}
const getImageByApiToken = (image, src, token) => {
image.setAttribute('src', `${src}&apiToken=${token}`);
};
const getImageByJwtToken = async (image, src, token) => {
const options = {
method: 'GET',
headers: new Headers({ Authorization: `Bearer ${token}` }),
mode: 'cors',
cache: 'default'
};
// src = src.replace('http', 'https');
const response = await fetch(src, options);
const buffer = await response.arrayBuffer();
const base64Flag = 'data:image/jpeg;base64,';
const imageStr = arrayBufferToBase64(buffer);
image.setAttribute('src', base64Flag + imageStr);
};
export default function processImageListener(apiToken) {
document.addEventListener('DOMNodeInserted', (e) => {
if (e.target.tagName && e.target.tagName.toLowerCase() === 'img') {
// e.target is img
const image = e.target;
if (image.getAttribute('type') === 'fugle' && !image.src) {
getImageByJwtToken(image, image.getAttribute('fugle-src'), apiToken);
}
}
if (e.target.hasChildNodes()) {
const images = e.target.querySelectorAll('img[type="fugle"]');
images.forEach((image) => {
if (!image.src) {
getImageByJwtToken(image, image.getAttribute('fugle-src'), apiToken);
}
});
}
});
}<file_sep>import { FUGLE_PICTURE_API_URL } from './config';
import processImageListener from './processImage';
export default class FuglePicture {
init(apiToken) {
if (!apiToken) {
console.warn('[Fugle Picture] Must Provide ApiToken');
return;
}
// Should check apiToken here ?
this.apiToken = apiToken;
processImageListener(apiToken);
}
checkToken() {
if (!this.apiToken) {
console.warn('[Fugle Picture] Must Provide ApiToken');
throw new Error();
}
}
async getUrl(symbolId, cardSpecId) {
try {
this.checkToken();
const apiUrl = `${FUGLE_PICTURE_API_URL}?symbolId=${symbolId}&cardSpecId=${cardSpecId}`;
const options = {
method: 'GET',
headers: new Headers({ Authorization: `Bearer ${this.apiToken}` }),
mode: 'cors',
cache: 'default'
};
const response = await fetch(apiUrl, options);
const result = await response.json();
const { url } = result.data;
return url;
} catch (error) {
return null;
}
}
}
|
ac6450f4ff9ae6e0dd02bb76435e850aaaf45dbf
|
[
"JavaScript"
] | 2 |
JavaScript
|
thstarshine/fugle-picture-sdk
|
07e02ca8b112b7bc860ea21b026efd75c4680328
|
ce6845b16f571367ecf23d6533e60db16dec747c
|
refs/heads/master
|
<file_sep>from flask import Flask, render_template, session, redirect, url_for
from flask_session import Session
from tempfile import mkdtemp
import numpy as np
app = Flask(__name__)
app.config["SESSION_FILE_DIR"] = mkdtemp()
app.config["SESSION_PERMANENT"] = False
app.config["SESSION_TYPE"] = "filesystem"
Session(app)
def myfilter(x):
if x== "X": return 1
if x == "O": return -1
else: return 0
def check_game_state(board_sess):
board_sess_new = []
for item in board_sess:
board_sess_new.append ( list(map(myfilter, item)) )
print(board_sess_new)
board_sess = board_sess_new
board_np =np.array(board_sess)
winner = [False, None]
diag_rows = board_np [ range(0,3) , range(0,3) ] , board_np [ range(0,3) , range(2,-1, -1) ]
for board in [board_np, board_np.T, diag_rows ]:
for row in board:
result = sum(row)
if result in [3,-3]:
winner[0] = True
winner[1] = "X" if result == 3 else "O"
break
return(winner)
@app.route("/")
def index():
if "board" not in session:
session["board"] = [ [0]*3 , [0]*3, [0]*3 ]
session["turn"] = "X"
result = check_game_state(session["board"])
if result[0] == True :
session["board"] = [ [0]*3 , [0]*3, [0]*3 ]
session["turn"] = "X"
return render_template("game.html", game = session["board"], turn = session["turn"], result=result)
@app.route("/play/<int:row>/<int:col>")
def play(row, col):
print(row,col)
if session["turn"] == "X":
session["turn"] = "O"
session["board"][row][col] = "X"
else:
session["turn"] = "X"
session["board"][row][col] = "O"
return redirect(url_for("index"))
@app.route("/reset")
def reset():
session["board"] = [ [0]*3 , [0]*3, [0]*3 ]
session["turn"] = "X"
result = check_game_state(session["board"])
return render_template("game.html", game = session["board"], turn = session["turn"],result=result)
if __name__ =="__main__":
app.run(host="0.0.0.0",port=5003,debug=True)
<file_sep>
flask
numpy
gunicorn
|
ebe2ebd15f619c442bec0e842036575ce7bb1cb8
|
[
"Python",
"Text"
] | 2 |
Python
|
DhilipBinny/_TicTacToe-PYTHON
|
deea32a109ce72044c964ec102b35ef218cb849e
|
eaa165469bab1192c2cf144940ab9f68d37df321
|
refs/heads/master
|
<repo_name>zwjin1210/smkflow<file_sep>/src/smkflow/widget/LabelImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <smk/RenderTarget.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/widget/LabelImpl.hpp>
namespace smkflow {
LabelImpl::LabelImpl(Delegate* delegate, const std::string& text)
: Widget(delegate) {
text_ = smk::Text(delegate->Font(), text);
computed_dimensions_ = text_.ComputeDimensions();
}
// Widget implementation:
glm::vec2 LabelImpl::ComputeDimensions() {
return computed_dimensions_;
}
void LabelImpl::Draw(smk::RenderTarget* target) {
auto position = Position();
position.y += dimensions().y * 0.5f - computed_dimensions_.y * 0.5f;
text_.SetPosition(position);
target->Draw(text_);
}
WidgetFactory Label(const std::string& label) {
return [label](Widget::Delegate* delegate) {
return std::make_unique<LabelImpl>(delegate, label);
};
}
} // namespace smkflow
<file_sep>/include/smkflow/widget/Action.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_ACTION_HPP
#define SMKFLOW_WIDGET_ACTION_HPP
namespace smkflow {
namespace model {
struct Node;
}
class ActionContext {
public:
virtual Board* board() = 0;
virtual glm::vec2 cursor() = 0;
};
using Action = std::function<void(ActionContext*)>;
// Predefined Actions.
Action CreateNode(model::Node);
Action ActionNone();
} /* namespace smkflow */
#endif /* end of include guard: SMKFLOW_WIDGET_ACTION_HPP */
<file_sep>/src/smkflow/NodeImpl.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_NODE_HPP
#define SMKFLOW_NODE_HPP
#include <glm/glm.hpp>
#include <memory>
#include <smk/RenderTarget.hpp>
#include <smk/Text.hpp>
#include <smk/Transformable.hpp>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include <smkflow/SlotImpl.hpp>
#include <vector>
namespace smkflow {
class SlotImpl;
class BoardImpl;
class NodeImpl : public Node, public Widget::Delegate {
public:
NodeImpl(BoardImpl* board, const model::Node& model);
~NodeImpl() override;
static NodeImpl* From(Node* node) { return static_cast<NodeImpl*>(node); }
void Draw(smk::RenderTarget*);
void Step(smk::Input* input, glm::vec2 cursor);
void Layout();
const glm::vec2& GetPosition();
SlotImpl* FindSlot(const glm::vec2& position);
BoardImpl* boardImpl() { return board_; }
void Push(glm::vec2 direction);
glm::vec2 position() { return position_; }
glm::vec2 dimension() { return dimension_; }
JSON Serialize();
bool Deserialize(JSON& in);
// Node:
Board* GetBoard() override;
int Identifier() override { return identifier_; }
void SetPosition(const glm::vec2& position) override;
int InputCount() override;
Slot* InputAt(int i) override;
int OutputCount() override;
Slot* OutputAt(int i) override;
Widget* widget() override;
// WidgetDelegate:
glm::vec2 Position() override { return position_; }
void InvalidateLayout() override;
smk::Font& Font() override;
CursorCapture CaptureCursor() override;
Board* board() override;
private:
BoardImpl* board_;
int identifier_;
std::vector<std::unique_ptr<SlotImpl>> inputs_;
std::vector<std::unique_ptr<SlotImpl>> outputs_;
std::unique_ptr<Widget> widget_;
glm::vec2 position_ = glm::vec2(0, 0);
glm::vec2 dimension_ = glm::vec2(0, 0);
smk::Text title_;
smk::Transformable title_base_;
smk::Transformable base_;
glm::vec4 color_;
float width_;
float height_;
bool layout_invalidated_ = true;
glm::vec2 speed_ = glm::vec2(0.f, 0.f);
glm::vec2 cursor_drag_point;
CursorCapture cursor_captured_;
CursorCapture cursor_captured_for_selection_;
bool Selected();
public:
const decltype(inputs_)& inputs() { return inputs_; }
const decltype(outputs_)& outputs() { return outputs_; }
};
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_NODE_HPP */
<file_sep>/examples/algebra.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <fmt/core.h>
#include <iostream>
#include <smk/Color.hpp>
#include <smk/Window.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include <smkflow/widget/Box.hpp>
#include <smkflow/widget/Input.hpp>
#include <smkflow/widget/Menu.hpp>
#include <smkflow/widget/Slider.hpp>
#include "asset.hpp"
enum Node {
Number,
Add,
Substract,
Multiply,
Divide,
};
auto type_number = glm::vec4(1.f, 0.5f, 0.5f, 1.f);
auto node_color = glm::vec4(0.5f, 0.5f, 0.5f, 1.f);
auto node_color_number = glm::vec4(0.5, 0.25f, 0.25f, 1.f);
auto node_add = smkflow::model::Node{Node::Add,
"Add",
node_color,
{
{"", type_number},
{"", type_number},
},
{
{"out", type_number},
},
smkflow::VBox({
smkflow::Input("0.0"),
smkflow::Input("0.0"),
})};
auto node_substract = smkflow::model::Node{Node::Substract,
"Substract",
node_color,
{
{"", type_number},
{"", type_number},
},
{
{"out", type_number},
},
smkflow::VBox({
smkflow::Input("0.0"),
smkflow::Input("0.0"),
})};
auto node_multiply = smkflow::model::Node{Node::Multiply,
"Multiply",
node_color,
{
{"", type_number},
{"", type_number},
},
{
{"out", type_number},
},
smkflow::VBox({
smkflow::Input("0.0"),
smkflow::Input("0.0"),
})};
auto node_divide = smkflow::model::Node{Node::Divide,
"Divide",
node_color,
{
{"", type_number},
{"", type_number},
},
{
{"", type_number},
},
smkflow::VBox({
smkflow::Input("0.0"),
smkflow::Input("0.0"),
})};
auto node_number = smkflow::model::Node{
Node::Number,
"Number",
node_color_number,
{},
{
{"out", type_number},
},
smkflow::Slider(-20.f, 20.f, 0.f, "{:.2f}"),
};
auto my_board = smkflow::model::Board{
// Node list
{
node_number,
node_add,
node_substract,
node_multiply,
node_divide,
},
// Contextual menu
{
smkflow::MenuEntry("Number", smkflow::CreateNode(node_number)),
smkflow::MenuEntry("Add", smkflow::CreateNode(node_add)),
smkflow::MenuEntry("Substract", smkflow::CreateNode(node_substract)),
smkflow::MenuEntry("Multiply", smkflow::CreateNode(node_multiply)),
smkflow::MenuEntry("Divide", smkflow::CreateNode(node_divide)),
},
asset::arial_ttf,
};
std::map<smkflow::Node*, float> values;
const char* float_format = "{:.2f}";
void UpdateValues(smkflow::Board* board) {
for (int i = 0; i < board->NodeCount(); ++i) {
smkflow::Node* node = board->NodeAt(i);
float value = 0;
if (node->Identifier() == Number) {
auto slider = smkflow::Slider(node->widget());
value = slider->GetValue();
values[node] = value;
continue;
}
auto box = smkflow::Box(node->widget());
auto input_1 = smkflow::Input(box->ChildAt(0));
auto input_2 = smkflow::Input(box->ChildAt(1));
if (auto* a = node->InputAt(0)->OppositeNode())
input_1->SetValue(fmt::format(float_format, values[a]));
if (auto* b = node->InputAt(1)->OppositeNode())
input_2->SetValue(fmt::format(float_format, values[b]));
float a_value = std::atof(input_1->GetValue().c_str());
float b_value = std::atof(input_2->GetValue().c_str());
// clang-format off
switch (node->Identifier()) {
case Number: break;
case Add: value = a_value + b_value; break;
case Substract: value = a_value - b_value; break;
case Multiply: value = a_value * b_value; break;
case Divide: value = b_value ? a_value / b_value : 0; break;
}
// clang-format on
values[node] = value;
node->OutputAt(0)->SetText(fmt::format(float_format, value));
}
}
int main() {
auto window = smk::Window(512, 512, "test");
auto board = smkflow::Board::Create(my_board);
auto nodes = {
node_number, node_add, node_multiply, node_substract, node_divide,
};
// Instanciate some Node based on the model.
int x = -nodes.size() / 2;
for (const auto& node_model : nodes) {
smkflow::Node* node = board->Create(node_model);
node->SetPosition({200 * x, 0});
++x;
}
window.ExecuteMainLoop([&] {
window.Clear(smkflow::color::background);
window.PoolEvents();
UpdateValues(board.get());
board->Step(&window, &window.input());
board->Draw(&window);
window.Display();
});
return EXIT_SUCCESS;
}
<file_sep>/examples/CMakeLists.txt
add_subdirectory(assets)
if(EMSCRIPTEN)
configure_file(
${CMAKE_CURRENT_SOURCE_DIR}/index.html
${CMAKE_CURRENT_BINARY_DIR}/index.html
COPYONLY
)
endif()
function(add_example target input)
set(ns_target smkflow_example_${target})
add_executable(${ns_target} ${input})
target_link_libraries(${ns_target} PRIVATE smkflow::smkflow fmt::fmt asset)
set_target_properties(${ns_target} PROPERTIES CXX_STANDARD 11)
set_target_properties(${ns_target} PROPERTIES OUTPUT_NAME ${target})
# Detect emscripten is used.
if(EMSCRIPTEN)
# Release flags
# Release flags
set_property(TARGET ${ns_target} APPEND_STRING PROPERTY LINK_FLAGS
" -s ALLOW_MEMORY_GROWTH=1"
" -s DEMANGLE_SUPPORT=1"
" -s DISABLE_EXCEPTION_CATCHING=2"
" -s EXPORT_NAME='main' -s MODULARIZE=1"
)
set_property(GLOBAL APPEND_STRING PROPERTY LINK_FLAGS
" -s WASM=1"
" --js-opts 3"
" --llvm-lto 3"
" --llvm-opts 3"
" -O3"
)
# Allow some files to be fetched.
file(GLOB_RECURSE files "./assets/*")
foreach(file ${files})
file(RELATIVE_PATH relative_file ${CMAKE_SOURCE_DIR} "${file}")
set_property(TARGET ${ns_target} APPEND_STRING PROPERTY LINK_FLAGS " --preload-file \"${file}@/${relative_file}\"")
endforeach()
endif()
endfunction(add_example)
add_example(algebra algebra.cpp)
add_example(widget_gallery widget_gallery.cpp)
add_example(minimal minimal.cpp)
add_example(perftest perftest.cpp)
<file_sep>/src/smkflow/widget/MenuImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <algorithm>
#include <smk/Input.hpp>
#include <smk/RenderTarget.hpp>
#include <smk/Shape.hpp>
#include <smk/Text.hpp>
#include <smk/VertexArray.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/widget/BoxImpl.hpp>
#include <smkflow/widget/Menu.hpp>
#include <smkflow/widget/MenuImpl.hpp>
namespace smkflow {
class MenuImpl : public Widget, public Widget::Delegate {
public:
MenuImpl(Widget::Delegate* delegate,
const std::string& text,
std::vector<WidgetFactory> children)
: Widget(delegate) {
text_ = smk::Text(delegate->Font(), text);
computed_dimensions_ = text_.ComputeDimensions();
computed_dimensions_.x += computed_dimensions_.y;
square_ = smk::Shape::Square();
children_ = std::make_unique<BoxImplVertical>(this, children);
triangle_ = smk::Shape::FromVertexArray(smk::VertexArray({
{{-0.5f, -0.5f}, {0.f, 0.0f}},
{{+0.5f, +0.0f}, {1.f, 0.5f}},
{{-0.5f, +0.5f}, {0.f, 1.0f}},
}));
}
// Widget:
glm::vec2 ComputeDimensions() override {
child_dimension_ = children_->ComputeDimensions();
children_->ComputeDimensions();
// if (cursor_capture_) {
// return glm::vec2(computed_dimensions_.x + size::widget_margin + .x,
// std::max(computed_dimensions_.y, child.y));
//}
// else
return computed_dimensions_;
}
void SetPosition(glm::vec2 position) override {
Widget::SetPosition(position);
position.x += dimensions().x + size::widget_margin;
children_->SetPosition(position);
}
void SetDimensions(glm::vec2 dimension) override {
Widget::SetDimensions(dimension);
children_->SetDimensions(child_dimension_);
}
bool Step(smk::Input* input, const glm::vec2& cursor) override {
auto position = Widget::Position();
auto dimension = dimensions();
hover_ = cursor.x > position.x && //
cursor.x < position.x + dimension.x && //
cursor.y > position.y && //
cursor.y < position.y + dimension.y; //
// if (cursor_capture_ && hover_ && input->IsCursorPressed()) {
////cursor_capture_ = false;
// InvalidateLayout();
//}
if (hover_) {
if (cursor_capture_ && input->IsCursorPressed()) {
cursor_capture_.Invalidate();
} else if (!cursor_capture_ &&
(delegate()->IsInsideMenu() || input->IsCursorPressed())) {
cursor_capturable_.Invalidate();
cursor_capture_.Invalidate();
cursor_capture_ = delegate()->CaptureCursor();
Widget::InvalidateLayout();
}
}
if (cursor_capture_) {
bool clicked = false;
clicked |= children_->Step(input, cursor);
clicked |= Widget::Step(input, cursor);
if (!clicked && input->IsCursorPressed())
cursor_capture_.Invalidate();
return clicked;
}
return Widget::Step(input, cursor);
}
void Draw(smk::RenderTarget* target) override {
if (cursor_capture_ || hover_) {
square_.SetPosition(Widget::Position());
square_.SetScale(dimensions());
square_.SetColor(cursor_capture_ ? color::widget_background_focus
: color::widget_background_hover);
target->Draw(square_);
}
text_.SetPosition(Widget::Position());
target->Draw(text_);
if (cursor_capture_) {
DrawBoxBackground(
target, children_->Position() - size::widget_margin * glm::vec2(1.f),
children_->dimensions() + 2.f * size::widget_margin * glm::vec2(1.f));
children_->Draw(target);
}
triangle_.SetScale(dimensions().y * 0.5f);
triangle_.SetPosition(Widget::Position() +
glm::vec2(dimensions().x - 0.5f * dimensions().y,
dimensions().y * 0.5f));
target->Draw(triangle_);
}
glm::vec2 Position() override { return delegate()->Position(); }
void InvalidateLayout() override { return delegate()->InvalidateLayout(); }
smk::Font& Font() override { return delegate()->Font(); }
CursorCapture CaptureCursor() override {
if (!cursor_capture_) {
cursor_capture_ = delegate()->CaptureCursor();
}
if (!cursor_capture_)
return CursorCapture();
cursor_capturable_.Invalidate();
return cursor_capturable_.Capture();
}
bool IsInsideMenu() override { return true; }
Board* board() override { return delegate()->board(); }
private:
std::unique_ptr<smkflow::BoxImplVertical> children_;
smk::Transformable square_;
smk::Transformable triangle_;
glm::vec2 computed_dimensions_;
glm::vec2 child_dimension_;
smk::Text text_;
bool hover_ = false;
CursorCapture cursor_capture_;
CursorCapturable cursor_capturable_;
};
WidgetFactory Menu(const std::string& label,
std::vector<WidgetFactory> children) {
return [=](Widget::Delegate* delegate) {
return std::make_unique<MenuImpl>(delegate, label, children);
};
}
void DrawBoxBackground(smk::RenderTarget* target,
glm::vec2 position,
glm::vec2 dimension) {
auto square = smk::Shape::Square();
square.SetColor({0.f, 0.f, 0.f, 1.f});
square.SetPosition(position);
square.SetScale(dimension);
target->Draw(square);
auto border = smk::Shape::Path(
{
position,
position + glm::vec2(dimension.x, 0.f),
position + dimension,
position + glm::vec2(0.f, dimension.y),
position,
},
1);
border.SetColor({1.f, 1.f, 1.f, 1.f});
target->Draw(border);
}
} // namespace smkflow
<file_sep>/src/smkflow/widget/BoxImpl.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_BOXIMPL_HPP
#define SMKFLOW_WIDGET_BOXIMPL_HPP
#include <memory>
#include <smkflow/widget/Box.hpp>
#include <vector>
namespace smkflow {
class BoxImpl : public Widget, public BoxInterface {
public:
BoxImpl(Delegate* delegate, std::vector<WidgetFactory> children);
bool Step(smk::Input* input, const glm::vec2& cursor) override;
void Draw(smk::RenderTarget* target) override;
Widget* ChildAt(int i) override;
int ChildCount() override;
JSON Serialize() override;
bool Deserialize(JSON&) override;
protected:
std::vector<std::unique_ptr<Widget>> children_;
std::vector<float> children_size_;
glm::vec2 requested_dimensions_;
};
class BoxImplVertical : public BoxImpl {
public:
BoxImplVertical(Delegate* delegate, std::vector<WidgetFactory> children);
glm::vec2 ComputeDimensions() override;
void SetDimensions(glm::vec2 dimensions) override;
void SetPosition(glm::vec2 position) override;
};
class BoxImplHorizontal : public BoxImpl {
public:
BoxImplHorizontal(Delegate* delegate, std::vector<WidgetFactory> children);
glm::vec2 ComputeDimensions() override;
void SetDimensions(glm::vec2 dimensions) override;
void SetPosition(glm::vec2 position) override;
};
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_WIDGET_BOXIMPL_HPP */
<file_sep>/CMakeLists.txt
cmake_minimum_required (VERSION 3.11)
add_subdirectory(third_party)
project(smkflow
LANGUAGES CXX
VERSION 1.0.0
)
option(SMKFLOW_BUILD_EXAMPLES "Set to ON to build examples" ON)
option(SMKFLOW_BUILD_TESTS "Set to ON to build tests" OFF)
add_library(smkflow STATIC
include/smkflow/Constants.hpp
include/smkflow/CursorCapture.hpp
include/smkflow/Elements.hpp
include/smkflow/Model.hpp
include/smkflow/widget/Action.hpp
include/smkflow/widget/Box.hpp
include/smkflow/widget/Input.hpp
include/smkflow/widget/Label.hpp
include/smkflow/widget/Menu.hpp
include/smkflow/widget/Slider.hpp
include/smkflow/widget/Widget.hpp
src/smkflow/BoardImpl.cpp
src/smkflow/BoardImpl.hpp
src/smkflow/ConnectorImpl.cpp
src/smkflow/ConnectorImpl.hpp
src/smkflow/CursorCapture.cpp
src/smkflow/NodeImpl.cpp
src/smkflow/NodeImpl.hpp
src/smkflow/SlotImpl.cpp
src/smkflow/SlotImpl.hpp
src/smkflow/widget/BoxImpl.cpp
src/smkflow/widget/BoxImpl.cpp
src/smkflow/widget/InputImpl.cpp
src/smkflow/widget/LabelImpl.cpp
src/smkflow/widget/LabelImpl.hpp
src/smkflow/widget/MenuEntryImpl.cpp
src/smkflow/widget/MenuImpl.cpp
src/smkflow/widget/SliderImpl.cpp
src/smkflow/widget/Widget.cpp
)
add_library(smkflow::smkflow ALIAS smkflow)
target_include_directories(smkflow
PUBLIC
$<INSTALL_INTERFACE:include>
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
PRIVATE
src/
)
# Add as many warning as possible:
if (MSVC)
target_compile_options(smkflow PRIVATE "/wd4244")
target_compile_options(smkflow PRIVATE "/wd4267")
target_compile_options(smkflow PRIVATE "/wd4996")
target_compile_options(smkflow PRIVATE "/wd4305")
else()
target_compile_options(smkflow PRIVATE "-Wall")
target_compile_options(smkflow PRIVATE "-Werror")
target_compile_options(smkflow PRIVATE "-pedantic-errors")
target_compile_options(smkflow PRIVATE "-Wextra")
target_compile_options(smkflow PRIVATE "-Wno-sign-compare")
endif()
target_link_libraries(smkflow PUBLIC smk::smk)
target_link_libraries(smkflow PRIVATE fmt::fmt)
target_link_libraries(smkflow PUBLIC nlohmann_json::nlohmann_json)
set_target_properties(smkflow PROPERTIES CXX_STANDARD 17)
if(SMKFLOW_BUILD_EXAMPLES)
add_subdirectory(examples)
endif()
if (SMKFLOW_BUILD_TESTS AND ${CMAKE_VERSION} VERSION_GREATER "3.11.4")
set(gtest_force_shared_crt ON CACHE BOOL "" FORCE)
set(FETCHCONTENT_UPDATES_DISCONNECTED TRUE)
include(FetchContent)
FetchContent_Declare( googletest
GIT_REPOSITORY "https://github.com/google/googletest"
GIT_TAG release-1.10.0
)
FetchContent_GetProperties(googletest)
if(NOT googletest_POPULATED)
message(STATUS "Fetching googletest...")
FetchContent_Populate(googletest)
message(STATUS "... done")
add_subdirectory(
${googletest_SOURCE_DIR}
${googletest_BINARY_DIR}
EXCLUDE_FROM_ALL)
endif()
add_executable(tests
src/smkflow/test.hpp
src/smkflow/serialization_test.cpp
)
target_link_libraries(tests
PRIVATE smkflow::smkflow
PRIVATE gtest
PRIVATE gmock
PRIVATE gtest_main
PRIVATE asset
)
set_property(TARGET tests PROPERTY CXX_STANDARD 17)
endif()
<file_sep>/src/smkflow/widget/Widget.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <smkflow/NodeImpl.hpp>
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
void Widget::SetDimensions(glm::vec2 dimensions) {
dimensions_ = dimensions;
}
glm::vec2 Widget::Position() {
return delegate_->Position() + position_;
}
void Widget::InvalidateLayout() {
delegate_->InvalidateLayout();
}
bool Widget::Step(smk::Input* input, const glm::vec2& cursor) {
if (!input->IsCursorPressed())
return false;
auto position = Position();
auto dimension = dimensions();
bool hover = cursor.x > position.x && //
cursor.x < position.x + dimension.x && //
cursor.y > position.y && //
cursor.y < position.y + dimension.y; //
return hover;
}
} // namespace smkflow
<file_sep>/include/smkflow/Constants.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_COLOR_HPP
#define SMKFLOW_COLOR_HPP
#include <glm/glm.hpp>
namespace smkflow {
namespace size {
const float widget_margin = 4.f;
const float widget_height = 48.f - 2.f * widget_margin;
} // namespace size
namespace color {
const float transition = 0.1f;
const auto background = glm::vec4(0.1f, 0.1f, 0.1f, 1.f);
const auto node_background = glm::vec4(0.4f, 0.4f, 0.4f, 0.5f);
const auto text = glm::vec4(1.f, 1.f, 1.f, 1.f);
const auto connector_background = glm::vec4(0.15f, 0.15f, 0.15f, 0.5);
const auto widget_background = glm::vec4(0.5f, 0.5f, 0.5f, 0.5f);
const auto widget_background_hover = glm::vec4(0.2f, 0.2f, 0.2f, 0.8f);
const auto widget_background_focus = glm::vec4(0.1f, 0.1f, 0.1f, 1.f);
const auto widget_foreground = glm::vec4(0.5f, 0.5f, 0.9f, 1.0f);
const auto widget_foreground_hover = glm::vec4(0.3f, 0.3f, 1.0f, 0.9f);
const auto widget_foreground_focus = glm::vec4(0.0f, 0.0f, 1.0f, 1.0f);
} // namespace color
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_COLOR_HPP */
<file_sep>/src/smkflow/ConnectorImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include "smkflow/ConnectorImpl.hpp"
#include <smk/Shape.hpp>
#include <smkflow/Constants.hpp>
#include "smkflow/SlotImpl.hpp"
namespace smkflow {
ConnectorImpl::ConnectorImpl(SlotImpl* A, SlotImpl* B) : input_(A), output_(B) {
if (!input_->IsRight() && output_->IsRight())
std::swap(input_, output_);
input_->Connect(this);
output_->Connect(this);
}
ConnectorImpl::~ConnectorImpl() {
Disconnect();
}
bool ConnectorImpl::IsConnected() {
return input_;
}
void ConnectorImpl::Disconnect() {
SlotImpl* input = input_;
SlotImpl* output = output_;
input_ = nullptr;
output_ = nullptr;
if (input)
input->Disconnect(this);
if (output)
output->Disconnect(this);
}
void ConnectorImpl::DrawBackground(smk::RenderTarget* target) {
if (!IsConnected())
return;
RebuildVertex();
target->Draw(background_);
}
void ConnectorImpl::DrawForeground(smk::RenderTarget* target) {
if (!IsConnected())
return;
RebuildVertex();
target->Draw(foreground_);
}
void ConnectorImpl::RebuildVertex() {
glm::vec2 position_a = input_->GetPosition();
glm::vec2 position_b = output_->GetPosition();
if (position_a == position_a_ && position_b == position_b_)
return;
position_a_ = position_a;
position_b_ = position_b;
float d = glm::distance(position_a, position_b);
glm::vec2 strength(d * 0.4, 0);
auto bezier = smk::Shape::Bezier(
{
position_a,
position_a + (input_->IsRight() ? +strength : -strength),
position_b + (output_->IsRight() ? +strength : -strength),
position_b,
},
32);
background_ = smk::Shape::Path(bezier, 16);
foreground_ = smk::Shape::Path(bezier, 10);
background_.SetColor(color::connector_background);
foreground_.SetColor(input_->GetColor());
}
Slot* ConnectorImpl::GetInput() {
return input_;
}
Slot* ConnectorImpl::GetOutput() {
return output_;
}
} // namespace smkflow
<file_sep>/src/smkflow/widget/MenuEntryImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <smk/RenderTarget.hpp>
#include <smk/Shape.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include <smkflow/widget/LabelImpl.hpp>
#include <smkflow/widget/Menu.hpp>
namespace smkflow {
class MenuEntryImpl : public LabelImpl, public ActionContext {
public:
MenuEntryImpl(Widget::Delegate* delegate,
const std::string& label,
Action action)
: LabelImpl(delegate, label), action_(action) {
square_ = smk::Shape::Square();
}
virtual ~MenuEntryImpl() = default;
bool Step(smk::Input* input, const glm::vec2& cursor) override {
cursor_ = cursor;
auto position = cursor_ - Position();
hover_ = (position.x >= 0.f && position.y >= 0.f &&
position.x <= dimensions().x && position.y <= dimensions().y);
focused_ = hover_ && input->IsCursorHeld();
LabelImpl::Step(input, cursor_);
if (hover_ && input->IsCursorPressed())
action_(this);
return Widget::Step(input, cursor_);
}
void Draw(smk::RenderTarget* target) override {
if (hover_) {
square_.SetColor(focused_ ? color::widget_background_focus
: hover_ ? color::widget_background_hover
: color::widget_background);
square_.SetPosition(Position());
square_.SetScale(dimensions());
target->Draw(square_);
}
LabelImpl::Draw(target);
}
Board* board() override { return delegate()->board(); }
glm::vec2 cursor() override { return cursor_; }
private:
glm::vec2 cursor_;
smk::Transformable square_;
Action action_;
bool focused_ = false;
bool hover_ = false;
};
WidgetFactory MenuEntry(const std::string& label, Action action) {
return [=](Widget::Delegate* delegate) {
return std::make_unique<MenuEntryImpl>(delegate, label, action);
};
}
Action CreateNode(model::Node node) {
return [=](ActionContext* context) {
context->board()->Create(node)->SetPosition(context->cursor());
};
}
Action ActionNone() {
return [=](ActionContext*) {};
}
} // namespace smkflow
<file_sep>/src/smkflow/test.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <gtest/gtest.h>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include <smk/Window.hpp>
#include "asset.hpp"
class Test : public ::testing::Test {
public:
Test() { window_ = smk::Window(640, 480, ""); }
smk::Window& window() { return window_; }
const char* font() { return asset::arial_ttf; }
private:
smk::Window window_;
};
<file_sep>/examples/widget_gallery.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <iostream>
#include <smk/Color.hpp>
#include <smk/Window.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include <smkflow/widget/Box.hpp>
#include <smkflow/widget/Input.hpp>
#include <smkflow/widget/Label.hpp>
#include <smkflow/widget/Menu.hpp>
#include <smkflow/widget/Slider.hpp>
#include <smkflow/widget/Widget.hpp>
#include "asset.hpp"
auto color_node = glm::vec4(0.5f, 0.2f, 0.2f, 1.f);
using namespace smkflow;
auto node_sliders = model::Node{
0,
"Sliders",
color_node,
{},
{},
VBox({
Slider(),
Slider(0, 10, 0, "{:.0f} children"),
Slider(0, 1, 0.5, "{:.2f}"),
}),
};
auto node_input = model::Node{
0,
"Input",
color_node,
{},
{},
VBox({
Input("input box"),
Input("input box"),
Input("input box"),
}),
};
auto node_label = model::Node{
0,
"Label",
color_node,
{},
{},
VBox({
HBox({Label("R:"), Slider(0, 1, 0.5, "{:.2f}")}),
HBox({Label("G:"), Slider(0, 1, 0.5, "{:.2f}")}),
HBox({Label("B:"), Slider(0, 1, 0.5, "{:.2f}")}),
}),
};
auto node_box = model::Node{
0,
"Box",
color_node,
{},
{},
HBox({
VBox({
Slider(),
Slider(0, 10, 0, "{:.0f} children"),
Slider(0, 1, 0.5, "{:.2f}"),
}),
VBox({
Slider(),
Slider(0, 1, 0.5, "{:.2f}"),
}),
VBox({
Slider(),
HBox({
Slider(),
Slider(0, 1, 0.5, "{:.2f}"),
}),
Slider(0, 1, 0.5, "{:.2f}"),
}),
}),
};
auto node_menu = model::Node{
0,
"Menu",
color_node,
{},
{},
Menu("menu",
{
Menu("File",
{
MenuEntry("1.html", ActionNone()),
MenuEntry("2.html", ActionNone()),
MenuEntry("3.html", ActionNone()),
MenuEntry("4.html", ActionNone()),
MenuEntry("5.html", ActionNone()),
MenuEntry("6.html", ActionNone()),
MenuEntry("7.html", ActionNone()),
MenuEntry("8.html", ActionNone()),
MenuEntry("9.html", ActionNone()),
}),
Menu("Edition",
{
Slider(),
Slider(0, 1, 0.5, "{:.2f}"),
}),
Menu("Display",
{
Menu("Sliders",
{
Slider(0, 1, 0.5, "{:.2f}"),
Slider(0, 1, 0.5, "{:.2f}"),
}),
Menu("Input",
{
Input("input 1"),
Input("input 2"),
}),
}),
}),
};
auto my_board = model::Board{
{
node_sliders,
node_box,
node_input,
node_label,
},
{
MenuEntry("Sliders", CreateNode(node_sliders)),
MenuEntry("Box", CreateNode(node_box)),
MenuEntry("Input", CreateNode(node_input)),
MenuEntry("Label", CreateNode(node_label)),
},
asset::arial_ttf,
};
int main() {
auto window = smk::Window(512, 512, "test");
auto board = Board::Create(my_board);
board->Create(node_input)->SetPosition({-150, -150});
board->Create(node_sliders)->SetPosition({+150, -150});
board->Create(node_box)->SetPosition({-150, +100});
board->Create(node_label)->SetPosition({-150, +300});
board->Create(node_menu)->SetPosition({+150, +300});
window.ExecuteMainLoop([&] {
window.Clear(color::background);
window.PoolEvents();
board->Step(&window, &window.input());
board->Draw(&window);
window.Display();
});
return EXIT_SUCCESS;
}
<file_sep>/src/smkflow/widget/MenuImpl.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_MENUIMPL_HPP
#define SMKFLOW_WIDGET_MENUIMPL_HPP
#include <glm/glm.hpp>
namespace smk {
class RenderTarget;
}
namespace smkflow {
void DrawBoxBackground(smk::RenderTarget* target,
glm::vec2 position,
glm::vec2 dimensions);
} /* namespace smkflow */
#endif /* end of include guard: SMKFLOW_WIDGET_MENUIMPL_HPP */
<file_sep>/include/smkflow/widget/Widget.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_WIDGET_HPP
#define SMKFLOW_WIDGET_WIDGET_HPP
#include <functional>
#include <glm/glm.hpp>
#include <memory>
#include <smkflow/CursorCapture.hpp>
#include <smkflow/JSON.hpp>
namespace smk {
class RenderTarget;
class Input;
class Font;
} // namespace smk
namespace smkflow {
class Board;
class Widget {
public:
class Delegate {
public:
virtual ~Delegate() = default;
virtual Board* board() = 0;
virtual CursorCapture CaptureCursor() = 0;
virtual bool IsInsideMenu() { return false; }
virtual glm::vec2 Position() = 0;
virtual smk::Font& Font() = 0;
virtual void InvalidateLayout() = 0;
};
Widget(Delegate* delegate) : delegate_(delegate) {}
virtual ~Widget() = default;
// Layout:
glm::vec2 Position();
glm::vec2 PositionInWidget() { return position_; }
glm::vec2 dimensions() { return dimensions_; }
virtual glm::vec2 ComputeDimensions() = 0;
virtual void SetDimensions(glm::vec2 dimensions);
virtual void SetPosition(glm::vec2 position) { position_ = position; }
void InvalidateLayout();
// Interactivity:
virtual bool Step(smk::Input*, const glm::vec2& /* cursor */);
// Render:
virtual void Draw(smk::RenderTarget*) {}
// Serialization:
virtual JSON Serialize() { return JSON(); }
virtual bool Deserialize(JSON&) { return true; }
protected:
Delegate* delegate() { return delegate_; }
private:
Delegate* delegate_;
glm::vec2 position_;
glm::vec2 dimensions_;
};
using WidgetFactory = std::function<std::unique_ptr<Widget>(Widget::Delegate*)>;
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_WIDGET_WIDGET_HPP */
<file_sep>/src/smkflow/widget/SliderImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <fmt/core.h>
#include <algorithm>
#include <smk/Input.hpp>
#include <smk/RenderTarget.hpp>
#include <smk/Shape.hpp>
#include <smk/Text.hpp>
#include <smkflow/BoardImpl.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/widget/Slider.hpp>
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
namespace {
const float handle_width = 8.f;
} // namespace
class SliderImpl : public Widget, public SliderInterface {
public:
SliderImpl(Delegate* delegate,
float min,
float max,
float value,
std::string format)
: Widget(delegate), min_(min), max_(max), value_(value), format_(format) {
value_ = std::min(max_, std::max(min_, value_));
track_ = smk::Shape::Square();
handle_ = smk::Shape::Square();
computed_dimensions_ = {200.f, size::widget_height};
}
// Widget implementation:
glm::vec2 ComputeDimensions() override { return computed_dimensions_; }
bool Step(smk::Input* input, const glm::vec2& cursor) override {
auto position = Position();
auto dimension = dimensions();
if (cursor_capture_ && input->IsCursorReleased())
cursor_capture_.Invalidate();
hover_ = cursor.x > position.x && //
cursor.x < position.x + dimension.x && //
cursor.y > position.y && //
cursor.y < position.y + dimension.y; //
focus_ = bool(cursor_capture_);
if (hover_ && input->IsCursorPressed())
cursor_capture_ = delegate()->CaptureCursor();
if (cursor_capture_) {
hover_ = true;
value_ = min_ + (cursor.x - position.x) * (max_ - min_) / dimension.x;
value_ = std::max(min_, std::min(max_, value_));
}
return Widget::Step(input, cursor);
}
void Draw(smk::RenderTarget* target) override {
auto position = Position();
auto dimension = dimensions();
text_ = smk::Text(delegate()->Font(), fmt::format(format_, value_));
track_.SetPosition(position);
track_.SetScale(dimension);
handle_.SetScale(handle_width, dimension.y);
handle_.SetPosition(position.x + (dimension.x - handle_width) *
(value_ - min_) / (max_ - min_),
position.y);
auto& track_color_target = focus_ ? color::widget_background_focus
: hover_ ? color::widget_background_hover
: color::widget_background;
auto& handle_color_target = focus_ ? color::widget_foreground_focus
: hover_ ? color::widget_foreground_hover
: color::widget_foreground;
track_color_ += (track_color_target - track_color_) * color::transition;
handle_color_ += (handle_color_target - handle_color_) * color::transition;
track_.SetColor(track_color_);
handle_.SetColor(handle_color_);
target->Draw(track_);
target->Draw(handle_);
text_.SetPosition(position + dimension * 0.5f -
text_.ComputeDimensions() * 0.5f);
target->Draw(text_);
}
void SetValue(float value) override { value_ = value; }
float GetValue() override { return value_; }
JSON Serialize() override {
JSON json;
json["value"] = value_;
return json;
}
bool Deserialize(JSON& json) override {
value_ = json["value"];
return true;
}
private:
float min_;
float max_;
float value_;
glm::vec2 computed_dimensions_;
bool focus_ = false;
bool hover_ = false;
smk::Transformable handle_;
smk::Transformable track_;
CursorCapture cursor_capture_;
smk::Text text_;
std::string format_;
glm::vec4 track_color_ = glm::vec4(0.f);
glm::vec4 handle_color_ = glm::vec4(0.f);
};
// static
WidgetFactory Slider(float min, float max, float value, std::string format) {
return [=](Widget::Delegate* delegate) {
return std::make_unique<SliderImpl>(delegate, min, max, value, format);
};
}
// static
SliderInterface* Slider(Widget* w) {
return dynamic_cast<SliderInterface*>(w);
}
} // namespace smkflow
<file_sep>/src/smkflow/NodeImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <algorithm>
#include <smk/Font.hpp>
#include <smk/Shape.hpp>
#include <smkflow/BoardImpl.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/NodeImpl.hpp>
#include <smkflow/SlotImpl.hpp>
namespace smkflow {
float width = 150;
float height = 150;
float title_height = 48;
float padding = 10;
NodeImpl::NodeImpl(BoardImpl* board, const model::Node& model) : board_(board) {
color_ = model.color;
identifier_ = model.identifier;
width_ = 0.f; // 32.f;
height_ = 0.f; // 32.f;
title_ = smk::Text(board->font(), model.label);
title_.SetColor(color::text);
for (const auto& model : model.input) {
auto slot =
std::make_unique<SlotImpl>(this, model.label, false, model.color);
inputs_.push_back(std::move(slot));
}
for (const auto& model : model.output) {
auto slot =
std::make_unique<SlotImpl>(this, model.label, true, model.color);
outputs_.push_back(std::move(slot));
}
if (model.widget)
widget_ = model.widget(this);
Layout();
}
void NodeImpl::InvalidateLayout() {
layout_invalidated_ = true;
}
void NodeImpl::Layout() {
layout_invalidated_ = false;
auto title_dimension =
title_.ComputeDimensions() + 6.f * padding * glm::vec2(1.f);
float widget_width = 0.f;
float widget_height = 0.f;
if (widget_) {
auto dimensions = widget_->ComputeDimensions();
widget_->SetDimensions(dimensions);
widget_width = std::max(widget_width, dimensions.x);
widget_height += dimensions.y + size::widget_margin;
}
float input_width = 0.f;
float input_height = 0.f;
for (const auto& slot : inputs_) {
auto dimension = slot->ComputeDimensions();
input_width = std::max(input_width, dimension.x);
input_height += dimension.y + size::widget_margin;
}
float output_width = 0.f;
float output_height = 0.f;
for (const auto& slot : outputs_) {
auto dimension = slot->ComputeDimensions();
output_width = std::max(output_width, dimension.x);
output_height += dimension.y + size::widget_margin;
}
input_width += padding;
output_width += padding;
widget_width = std::max(widget_width, title_dimension.x - input_width -
output_height + 2 * padding);
const float x_a = 0.f;
const float x_b = x_a + input_width;
const float x_c = x_b + widget_width;
const float x_d = x_c + output_width;
const float y_a = 0.f;
const float y_b = y_a + title_height + padding;
const float y_c =
y_b + std::max(input_height, std::max(widget_height, output_height));
width_ = x_d;
height_ = y_c;
float x, y;
x = x_a;
y = y_b + board_->font().line_height() * 0.5f;
for (auto& slot : inputs_) {
slot->SetPosition({x, y});
auto dimension = slot->ComputeDimensions();
y += dimension.y + size::widget_margin;
}
x = x_d;
y = y_b + board_->font().line_height() * 0.5f;
for (auto& slot : outputs_) {
auto dimension = slot->ComputeDimensions();
slot->SetPosition({x, y});
y += dimension.y + size::widget_margin;
}
x = x_b;
y = y_b;
if (widget_) {
auto dimensions = widget_->ComputeDimensions();
widget_->SetDimensions({widget_width, dimensions.y});
widget_->SetPosition({x, y});
y += dimensions.y + size::widget_margin;
}
width_ = x_d;
height_ = y_c;
base_ = smk::Shape::RoundedRectangle(width_, height_, 10);
base_.SetCenter(-width_ * 0.5, -height_ * 0.5);
base_.SetColor(color::node_background);
title_base_ = smk::Shape::RoundedRectangle(width_, title_height, 10);
title_base_.SetCenter(-width_ * 0.5, -title_height * 0.5);
title_base_.SetColor(color_);
dimension_ = {width_, height_};
}
NodeImpl::~NodeImpl() = default;
void NodeImpl::Draw(smk::RenderTarget* target) {
base_.SetPosition(position_);
title_base_.SetPosition(position_);
title_.SetPosition(position_ + glm::vec2(padding, padding));
target->Draw(base_);
if (!Selected())
target->Draw(title_base_);
target->Draw(title_);
for (auto& slot : inputs_)
slot->Draw(target);
for (auto& slot : outputs_)
slot->Draw(target);
if (widget_) {
widget_->Draw(target);
}
}
void NodeImpl::Step(smk::Input* input, glm::vec2 cursor) {
position_ += speed_;
speed_ *= 0.2f;
if (input->IsCursorReleased())
cursor_captured_.Invalidate();
if (layout_invalidated_)
Layout();
if (widget_)
widget_->Step(input, cursor);
bool hover = cursor.x > position_.x && cursor.x < position_.x + width_ &&
cursor.y > position_.y && cursor.y < position_.y + height_;
if (input->IsCursorPressed()) {
if (hover) {
if (input->IsKeyHold(GLFW_KEY_LEFT_CONTROL))
cursor_captured_for_selection_ = board_->CaptureSelection();
cursor_captured_ = board_->CaptureCursor();
}
cursor_drag_point = position_ - cursor;
}
if (!input->IsCursorHeld())
return;
if (!(cursor_captured_ || cursor_captured_for_selection_))
return;
position_ = cursor_drag_point + cursor;
speed_ = glm::vec2(0.f, 0.f);
}
void NodeImpl::Push(glm::vec2 direction) {
position_ += direction;
speed_ += direction * 0.2f;
}
void NodeImpl::SetPosition(const glm::vec2& position) {
position_ = position;
speed_ = glm::vec2(0.f, 0.f);
}
const glm::vec2& NodeImpl::GetPosition() {
return position_;
}
SlotImpl* NodeImpl::FindSlot(const glm::vec2& position) {
for (auto& slot : inputs_) {
glm::vec2 slot_position = slot->GetPosition();
if (glm::distance(position, slot_position) < 16)
return slot.get();
}
for (auto& slot : outputs_) {
glm::vec2 slot_position = slot->GetPosition();
if (glm::distance(position, slot_position) < 16)
return slot.get();
}
return nullptr;
}
Board* NodeImpl::GetBoard() {
return board_;
}
int NodeImpl::InputCount() {
return inputs_.size();
}
Slot* NodeImpl::InputAt(int i) {
return inputs_.at(i).get();
}
int NodeImpl::OutputCount() {
return outputs_.size();
}
Slot* NodeImpl::OutputAt(int i) {
return outputs_.at(i).get();
}
Widget* NodeImpl::widget() {
return widget_.get();
}
smk::Font& NodeImpl::Font() {
return board_->font();
}
CursorCapture NodeImpl::CaptureCursor() {
return board_->CaptureCursor();
}
Board* NodeImpl::board() {
return board_;
}
JSON NodeImpl::Serialize() {
JSON json;
json["position"] = {position_.x, position_.y};
json["identifier"] = identifier_;
if (widget_)
json["widget"] = widget_->Serialize();
return json;
}
bool NodeImpl::Deserialize(JSON& json) {
position_.x = json["position"][0];
position_.y = json["position"][1];
if (widget_)
widget_->Deserialize(json["widget"]);
return true;
}
bool NodeImpl::Selected() {
return bool(cursor_captured_for_selection_);
}
} // namespace smkflow
<file_sep>/src/smkflow/CursorCapture.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <algorithm>
#include <smkflow/CursorCapture.hpp>
namespace smkflow {
CursorCapture::CursorCapture() = default;
CursorCapture::CursorCapture(CursorCapturable* ref) {
if (ref->set_.size() >= ref->capacity_)
return;
ref_ = ref;
ref_->set_.insert(this);
}
CursorCapture::~CursorCapture() {
Invalidate();
}
CursorCapture::operator bool() {
return ref_;
}
CursorCapture::CursorCapture(CursorCapture&& other) {
Swap(other);
}
void CursorCapture::operator=(CursorCapture&& other) {
Swap(other);
}
void CursorCapture::Swap(CursorCapture& other) {
if (this == &other)
return;
std::swap(ref_, other.ref_);
if (other.ref_) {
other.ref_->set_.erase(this);
other.ref_->set_.insert(&other);
}
if (ref_) {
ref_->set_.erase(&other);
ref_->set_.insert(this);
}
}
void CursorCapture::Invalidate() {
if (!ref_)
return;
ref_->set_.erase(this);
ref_ = nullptr;
}
CursorCapturable::CursorCapturable(int capacity) : capacity_(capacity) {}
CursorCapturable::~CursorCapturable() {
Invalidate();
}
CursorCapture CursorCapturable::Capture() {
return CursorCapture(this);
}
void CursorCapturable::Invalidate() {
while (set_.size())
(**set_.begin()).Invalidate();
}
CursorCapturable::operator bool() {
return set_.size();
}
} // namespace smkflow
<file_sep>/README.md
[smk]: https://github.com/ArthurSonzogni/smk
[smkflow]: https://github.com/ArthurSonzogni/smkflow
[logo]: ./logo.png
![logo][logo]
[![travis][badge.travis]][travis]
[![issues][badge.issues]][issues]
[![license][badge.license]][license]
[![contributors][badge.contributors]][contributors]
[badge.travis]: https://img.shields.io/travis/com/arthursonzogni/smkflow
[badge.issues]: https://img.shields.io/github/issues-raw/arthursonzogni/smkflow
[badge.license]: https://img.shields.io/github/license/arthursonzogni/smkflow?color=black
[badge.contributors]: https://img.shields.io/github/contributors/arthursonzogni/smkflow?color=blue
[travis]: https://travis-ci.com/ArthurSonzogni/smkflow
[issues]: https://github.com/ArthurSonzogni/smkflow/issues
[license]: http://opensource.org/licenses/MIT
[contributors]: https://github.com/ArthurSonzogni/smkflow/graphs/contributors
SMKFLOW is a node editor in C++ compatible with WebAssembly using [SMK][smk]
**Features**:
- Compatible with WebAssembly.
- The permissive MIT license.
- Use CMake FetchContent. No download is needed. You use the cmake snippet below
to depends on smkflow.
**Warning**. This is an active project. Please do not expect the API to be stable for the next few months.
Examples/Demo:
---------
Use the [./examples/](./examples/) directory. This produce the following
webassembly [demo](http://arthursonzogni.github.io/smkflow/examples/index.html)
API
---
The API consists of 4 files:
- [Model.hpp](./include/smkflow/Model.hpp) Let you define how your nodes will look like. Please try example:
[./examples/minimal.cpp](./examples/minimal.cpp).
- [Elements.hpp](./include/smkflow/Elements.hpp) Contains the public definition elements composing the view at runtime. You can use them to query/update the view. See [./examples/algebra.cpp](./examples/algebra.cpp) file.
- [Constants.hpp](./include/smkflow/Constants.hpp) Contains the default sizes and
colors the library is using for staying consistant. Feel free to fork and modify
this file to make smkflow suits your needs.
- [Widget/](./include/smkflow/widget). Every nodes can display some GUI inside. This directory contains the GUI public interface. You can also easily define your own components if needed.
CMake
-----
Include the following lines in your CMake and you are ready to go.
~~~cmake
include(FetchContent)
FetchContent_Declare(smkflow
GIT_REPOSITORY https://github.com/ArthurSonzogni/smkflow
GIT_TAG master # Please choose a fixed commit hash here.
)
FetchContent_GetProperties(smkflow)
if(NOT smkflow_POPULATED)
FetchContent_Populate(smkflow)
add_subdirectory( ${smkflow_SOURCE_DIR} ${smkflow_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()
~~~
Then link your application with smkflow:
~~~cmake
target_link_library(my_applcation PRIVATE smkflow::smkflow)
~~~
Want to contribute?
-------------------
Feel free to post issues, ask questions or submit any work to this repository.
<file_sep>/src/smkflow/widget/LabelImpl.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <smk/Text.hpp>
#include <smkflow/widget/Label.hpp>
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
class LabelImpl : public Widget {
public:
LabelImpl(Delegate* delegate, const std::string& text);
// Widget implementation:
glm::vec2 ComputeDimensions() override;
void Draw(smk::RenderTarget* target) override;
private:
glm::vec2 computed_dimensions_;
smk::Text text_;
};
} // namespace smkflow
<file_sep>/src/smkflow/SlotImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <algorithm>
#include <smk/Shape.hpp>
#include <smk/Transformable.hpp>
#include <smkflow/BoardImpl.hpp>
#include <smkflow/ConnectorImpl.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/NodeImpl.hpp>
#include <smkflow/SlotImpl.hpp>
namespace smkflow {
smk::Transformable circle;
smk::Transformable circle_background;
SlotImpl::SlotImpl(NodeImpl* node,
std::string label,
bool is_right,
glm::vec4 color)
: node_(node), is_right_(is_right), color_(color) {
circle_background = smk::Shape::Circle(8);
circle = smk::Shape::Circle(5);
text_ = label + " ";
SetText(label);
}
glm::vec2 SlotImpl::ComputeDimensions() {
auto dimensions = label_.ComputeDimensions();
dimensions.y = std::max(dimensions.y, size::widget_height);
return dimensions;
}
glm::vec2 SlotImpl::GetPosition() {
return node_->GetPosition() + position_;
}
void SlotImpl::Draw(smk::RenderTarget* target) {
auto position = GetPosition();
circle_background.SetPosition(position);
circle_background.SetColor(color::connector_background);
target->Draw(circle_background);
circle.SetPosition(position);
circle.SetColor(color_);
target->Draw(circle);
label_.SetPosition(position);
target->Draw(label_);
}
void SlotImpl::Connect(ConnectorImpl* connector) {
if (connector->output() == this) {
while (!connectors_.empty())
Disconnect(connectors_.back());
}
for (auto& it : connectors_) {
if (it->input() == connector->input() &&
it->output() == connector->output()) {
return;
}
}
connectors_.push_back(connector);
// if (connector_)
// Disconnect(connector_);
// connector_ = connector;
}
void SlotImpl::Disconnect(ConnectorImpl* connector) {
auto it = std::find(connectors_.begin(), connectors_.end(), connector);
if (it == connectors_.end())
return;
connectors_.erase(it);
connector->Disconnect();
}
bool SlotImpl::IsRight() {
return is_right_;
}
glm::vec4 SlotImpl::GetColor() {
return color_;
}
void SlotImpl::SetText(const std::string& text) {
if (text_ == text)
return;
text_ = text;
label_ = smk::Text(node_->boardImpl()->font(), text_);
auto center = label_.ComputeDimensions();
center.y *= 0.5;
if (IsRight())
center.x += 5;
else
center.x = -5;
label_.SetCenter(center);
node_->InvalidateLayout();
}
Node* SlotImpl::GetNode() {
return node_;
}
Connector* SlotImpl::GetConnector() {
return connectors_.size() >= 1 ? connectors_[0] : nullptr;
}
Slot* SlotImpl::OppositeSlot() {
auto* connector = GetConnector();
return !connector ? nullptr
: connector->GetInput() == this ? connector->GetOutput()
: connector->GetInput();
}
Node* SlotImpl::OppositeNode() {
auto* opposite_slot = OppositeSlot();
return opposite_slot ? opposite_slot->GetNode() : nullptr;
}
} // namespace smkflow
<file_sep>/src/smkflow/BoardImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <algorithm>
#include <smk/Shape.hpp>
#include <smkflow/BoardImpl.hpp>
#include <smkflow/ConnectorImpl.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/NodeImpl.hpp>
#include <smkflow/SlotImpl.hpp>
#include <smkflow/widget/Box.hpp>
#include <smkflow/widget/MenuImpl.hpp>
namespace smkflow {
class BoardImpl::MenuDelegate : public Widget::Delegate {
public:
MenuDelegate(BoardImpl* board) : board_(board) {}
glm::vec2 Position() override { return {0.f, 0.f}; }
void InvalidateLayout() override { invalidated_ = true; }
smk::Font& Font() override { return board_->font(); }
CursorCapture CaptureCursor() override {
cursor_capturable_.Invalidate();
return cursor_capturable_.Capture();
}
bool IsInsideMenu() override { return true; }
bool Validate() {
bool ret = invalidated_;
invalidated_ = false;
return ret;
}
BoardImpl* board() override { return board_; }
private:
bool invalidated_ = true;
BoardImpl* board_;
CursorCapturable cursor_capturable_;
};
// static
std::unique_ptr<Board> Board::Create(const model::Board& model) {
return std::make_unique<BoardImpl>(model);
}
BoardImpl::~BoardImpl() = default;
BoardImpl::BoardImpl(const model::Board& model) : model_(model) {
font_ = smk::Font(model_.font, 30);
menu_delegate_ = std::make_unique<MenuDelegate>(this);
menu_widget_ = VBox(model.context_widgets_)(menu_delegate_.get());
square_ = smk::Shape::Square();
}
NodeImpl* BoardImpl::Create(const model::Node& model) {
cursor_captured_for_menu_.Invalidate();
nodes_.push_back(std::make_unique<NodeImpl>(this, model));
return nodes_.back().get();
}
void BoardImpl::Step(smk::RenderTarget* target, smk::Input* input) {
input_ = input;
// For some reasons the scrolling offset in web browsers is 100x less than the
// one on desktop?
// TODO(arthursonzogni): Figure out why???
#if __EMSCRIPTEN__
float zoom_increment = input->scroll_offset().y * 0.001f;
#else
float zoom_increment = input->scroll_offset().y * 0.1f;
#endif
view_shifting_ += (input->cursor() - target->dimensions() * 0.5f) *
std::exp(view_zoom_) * (1.f - std::exp(zoom_increment));
view_zoom_ += zoom_increment;
cursor_ =
(input->cursor() - target->dimensions() * 0.5f) * std::exp(view_zoom_) +
view_shifting_;
if (input_->IsKeyReleased(GLFW_KEY_LEFT_CONTROL))
cursor_capturable_for_selection_.Invalidate();
ReleaseConnector();
ReleaseView();
AquireConnector();
for (const auto& node : nodes_)
node->Step(input_, cursor_);
Menu();
MoveConnector();
AcquireView();
MoveView();
PushNodeAppart();
}
void BoardImpl::PushNodeAppart() {
if (cursor_capturable_) {
push_ = 0.f;
return;
}
// Find 2 nodes, try to move them away from each other.
int k = 0;
std::vector<NodeImpl*> h_nodes;
for (auto& it : nodes_)
h_nodes.push_back(it.get());
std::sort(h_nodes.begin(), h_nodes.end(), [](NodeImpl* a, NodeImpl* b) {
return a->position().x < b->position().x;
});
const float margin = 20.f;
for (size_t a = 0; a < h_nodes.size(); ++a) {
NodeImpl* node_a = nodes_.at(a).get();
glm::vec2 a1 = node_a->position() - glm::vec2(margin, margin);
glm::vec2 a2 = a1 + node_a->dimension() + 2.f * glm::vec2(margin, margin);
for (size_t b = a + 1; b < h_nodes.size(); ++b) {
NodeImpl* node_b = nodes_.at(b).get();
glm::vec2 b1 = node_b->position() - glm::vec2(margin, margin);
if (a2.x < b1.x)
continue;
++k;
glm::vec2 b2 = b1 + node_b->dimension() + 2.f * glm::vec2(margin, margin);
float dist = std::max(std::max(b1.x - a2.x, a1.x - b2.x),
std::max(b1.y - a2.y, a1.y - b2.y));
if (dist > 0.f)
continue;
// clang-format off
glm::vec2 dir;
if (b1.x - a2.x == dist)
dir = glm::vec2(dist, 0.f);
if (a1.x - b2.x == dist)
dir = glm::vec2(-dist, 0.f);
if (b1.y - a2.y == dist)
dir = glm::vec2(0.f, dist);
if (a1.y - b2.y == dist)
dir = glm::vec2(0.f, -dist);
// clang-format on
glm::vec2 ca = node_a->position() + node_a->dimension() * 0.5f;
glm::vec2 cb = node_b->position() + node_b->dimension() * 0.5f;
dir += glm::normalize(cb - ca) * dist * 0.1f;
dir *= push_;
node_a->Push(dir);
node_b->Push(-dir);
}
}
push_ += (0.2f - push_) * 0.01f;
}
void BoardImpl::AquireConnector() {
if (!input_->IsCursorPressed())
return;
start_slot_ = FindSlot(cursor_);
if (!start_slot_)
return;
cursor_captured_for_connector_ = CaptureCursor();
if (!cursor_captured_for_connector_)
return;
connector_in_ = start_slot_->GetPosition();
connector_in_pushed_ = start_slot_->GetPosition();
connector_out_pushed_ = start_slot_->GetPosition();
connector_out_ = start_slot_->GetPosition();
}
void BoardImpl::MoveConnector() {
if (!cursor_captured_for_connector_)
return;
float d = glm::distance(connector_in_, cursor_);
glm::vec2 strength(d * 0.4, 0);
glm::vec2 connector_in_pushed =
connector_in_ + (start_slot_->IsRight() ? +strength : -strength);
glm::vec2 connector_out_pushed = cursor_;
SlotImpl* end_slot = FindSlot(cursor_);
if (end_slot && end_slot != start_slot_ &&
end_slot->GetColor() == start_slot_->GetColor()) {
connector_out_ += (end_slot->GetPosition() - connector_out_) * 0.5f;
connector_out_pushed =
connector_out_ + (end_slot->IsRight() ? +strength : -strength);
connector_out_ += (connector_out_ - connector_out_) * 0.2f;
} else {
connector_out_ = cursor_;
}
connector_out_pushed_ +=
(connector_out_pushed - connector_out_pushed_) * 0.2f;
connector_in_pushed_ += (connector_in_pushed - connector_in_pushed_) * 0.2f;
}
void BoardImpl::ReleaseConnector() {
if (!cursor_captured_for_connector_)
return;
if (!input_->IsCursorReleased())
return;
cursor_captured_for_connector_.Invalidate();
SlotImpl* end_slot = FindSlot(cursor_);
if (!end_slot)
return;
if (end_slot->GetColor() != start_slot_->GetColor())
return;
Connect(start_slot_, end_slot);
}
void BoardImpl::AcquireView() {
if (!input_->IsCursorPressed())
return;
if (cursor_capturable_for_selection_)
return;
cursor_captured_for_dragging_view_ = CaptureCursor();
if (!cursor_captured_for_dragging_view_)
return;
selection_id_ ++;
grab_point_ = view_shifting_ + input_->cursor() * std::exp(view_zoom_);
}
void BoardImpl::MoveView() {
if (!cursor_captured_for_dragging_view_)
return;
view_shifting_ = grab_point_ - input_->cursor() * std::exp(view_zoom_);
}
void BoardImpl::ReleaseView() {
if (!input_->IsCursorReleased())
return;
cursor_captured_for_dragging_view_.Invalidate();
}
void BoardImpl::Draw(smk::RenderTarget* target) {
auto view = smk::View();
view.SetCenter(view_shifting_);
view.SetSize(target->dimensions() * std::exp(view_zoom_));
target->SetView(view);
for (const auto& node : nodes_)
node->Draw(target);
for (const auto& connector : connectors_)
connector->DrawBackground(target);
for (const auto& connector : connectors_)
connector->DrawForeground(target);
if (cursor_captured_for_connector_) {
auto bezier = smk::Shape::Bezier(
{
connector_in_,
connector_in_pushed_,
connector_out_pushed_,
connector_out_,
},
32);
auto background_ = smk::Shape::Path(bezier, 16);
auto foreground_ = smk::Shape::Path(bezier, 10);
background_.SetColor(color::connector_background);
foreground_.SetColor(start_slot_->GetColor());
target->Draw(background_);
target->Draw(foreground_);
}
if (cursor_captured_for_menu_) {
auto pos = menu_widget_->Position();
auto dim = menu_widget_->dimensions();
DrawBoxBackground(target, pos - size::widget_margin * glm::vec2(1.f),
dim + size::widget_margin * glm::vec2(2.f));
menu_widget_->Draw(target);
}
}
SlotImpl* BoardImpl::FindSlot(const glm::vec2& position) {
for (auto& node : nodes_) {
SlotImpl* slot = node->FindSlot(position);
if (slot)
return slot;
}
return nullptr;
}
CursorCapture BoardImpl::CaptureCursor() {
return cursor_capturable_.Capture();
}
CursorCapture BoardImpl::CaptureSelection() {
return cursor_capturable_for_selection_.Capture();
}
void BoardImpl::Menu() {
if (!cursor_captured_for_menu_) {
if (input_->IsMousePressed(GLFW_MOUSE_BUTTON_2))
cursor_captured_for_menu_ = CaptureCursor();
if (!cursor_captured_for_menu_)
return;
menu_widget_->SetDimensions(menu_widget_->ComputeDimensions());
menu_widget_->SetPosition(cursor_);
}
if (menu_delegate_->Validate())
menu_widget_->SetDimensions(menu_widget_->ComputeDimensions());
bool clicked = menu_widget_->Step(input_, cursor_);
if (input_->IsCursorPressed() && !clicked)
cursor_captured_for_menu_.Invalidate();
}
JSON BoardImpl::Serialize() {
auto non_connected =
std::remove_if(connectors_.begin(), connectors_.end(),
[](const auto& x) { return !x->IsConnected(); });
connectors_.erase(non_connected, connectors_.end());
int slot_last = 0;
std::map<SlotImpl*, int> slot_index;
slot_index[nullptr] = -1;
JSON json;
json["nodes"] = JSON::array();
for (auto& node : nodes_) {
json["nodes"].push_back(node->Serialize());
for (auto& it : node->inputs())
slot_index[it.get()] = slot_last++;
for (auto& it : node->outputs())
slot_index[it.get()] = slot_last++;
}
json["connectors"] = JSON::array();
for (auto& connector : connectors_) {
json["connectors"].push_back(slot_index[connector->input()]);
json["connectors"].push_back(slot_index[connector->output()]);
}
return json;
}
#define CHECK(what) if (!(what)) return false;
bool BoardImpl::Deserialize(JSON& json) {
nodes_.clear();
connectors_.clear();
std::map<int, int> index;
for (int i = 0; i < (int)model_.nodes.size(); ++i)
index[model_.nodes[i].identifier] = i;
int slot_last = 0;
std::map<int, SlotImpl*> slot_ptr;
for (auto& node_json : json["nodes"]) {
auto& model_index = index[node_json["identifier"]];
auto* node = Create(model_.nodes[model_index]);
node->Deserialize(node_json);
for (auto& it : node->inputs())
slot_ptr[slot_last++] = it.get();
for (auto& it : node->outputs())
slot_ptr[slot_last++] = it.get();
}
auto it = json["connectors"].begin();
while (it != json["connectors"].end()) {
int A = *it; ++it;
if (it == json["connectors"].end()) return false;
int B = *it; ++it;
Connect(slot_ptr[A], slot_ptr[B]);
}
return true;
}
void BoardImpl::Connect(Slot* A, Slot* B) {
connectors_.push_back(std::make_unique<ConnectorImpl>(
static_cast<SlotImpl*>(A), static_cast<SlotImpl*>(B)));
}
} // namespace smkflow
<file_sep>/include/smkflow/widget/Box.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_BOX_HPP
#define SMKFLOW_WIDGET_BOX_HPP
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
// Constructor
WidgetFactory VBox(std::vector<WidgetFactory> children);
WidgetFactory HBox(std::vector<WidgetFactory> children);
// Interface
class BoxInterface {
public:
virtual Widget* ChildAt(int i) = 0;
virtual int ChildCount() = 0;
};
// Cast:
BoxInterface* Box(Widget*);
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_WIDGET_BOX_HPP */
<file_sep>/src/smkflow/SlotImpl.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_SLOT_HPP
#define SMKFLOW_SLOT_HPP
#include <glm/glm.hpp>
#include <smk/RenderTarget.hpp>
#include <smk/Text.hpp>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include <smkflow/NodeImpl.hpp>
namespace smkflow {
class ConnectorImpl;
class NodeImpl;
class SlotImpl : public Slot {
public:
SlotImpl(NodeImpl* node, std::string label, bool is_right, glm::vec4 color);
void SetPosition(const glm::vec2 position) { position_ = position; }
glm::vec2 ComputeDimensions();
void Draw(smk::RenderTarget* target);
glm::vec2 GetPosition();
bool ValidateDimensions();
void Connect(ConnectorImpl* connector_);
void Disconnect(ConnectorImpl* connector_);
bool IsRight();
glm::vec4 GetColor();
NodeImpl* node() { return node_; }
// Slot implementation:
void SetText(const std::string& text) override;
Node* GetNode() override;
Connector* GetConnector() override;
Slot* OppositeSlot() override;
Node* OppositeNode() override;
private:
bool dimensions_modified_ = false;
NodeImpl* const node_; // Owner;
glm::vec2 position_;
smk::Text label_;
std::string text_;
bool is_right_ = true;
glm::vec4 color_;
std::vector<ConnectorImpl*> connectors_;
};
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_SLOT_HPP */
<file_sep>/include/smkflow/widget/Label.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_LABEL_HPP
#define SMKFLOW_WIDGET_LABEL_HPP
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
WidgetFactory Label(const std::string& label);
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_WIDGET_LABEL_HPP \
*/
<file_sep>/third_party/CMakeLists.txt
include(FetchContent)
set(FETCHCONTENT_UPDATES_DISCONNECTED false)
# ------------------------------------------------------------------------------
FetchContent_Declare(smk
GIT_REPOSITORY https://github.com/ArthurSonzogni/smk
GIT_TAG 7dc4f36051037d1fa36eacbaf7bf48d96da2b872
)
FetchContent_Declare(fmt
GIT_REPOSITORY https://github.com/fmtlib/fmt
GIT_TAG 2cac8a9
)
FetchContent_Declare(json
#GIT_REPOSITORY https://github.com/nlohmann/json
GIT_REPOSITORY https://github.com/ArthurSonzogni/nlohmann_json_cmake_fetchcontent
GIT_TAG master)
# ------------------------------------------------------------------------------
FetchContent_GetProperties(smk)
FetchContent_GetProperties(fmt)
FetchContent_GetProperties(json)
if(NOT smk_POPULATED)
message(STATUS "populate SMK > Start")
FetchContent_Populate(smk)
message(STATUS "populate SMK > Done")
add_subdirectory(${smk_SOURCE_DIR} ${smk_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()
if(NOT fmt_POPULATED)
message(STATUS "populate fmt > Start")
FetchContent_Populate(fmt)
set(BUILD_SHARED_LIBS FALSE)
message(STATUS "populate fmt > Done")
add_subdirectory(
${fmt_SOURCE_DIR}
${fmt_BINARY_DIR}
EXCLUDE_FROM_ALL)
endif()
FetchContent_Declare(json
GIT_REPOSITORY https://github.com/nlohmann/json
GIT_TAG v3.7.3)
FetchContent_GetProperties(json)
if(NOT json_POPULATED)
message(STATUS "populate json > Start")
FetchContent_Populate(json)
message(STATUS "populate json > Done")
add_subdirectory( ${json_SOURCE_DIR} ${json_BINARY_DIR} EXCLUDE_FROM_ALL)
endif()
<file_sep>/src/smkflow/serialization_test.cpp
// the LICENSE file.
#include <gtest/gtest.h>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include "test.hpp"
using Serialization = Test;
using JSON = smkflow::JSON;
TEST_F(Serialization, BoardEmpty) {
auto model = smkflow::model::Board{{}, {}, font()};
auto board = smkflow::Board::Create(model);
JSON expected = {
{"nodes", JSON::array()},
{"connectors", JSON::array()},
};
JSON out = board->Serialize();
EXPECT_EQ(out, expected);
}
TEST_F(Serialization, NodeBasic) {
auto node_model = smkflow::model::Node{
113, //
"label", //
{1.0f, 0.8f, 0.6f, 0.4f}, //
{}, // Input.
{}, // Output.
{}, // Widget.
};
auto board_model = smkflow::model::Board{{node_model}, {}, font()};
auto board = smkflow::Board::Create(board_model);
auto node = board->Create(node_model);
node->SetPosition({42, 13});
JSON expected = {
{"nodes",
{
{
{"identifier", 113},
{"position", {42.f, 13.f}},
},
}},
{"connectors", JSON::array()},
};
JSON out = board->Serialize();
EXPECT_EQ(out, expected);
// We should be able to deserialize / serialize and get the same output.
{
auto board = smkflow::Board::Create(board_model);
board->Deserialize(out);
EXPECT_EQ(board->Serialize(), out);
}
}
TEST_F(Serialization, Connectors) {
auto white = glm::vec4(1.f, 1.f, 1.f, 1.f);
auto node_model = smkflow::model::Node{
0, //
"label", //
white,
// Input:
{
{"A", white},
{"B", white},
{"C", white},
},
// Output:
{
{"A", white},
{"B", white},
{"C", white},
},
{}, // Widget.
};
auto board_model = smkflow::model::Board{{node_model}, {}, font()};
auto board = smkflow::Board::Create(board_model);
auto node_1 = board->Create(node_model);
auto node_2 = board->Create(node_model);
auto node_3 = board->Create(node_model);
board->Connect(node_1->OutputAt(0), node_2->InputAt(1));
board->Connect(node_1->OutputAt(2), node_3->InputAt(0));
board->Connect(node_2->OutputAt(1), node_1->InputAt(2));
board->Connect(node_2->OutputAt(0), node_3->InputAt(1));
board->Connect(node_3->OutputAt(2), node_1->InputAt(0));
board->Connect(node_3->OutputAt(1), node_2->InputAt(1));
JSON expected = {
{"nodes",
{
{
{"identifier", 0},
{"position", {0.f, 0.f}},
},
{
{"identifier", 0},
{"position", {0.f, 0.f}},
},
{
{"identifier", 0},
{"position", {0.f, 0.f}},
},
}},
{"connectors", {5, 12, 10, 2, 9, 13, 17, 0, 16, 7}},
};
JSON out = board->Serialize();
EXPECT_EQ(out, expected);
// We should be able to deserialize / serialize and get the same output.
{
auto board = smkflow::Board::Create(board_model);
board->Deserialize(out);
EXPECT_EQ(board->Serialize(), out);
}
}
<file_sep>/src/smkflow/widget/BoxImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <algorithm>
#include <smkflow/Constants.hpp>
#include <smkflow/widget/BoxImpl.hpp>
namespace smkflow {
BoxImpl::BoxImpl(Delegate* delegate, std::vector<WidgetFactory> children)
: Widget(delegate) {
for (auto& it : children)
children_.push_back(it(delegate));
children_size_.resize(children_.size());
}
bool BoxImpl::Step(smk::Input* input, const glm::vec2& cursor) {
bool ret = false;
for (auto& it : children_)
ret |= it->Step(input, cursor);
if (ret)
return true;
return Widget::Step(input, cursor);
}
void BoxImpl::Draw(smk::RenderTarget* target) {
for (auto& child : children_)
child->Draw(target);
}
Widget* BoxImpl::ChildAt(int i) {
return children_.at(i).get();
}
int BoxImpl::ChildCount() {
return children_.size();
}
JSON BoxImpl::Serialize() {
JSON json = JSON::array();
for (auto& child : children_)
json.push_back(child->Serialize());
return json;
}
bool BoxImpl::Deserialize(JSON& json) {
int i = 0;
bool ret = true;
for (auto& child : children_)
ret &= child->Deserialize(json[i++]);
return ret;
}
BoxImplVertical::BoxImplVertical(Delegate* delegate,
std::vector<WidgetFactory> children)
: BoxImpl(delegate, children) {}
glm::vec2 BoxImplVertical::ComputeDimensions() {
requested_dimensions_ = glm::vec2(0.f, 0.f);
int i = 0;
for (auto& it : children_) {
auto child_dimension = it->ComputeDimensions();
requested_dimensions_.x =
std::max(requested_dimensions_.x, child_dimension.x);
requested_dimensions_.y += child_dimension.y;
children_size_[i++] = child_dimension.y;
}
if (children_.size())
requested_dimensions_ += (children_.size() - 1) * size::widget_margin;
return requested_dimensions_;
}
void BoxImplVertical::SetDimensions(glm::vec2 dimensions) {
Widget::SetDimensions(dimensions);
float space_left = dimensions.y - requested_dimensions_.y;
space_left /= children_.size();
int i = 0;
for (auto& it : children_)
it->SetDimensions({dimensions.x, children_size_[i++] + space_left});
}
void BoxImplVertical::SetPosition(glm::vec2 position) {
Widget::SetPosition(position);
for (auto& it : children_) {
it->SetPosition(position);
position.y += it->dimensions().y + size::widget_margin;
}
}
BoxImplHorizontal::BoxImplHorizontal(Delegate* delegate,
std::vector<WidgetFactory> children)
: BoxImpl(delegate, children) {}
glm::vec2 BoxImplHorizontal::ComputeDimensions() {
requested_dimensions_ = glm::vec2(0.f, 0.f);
int i = 0;
for (auto& it : children_) {
auto child_dimension = it->ComputeDimensions();
requested_dimensions_.y =
std::max(requested_dimensions_.y, child_dimension.y);
requested_dimensions_.x += child_dimension.x;
children_size_[i++] = child_dimension.x;
}
if (children_.size())
requested_dimensions_ += (children_.size() - 1) * size::widget_margin;
return requested_dimensions_;
}
void BoxImplHorizontal::SetDimensions(glm::vec2 dimensions) {
Widget::SetDimensions(dimensions);
float space_left = dimensions.x - requested_dimensions_.x;
space_left /= children_.size();
int i = 0;
for (auto& it : children_)
it->SetDimensions({children_size_[i++] + space_left, dimensions.y});
}
void BoxImplHorizontal::SetPosition(glm::vec2 position) {
Widget::SetPosition(position);
for (auto& it : children_) {
it->SetPosition(position);
position.x += it->dimensions().x + size::widget_margin;
}
}
// static
WidgetFactory HBox(std::vector<WidgetFactory> children) {
return [=](Widget::Delegate* delegate) {
return std::make_unique<BoxImplHorizontal>(delegate, children);
};
}
// static
WidgetFactory VBox(std::vector<WidgetFactory> children) {
return [=](Widget::Delegate* delegate) {
return std::make_unique<BoxImplVertical>(delegate, children);
};
}
// static
BoxInterface* Box(Widget* w) {
return dynamic_cast<BoxInterface*>(w);
}
} // namespace smkflow
<file_sep>/include/smkflow/Elements.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_ELEMENT_HPP
#define SMKFLOW_ELEMENT_HPP
#include <memory>
#include <smk/Input.hpp>
#include <smk/RenderTarget.hpp>
#include <smkflow/Model.hpp>
#include <smkflow/JSON.hpp>
namespace smkflow {
class Board;
class Node;
class Slot;
class Connector;
class Widget;
class Board {
public:
static std::unique_ptr<Board> Create(const model::Board&);
virtual ~Board() = default;
// Called 60/s for animations:
virtual void Step(smk::RenderTarget* target, smk::Input* input) = 0;
// Called for producing a new image:
virtual void Draw(smk::RenderTarget* target) = 0;
// Modifier;
virtual Node* Create(const model::Node&) = 0;
virtual void Connect(Slot* A, Slot* B) = 0;
// Observers:
virtual int NodeCount() = 0;
virtual Node* NodeAt(int i) = 0;
// Used by widget to keep the cursor for it.
virtual CursorCapture CaptureCursor() = 0;
// Serialization:
virtual JSON Serialize() = 0;
virtual bool Deserialize(JSON& in) = 0;
};
class Slot {
public:
virtual ~Slot() = default;
virtual Connector* GetConnector() = 0;
virtual Slot* OppositeSlot() = 0;
virtual Node* GetNode() = 0;
virtual Node* OppositeNode() = 0;
virtual void SetText(const std::string& text) = 0;
};
class Connector {
public:
virtual ~Connector() = default;
virtual Slot* GetInput() = 0;
virtual Slot* GetOutput() = 0;
};
class Node {
public:
virtual ~Node() = default;
virtual Board* GetBoard() = 0;
virtual int Identifier() = 0;
virtual void SetPosition(const glm::vec2&) = 0;
virtual int InputCount() = 0;
virtual Slot* InputAt(int i) = 0;
virtual int OutputCount() = 0;
virtual Slot* OutputAt(int i) = 0;
virtual Widget* widget() = 0;
};
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_ELEMENT_HPP */
<file_sep>/src/smkflow/widget/InputImpl.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <algorithm>
#include <smk/Input.hpp>
#include <smk/RenderTarget.hpp>
#include <smk/Shape.hpp>
#include <smk/Text.hpp>
#include <smkflow/BoardImpl.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/widget/Input.hpp>
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
class InputImpl : public Widget, public InputInterface {
public:
InputImpl(Delegate* delegate,
const std::string& placeholder,
const std::string& value)
: Widget(delegate), placeholder_(placeholder), input_(value) {
square_ = smk::Shape::Square();
square_.SetScale({128.f, 32.f});
SetText();
}
void SetText() {
text_ =
smk::Text(delegate()->Font(), input_.empty() ? placeholder_ : input_);
text_.SetColor(input_.empty() ? glm::vec4(0.5f, 0.5f, 0.5f, 1.f)
: glm::vec4(1.f, 1.f, 1.f, 1.f));
computed_dimensions_ = text_.ComputeDimensions();
computed_dimensions_.y =
std::max(computed_dimensions_.y, size::widget_height);
InvalidateLayout();
}
// Widget implementation:
glm::vec2 ComputeDimensions() override { return computed_dimensions_; }
bool Step(smk::Input* input, const glm::vec2& cursor) override {
auto position = cursor - Position();
hover_ = (position.x >= 0.f && position.y >= 0.f &&
position.x <= dimensions().x && position.y <= dimensions().y);
if (input->IsCursorPressed())
focus_ = false;
if (input->IsCursorReleased() && hover_) {
character_listener_ = input->MakeCharacterListener();
focus_ = true;
cursor_position_ = 0;
for (cursor_position_ = 0; cursor_position_ < (int)input_.size();
++cursor_position_) {
auto subtext =
smk::Text(delegate()->Font(), input_.substr(0, cursor_position_));
auto dim = subtext.ComputeDimensions();
if (3.f + dim.x > position.x)
break;
}
}
if (focus_) {
bool modified = false;
wchar_t character;
while (character_listener_->Receive(&character)) {
input_.insert(cursor_position_++, 1, character);
modified = true;
}
if (CheckKey(GLFW_KEY_BACKSPACE, &backspace_repeat, input)) {
if (cursor_position_ >= 1) {
input_.erase(--cursor_position_, 1);
modified = true;
}
}
if (modified)
SetText();
if (CheckKey(GLFW_KEY_LEFT, &left_repeat, input))
cursor_position_ = std::max(0, cursor_position_ - 1);
if (CheckKey(GLFW_KEY_RIGHT, &right_repeat, input))
cursor_position_ = std::min((int)input_.size(), cursor_position_ + 1);
}
return hover_ && input->IsCursorPressed();
}
void Draw(smk::RenderTarget* target) override {
auto position = Position();
auto dimension = dimensions();
square_.SetPosition(position);
square_.SetScale(dimension);
square_.SetColor(focus_ ? color::widget_background_focus
: hover_ ? color::widget_background_hover
: color::widget_background);
target->Draw(square_);
text_.SetPosition(
position +
glm::vec2(3.f, dimension.y * 0.5f - computed_dimensions_.y * 0.5f));
target->Draw(text_);
if (focus_) {
auto subtext =
smk::Text(delegate()->Font(), input_.substr(0, cursor_position_));
auto dim = subtext.ComputeDimensions();
square_.SetScale({1.f, dim.y});
square_.SetPosition({position.x + dim.x + 3.f, position.y});
square_.SetColor({1.f, 1.f, 1.f, 1.f});
target->Draw(square_);
}
}
void SetValue(const std::string& value) override {
if (input_ == value)
return;
input_ = value;
cursor_position_ = input_.size();
SetText();
}
bool CheckKey(int key, int* repeat, smk::Input* input) {
if (input->IsKeyPressed(key))
return true;
if (!input->IsKeyHold(key)) {
*repeat = 0;
return false;
}
(*repeat)++;
if (*repeat <= 20)
return false;
if (*repeat % 3)
return false;
return true;
}
const std::string& GetValue() override { return input_; }
JSON Serialize() override {
JSON json;
json["input"] = input_;
return json;
}
bool Deserialize(JSON& json) override {
SetValue(json["input"]);
return true;
}
private:
glm::vec2 computed_dimensions_;
int backspace_repeat = 0;
int left_repeat = 0;
int right_repeat = 0;
int cursor_position_ = 0;
bool focus_ = false;
bool hover_ = false;
smk::Text text_;
std::string placeholder_;
std::string input_;
smk::Transformable square_;
smk::Input::CharacterListener character_listener_;
};
// static
WidgetFactory Input(const std::string& placeholder,
const std::string& initial_value) {
return [placeholder, initial_value](Widget::Delegate* delegate) {
return std::make_unique<InputImpl>(delegate, placeholder, initial_value);
};
}
InputInterface* Input(Widget* w) {
return dynamic_cast<InputInterface*>(w);
}
} // namespace smkflow
<file_sep>/examples/minimal.cpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#include <smk/Window.hpp>
#include <smkflow/Constants.hpp>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include "asset.hpp"
enum Node { A, B };
auto blue = glm::vec4(0.3, 0.3, 0.8, 1.0);
auto red = glm::vec4(0.8, 0.3, 0.3, 1.0);
auto green = glm::vec4(0.3, 0.8, 0.3, 1.0);
auto node_A = smkflow::model::Node{
Node::A,
"Transposition",
blue,
// Input:
{
{"a", blue},
{"b", red},
},
// Output:
{
{"b", red},
{"a", blue},
},
};
auto my_board = smkflow::model::Board{
// Node list:
{
node_A,
},
// Contextual menu:
{},
// Font to be used:
asset::arial_ttf,
};
int main() {
auto window = smk::Window(512, 512, "test");
auto board = smkflow::Board::Create(my_board);
// Instanciate some Node based on the model.
board->Create(node_A)->SetPosition({-120, 0});
board->Create(node_A)->SetPosition({+120, 0});
board->Create(node_A)->SetPosition({+0, +120});
window.ExecuteMainLoop([&] {
window.Clear(smkflow::color::background);
window.PoolEvents();
board->Step(&window, &window.input());
board->Draw(&window);
window.Display();
});
return EXIT_SUCCESS;
}
<file_sep>/include/smkflow/widget/Menu.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_MENU_HPP
#define SMKFLOW_WIDGET_MENU_HPP
#include <smkflow/widget/Action.hpp>
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
/// Usage:
/// ~~~cpp
/// Menu("Main", {
/// Menu("File", {
/// MenuEntry("Open", Open),
/// MenuEntry("Save", Save),
/// MenuEntry("Quit", Quit),
/// });
/// Menu("Display", {
/// MenuEntry("Bar", Bar),
/// });
/// });
/// ~~~
WidgetFactory MenuEntry(const std::string& label, Action);
WidgetFactory Menu(const std::string& label,
std::vector<WidgetFactory> children);
} // namespace smkflow
#endif // end of include guard: SMKFLOW_WIDGET_MENU_HPP
<file_sep>/include/smkflow/widget/Input.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_INPUTBOX_HPP
#define SMKFLOW_WIDGET_INPUTBOX_HPP
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
// Constructor:
WidgetFactory Input(const std::string& placeholder,
const std::string& input = "");
// Interface:
class InputInterface {
public:
virtual void SetValue(const std::string& value) = 0;
virtual const std::string& GetValue() = 0;
};
// Cast:
InputInterface* Input(Widget*);
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_WIDGET_INPUTBOX_HPP*/
<file_sep>/include/smkflow/Model.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_MODEL_HPP
#define SMKFLOW_MODEL_HPP
#include <glm/glm.hpp>
#include <smkflow/widget/Widget.hpp>
#include <string>
#include <vector>
namespace smkflow {
namespace model {
struct Slot {
std::string label;
glm::vec4 color;
};
struct Node {
int identifier;
std::string label;
glm::vec4 color;
std::vector<Slot> input;
std::vector<Slot> output;
WidgetFactory widget;
};
struct Board {
std::vector<Node> nodes;
std::vector<WidgetFactory> context_widgets_;
std::string font;
};
} // namespace model
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_MODEL_HPP */
<file_sep>/src/smkflow/ConnectorImpl.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_CONNECTOR_HPP
#define SMKFLOW_CONNECTOR_HPP
#include <smk/RenderTarget.hpp>
#include <smk/Transformable.hpp>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
namespace smkflow {
class SlotImpl;
class ConnectorImpl : public Connector {
public:
ConnectorImpl(SlotImpl* A, SlotImpl* B);
~ConnectorImpl();
bool IsConnected();
void Disconnect();
void DrawForeground(smk::RenderTarget* target);
void DrawBackground(smk::RenderTarget* target);
SlotImpl* input() { return input_; }
SlotImpl* output() { return output_; }
// Connector implementations:
Slot* GetInput() override;
Slot* GetOutput() override;
private:
void RebuildVertex();
SlotImpl* input_ = nullptr;
SlotImpl* output_ = nullptr;
smk::Transformable background_;
smk::Transformable foreground_;
glm::vec2 position_a_ = glm::vec2(0.f, 0.f);
glm::vec2 position_b_ = glm::vec2(0.f, 0.f);
};
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_CONNECTOR_HPP */
<file_sep>/src/smkflow/BoardImpl.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef EDITOR_BOARD_HPP
#define EDITOR_BOARD_HPP
#include <smk/Font.hpp>
#include <smkflow/CursorCapture.hpp>
#include <smkflow/Elements.hpp>
#include <smkflow/Model.hpp>
#include <smkflow/NodeImpl.hpp>
namespace smkflow {
class ConnectorImpl;
class SlotImpl;
class NodeImpl;
class BoardImpl : public Board {
public:
BoardImpl(const model::Board& model);
~BoardImpl();
SlotImpl* FindSlot(const glm::vec2& position);
smk::Font& font() { return font_; }
// Board implementations:
NodeImpl* Create(const model::Node&) override;
void Step(smk::RenderTarget* target, smk::Input* input) override;
void Draw(smk::RenderTarget* target) override;
int NodeCount() override { return nodes_.size(); }
NodeImpl* NodeAt(int i) override { return nodes_.at(i).get(); }
CursorCapture CaptureCursor() override;
CursorCapture CaptureSelection();
void Connect(Slot* A, Slot* B) override;
JSON Serialize() override;
bool Deserialize(JSON&) override;
private:
void PushNodeAppart();
// Move / Zoom the view ------------------------------------------------------
void AcquireView();
void MoveView();
void ReleaseView();
CursorCapture cursor_captured_for_dragging_view_;
glm::vec2 grab_point_ = {0.f, 0.f};
glm::vec2 view_shifting_ = {0.f, 0.f};
float view_zoom_ = 0.f;
// Build connectors in between nodes -----------------------------------------
void AquireConnector();
void MoveConnector();
void ReleaseConnector();
// Right click ---------------------------------------------------------------
void Menu();
std::unique_ptr<Widget> menu_widget_;
CursorCapture cursor_captured_for_menu_;
smk::Transformable square_;
glm::vec2 connector_in_;
glm::vec2 connector_in_pushed_;
glm::vec2 connector_out_pushed_;
glm::vec2 connector_out_;
SlotImpl* start_slot_ = nullptr;
CursorCapture cursor_captured_for_connector_;
// ---------------------------------------------------------------------------
std::vector<std::unique_ptr<NodeImpl>> nodes_;
std::vector<std::unique_ptr<ConnectorImpl>> connectors_;
smk::Font font_;
CursorCapturable cursor_capturable_ = {1};
CursorCapturable cursor_capturable_for_selection_ = {9999};
smk::Input* input_;
glm::vec2 cursor_;
float push_ = 0.f;
class MenuDelegate;
std::unique_ptr<MenuDelegate> menu_delegate_;
friend class MenuDelegate;
model::Board model_;
int selection_id_ = 0;
};
} // namespace smkflow
#endif /* end of include guard: EDITOR_BOARD_HPP */
<file_sep>/include/smkflow/CursorCapture.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_CURSOR_CAPTURE_HPP
#define SMKFLOW_CURSOR_CAPTURE_HPP
#include <set>
namespace smkflow {
class CursorCapture;
class CursorCapturable;
class CursorCapture {
public:
CursorCapture();
CursorCapture(CursorCapturable* ref);
explicit operator bool();
// Move-only
CursorCapture(const CursorCapture&&) = delete;
CursorCapture(CursorCapture&& o);
void operator=(const CursorCapture&) = delete;
void operator=(CursorCapture&& o);
void Invalidate();
virtual ~CursorCapture();
void Swap(CursorCapture& other);
private:
CursorCapturable* ref_ = nullptr;
};
class CursorCapturable {
public:
CursorCapturable(int capacity = 1);
~CursorCapturable();
CursorCapture Capture();
void Invalidate();
explicit operator bool();
private:
friend CursorCapture;
int capacity_ = 0;
std::set<CursorCapture*> set_;
};
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_CURSOR_CAPTURE_HPP */
<file_sep>/include/smkflow/JSON.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_JSON_HPP
#define SMKFLOW_JSON_HPP
#include <nlohmann/json.hpp>
namespace smkflow {
using JSON = nlohmann::json;
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_JSON_HPP */
<file_sep>/include/smkflow/widget/Slider.hpp
// Copyright 2020 <NAME>. All rights reserved.
// Use of this source code is governed by the MIT license that can be found in
// the LICENSE file.
#ifndef SMKFLOW_WIDGET_SLIDER_HPP
#define SMKFLOW_WIDGET_SLIDER_HPP
#include <smkflow/widget/Widget.hpp>
namespace smkflow {
// Constructor
WidgetFactory Slider(float min = 0.f,
float max = 100.f,
float value = 50.f,
std::string format = "{:.0f}%"); // Use fmt lib.
// Interface
class SliderInterface {
public:
virtual void SetValue(float) = 0;
virtual float GetValue() = 0;
};
// Cast
SliderInterface* Slider(Widget*);
} // namespace smkflow
#endif /* end of include guard: SMKFLOW_WIDGET_SLIDER_HPP \
*/
|
e504525561eeaa3122c7e78a213c0026955ffc8a
|
[
"Markdown",
"CMake",
"C++"
] | 40 |
C++
|
zwjin1210/smkflow
|
c7d4b887881b51130add6f358abd2612a41c4db7
|
c613fe189a8b1f540fc5ef116986111518579c73
|
refs/heads/master
|
<repo_name>mstykt/generics<file_sep>/src/main/java/com/generics/GenericMethods.java
package com.generics;
/**
* Created by mesut on 25.07.2016.
*/
public class GenericMethods {
public static void main(String[] args) {
PrintSometing print = new PrintSometing();
print.printData("hello world!");
print.printData(50);
System.out.println(print.something("asdads"));
}
}
/*
Burada dikkat edilmesi gereken nokta ลudur ki;
Generik T kullanฤฑldฤฑฤฤฑnda baฤlฤฑ bulunduฤu scope a gรถre method yada class tanฤฑmฤฑnda da tanฤฑmlanmalฤฑdฤฑr.
Sฤฑnฤฑflar iรงin sadece deฤiลkenler iรงin kullanฤฑldฤฑฤฤฑnda!
รrneฤin T parametresi sฤฑnฤฑf iรงin kullanฤฑlan bir deฤiลkense sฤฑnฤฑf tanฤฑmฤฑna <T> eklenmeli
aynฤฑ ลekilde method iรงinde kullanฤฑlacak deฤiลkenler iรงinde method imzasฤฑna <T> eklenmeli.
*/
class PrintSometing {
public <T> void printData(T data) {
System.out.println(data.toString());
}
public <T> T something(T data) {
return data;
}
}
|
f54fe0e28ec0bb031e6f1b593f02a50f86dbd20d
|
[
"Java"
] | 1 |
Java
|
mstykt/generics
|
c30d7707e4dfabd78e025bad6f3e6842f7392146
|
66b4b364619cb19b4147b16086161e0a8ec491f5
|
refs/heads/master
|
<repo_name>larynxmith/bracket-matcher<file_sep>/solution.py
# def bracket_matcher(input):
# while len(input) > 0:
# check_string = ''
# if input[0] == '(':
# print('hi')
# if input[len(input) -1] == ')':
# print('MATCHED')
# check_string = input(1, len(input) -1)
# bracket_matcher(check_string)
# elif input[len(input) - 1] == '' or input[len(input) - 1] == '}':
# print('Missing closing Parens')
# return False
# if input[0] != '[' or input[0] != '{' or input[0] != '(':
# check_string = input[1:]
# print(check_string)
# bracket_matcher(check_string)
# return
# return True
open_brackets = ['(', '[', '{']
close_brackets = [')', ']', '}']
# def bracket_matcher(input):
# open_bracket_list = []
# for i in range(len(input)):
# if input[i] in open_brackets:
# open_bracket_list.append(input[i])
# print(open_bracket_list)
# return open_bracket_list
# def bracket_matcher(input):
# check_list = bracket_reducer(input)
# for i in range(len(check_list)):
# if len(check_list) == 0:
# return True
# elif check_list[i] in close_brackets or len(check_list) % 2 != 0:
# return False
# if check_list[i + 1] in close_brackets and open_brackets.index(check_list[i]) == close_brackets.index(check_list[i + 1]):
# check_list =
def bracket_matcher(input):
open_bracket_list =[]
for char in input:
if char in open_brackets:
open_bracket_list.append(char)
print(open_bracket_list)
elif char in close_brackets:
if len(open_bracket_list) > 0 and open_bracket_list[len(open_bracket_list) - 1] == open_brackets[close_brackets.index(char)]:
open_bracket_list.pop()
print(open_bracket_list)
else:
print('False')
return False
if len(open_bracket_list) == 0:
print('True')
return True
else:
print('False')
return False
bracket_matcher('abc(123)')
# returns true
bracket_matcher('a[b]c(123')
# returns false -- missing closing parens
bracket_matcher('a[bc(123)]')
# returns true
bracket_matcher('a[bc(12]3)')
# returns false -- improperly nested
bracket_matcher('a{b}{c(1[2]3)}')
# returns true
bracket_matcher('a{b}{c(1}[2]3)')
# returns false -- improperly nested
bracket_matcher('()')
# returns true
bracket_matcher('[]]')
# returns false - no opening bracket to correspond with last character
bracket_matcher('abc123yay')
# returns true -- no brackets = correctly matched
|
cc474b5487d1259a19569c97a95ca546ab84bf65
|
[
"Python"
] | 1 |
Python
|
larynxmith/bracket-matcher
|
682036233311110813dc22c7ed2dc90b7300104d
|
2e23b49e7c85fdeab0b6f84568b6309be76ef497
|
refs/heads/master
|
<repo_name>joeblew99/printing<file_sep>/pdf/pdf-to-raster/cmd/watermark/Makefile
dep:
brew install --with-ghostscript imagemagick
magick --version
run:
GO111MODULE=on go run main.go<file_sep>/print/google/try/listprinter/main.go
// Copyright 2016 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// print command prints text documents to selected printer.
package main
import (
"flag"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"github.com/alexbrainman/printer"
)
var (
copies = flag.Int("n", 1, "number of copies to print")
printerId = flag.String("p", findDefaultPrinter(), "printer name or printer index from printer list")
doList = flag.Bool("l", false, "list printers")
)
func findDefaultPrinter() string {
p, err := printer.Default()
if err != nil {
return ""
}
return p
}
func listPrinters() error {
printers, err := printer.ReadNames()
if err != nil {
return err
}
defaultPrinter, err := printer.Default()
if err != nil {
return err
}
for i, p := range printers {
s := " "
if p == defaultPrinter {
s = "*"
}
fmt.Printf(" %s %d. %s\n", s, i, p)
}
return nil
}
func selectPrinter() (string, error) {
n, err := strconv.Atoi(*printerId)
if err != nil {
// must be a printer name
return *printerId, nil
}
printers, err := printer.ReadNames()
if err != nil {
return "", err
}
if n < 0 {
return "", fmt.Errorf("printer index (%d) cannot be negative", n)
}
if n >= len(printers) {
return "", fmt.Errorf("printer index (%d) is too large, there are only %d printers", n, len(printers))
}
return printers[n], nil
}
func printOneDocument(printerName, documentName string, lines []string) error {
p, err := printer.Open(printerName)
if err != nil {
return err
}
defer p.Close()
err = p.StartDocument(documentName, "RAW")
if err != nil {
return err
}
defer p.EndDocument()
err = p.StartPage()
if err != nil {
return err
}
for _, line := range lines {
fmt.Fprintf(p, "%s\r\n", line)
}
return p.EndPage()
}
func printDocument(path string) error {
if *copies < 0 {
return fmt.Errorf("number of copies to print (%d) cannot be negative", *copies)
}
output, err := ioutil.ReadFile(path)
if err != nil {
return err
}
lines := strings.Split(string(output), "\n")
printerName, err := selectPrinter()
if err != nil {
return err
}
for i := 0; i < *copies; i++ {
err := printOneDocument(printerName, path, lines)
if err != nil {
return err
}
}
return nil
}
func usage() {
fmt.Fprintln(os.Stderr)
fmt.Fprintf(os.Stderr, "usage: print [-n=<copies>] [-p=<printer>] <file-path-to-print>\n")
fmt.Fprintf(os.Stderr, " or\n")
fmt.Fprintf(os.Stderr, " print -l\n")
fmt.Fprintln(os.Stderr)
flag.PrintDefaults()
os.Exit(1)
}
func exit(err error) {
if err != nil {
fmt.Fprintf(os.Stderr, "%v\n", err)
os.Exit(1)
}
os.Exit(0)
}
func main() {
flag.Usage = usage
flag.Parse()
if *doList {
exit(listPrinters())
}
switch len(flag.Args()) {
case 0:
fmt.Fprintf(os.Stderr, "no document path to print provided\n")
case 1:
exit(printDocument(flag.Arg(0)))
default:
fmt.Fprintf(os.Stderr, "too many parameters provided\n")
}
usage()
}
<file_sep>/pdf/html-to-pdf/github.com/SebastiaanKlippert/go-wkhtmltopdf/Makefile
# github.com/SebastiaanKlippert/go-wkhtmltopdf
GOCMD=go
NAME=go-wkhtmltopdf
LIB=github.com/SebastiaanKlippert/$(NAME)
LIB_FSPATH=$(GOPATH)/src/$(LIB)
print:
@echo
@echo NAME :$(NAME)
@echo LIB :$(LIB)
@echo LIB_FSPATH : $(LIB_FSPATH)
@echo
dep-all: dep-os dep dep-modules
# get all deps
dep-os:
# get the binary (https://github.com/wkhtmltopdf/wkhtmltopdf/releases)
# did it manually for now.
chmod +x $(PWD)/bin/wkhtmltox-0.12.5-1.macos-cocoa.pkg
dep:
## install on gopath
mkdir -p $(LIB_FSPATH)
cd $(LIB_FSPATH) && cd .. && rm -rf $(NAME) && git clone https://$(LIB).git
dep-modules:
# theirs
cd $(LIB_FSPATH) && make deps
code:
code $(LIB_FSPATH)
clean:
# gopath
rm -rf $(LIB_FSPATH)
### Dev Tools
linters-install:
$(GOCMD) get -u github.com/alecthomas/gometalinter
gometalinter --install
lint: linters-install
cd $(LIB_FSPATH) && gometalinter --vendor --disable-all --enable=vet --enable=vetshadow --enable=golint --enable=maligned --enable=megacheck --enable=ineffassign --enable=misspell --enable=errcheck --enable=goconst ./...
test:
cd $(LIB_FSPATH) && $(GOCMD) test -cover -race ./...
bench:
cd $(LIB_FSPATH) && $(GOCMD) test -bench=. -benchmem ./...
### Metrics
qlog:
# for debugging...
tail -f $(TMPDIR)/q
#### Build
run:
go run main.go
build:
go build main.go
<file_sep>/pdf/viewer/readme.md
# pdf viewer
Mobile
https://github.com/albo1337/flutter_full_pdf_viewer
- android and ios
-Has share button to allow printing.
Desktop
Open on Native Peview app , so they can print
- We need to allow the user to select the Paper Format and Orientation, and then render the PDF again.
https://github.com/DavBfr/dart_pdf/issues/63
Then send to the normal Native PDF viewer and they print.
<file_sep>/pdf/viewer/epub/readme.md
# epub
Seems to support HTML being part of it !
- SO easy for HTML driving it.
<file_sep>/print/readme.md
# Print on Desktop
easy.
https://github.com/google/cloud-print-connector
DEUGGER for Cloud Print
https://www.google.com/cloudprint/simulate.html
https://github.com/alexbrainman/printer
- Windows only
https://github.com/go-flutter-desktop/go-flutter/issues/64
- all the native stuff
<file_sep>/pdf/pdf-to-raster/Makefile
## https://github.com/catherinelu/evangelist
LIB_NAME=evangelist
LIB=github.com/catherinelu/$(LIB_NAME)
LIB_PATH=$(GOPATH)/src/$(LIB)
LIB_DOC=https://$(LIB)
help: ## Display this help
# from: https://suva.sh/posts/well-documented-makefiles/
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n\nTargets:\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-10s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)
print:
@echo
@echo /PDFV pdfveek
@echo 'LIB_NAME $(LIB_NAME)'
@echo 'LIB $(LIB)'
@echo 'LIB_PATH $(LIB_PATH)'
@echo 'LIB_DOC $(LIB_DOC)'
@echo
git-clone: git-clone ### git-clone
# all
git-clean: git-clean ### git-clean
# all
git-clone: ### git-clone
mkdir -p $(LIB_PATH)
cd $(LIB_PATH) && cd .. && rm -rf $(LIB_NAME) && git clone ssh://git@$(LIB).git
git-clean: ### git-clean
rm -rf $(LIB_PATH)
doc-open: ### doc-open
open $(LIB_DOC)
code-open: ### code-open
code $(LIB_PATH)
go-run: ### flu-mob-run
cd $(LIB_PATH)/example && Flutter run -d all
<file_sep>/pdf/html-to-pdf/github.com/SebastiaanKlippert/go-wkhtmltopdf/main.go
package main
import (
"fmt"
"log"
"github.com/SebastiaanKlippert/go-wkhtmltopdf"
)
func main() {
ExampleNewPDFGenerator()
}
func ExampleNewPDFGenerator() {
// Create new PDF generator
wkhtmltopdf.SetPath("/Users/apple/workspace/go/src/bitbucket.org/gedw99/afira/client/flutter/pdf/print/github.com/SebastiaanKlippert/go-wkhtmltopdf/bin/wkhtmltox-0.12.5-1.macos-cocoa.pkg")
pdfg, err := wkhtmltopdf.NewPDFGenerator()
if err != nil {
log.Fatal(err)
}
// Set global options
pdfg.Dpi.Set(300)
pdfg.Orientation.Set(wkhtmltopdf.OrientationLandscape)
pdfg.Grayscale.Set(true)
// Create a new input page from an URL
page := wkhtmltopdf.NewPage("https://godoc.org/github.com/SebastiaanKlippert/go-wkhtmltopdf")
// Set options for this page
page.FooterRight.Set("[page]")
page.FooterFontSize.Set(10)
page.Zoom.Set(0.95)
// Add to document
pdfg.AddPage(page)
// Create PDF document in internal buffer
err = pdfg.Create()
if err != nil {
log.Fatal(err)
}
// Write buffer contents to file on disk
err = pdfg.WriteFile("./simplesample.pdf")
if err != nil {
log.Fatal(err)
}
fmt.Println("Done")
// Output: Done
}
<file_sep>/pdf/readme.md
# pdf
SO pipeline is:
HTML --> FL Widgets --> FL PDF
- If not using HTML its all fine.
If there is a way to use zephyr to write any doc then great, but getting that to PDF using Flutter is not so easy.
There many be a need for using golang to make PDF's from PDF Templates
https://github.com/unidoc/unidoc-examples/tree/v3
- Looks very powerful now.
- zephyr is for generate Front end RTE, but maybe UniDoc can help with pre-setup templates and merging.
https://github.com/memspace/zefyr/pull/59
- Converts the Quill --> HTML. Ok this is great
- Now just need to write a QUILL --> PDF using the PDF lib. It MIGHT make sense to take the HTML and then convert that to PDF !!
- Why because HTML will drive the whole thing later and so then we are sorted...
- SO just write a HTML to PDF ( https://github.com/DavBfr/dart_pdf)
We want a unidirectional Rendering
HTML is per widget. Like Web Custom Elements
- Flutter ONYL gets the data and then turns it into pure Flutter
Printing is to take a screen shot and so its raster
- From the pure Flutter, we take a screen shot and embed it inside a PDF
- From there the Raster is injected inside a PDF, and ten send off to the Native PDF Preview for Printing
The other way is to write a PDF Rendered for each widget, instead of just taking a screen shot
- We DONT have to compose many Widgets together if we use this approahc because for business apps you never want to do that.
- Data View is a list, and you dont want any other shit on the screen. Same with Forms
- Reporting View with lots of Charts and Tables on it is a single Widget. In fact you would be better off Rendering to PDF; and then showing that as the Flutter Widget
- RTE, if a tough one. But the best way is to Write a PDF renderer that understands the Quill format. Or wimp out and take a screen shot.
- Cal, i think its reasonable to write a PDF rendrer. Its likely that the PDF version looks different anyway.
The only issue is that the Print Format is not known until you get to the PDF Printing stage
- Instead you want to ask the Print size before hand, and render the Screenshot using:
- The required DPI for the Paper size
- The orientation ( Landscape or Portrait)
The Solution is to have a Flutter PDF Viewer, where the user selects the Paper format and based on that we re-render the PDF.
- It should be a matter of just making each Widgets PDF Rendered parametric for Landscape or portrait, and Paper size.
- We wont be able to know the potential Printer formats they have because we cant access that info easily, but thats ok, because:
- the main thing is if its Portrait or Landscape
- The Paper size chosen later wont matter because its Vector anyway and so will scale up fine.
---
golang libs
https://github.com/jung-kurt/gofpdf
- zero dependencies
what i need:
- convert to raster
- protect ( pass phrase) for sending to someone
- anoate and save
- templating ( for printing)
- i will maybe have to parse FLUTTER OR HTML and then pump to the PDF:
- or a screen shot
## Printing
Well thats the next challenge.
IF i have HTML.
1.
Use Chrome embedded to do HTML to PDF
https://medium.com/compass-true-north/go-service-to-convert-web-pages-to-pdf-using-headless-chrome-5fd9ffbae1af
https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF
- that will work !!
2. Use wkhtmltopdf
https://github.com/wkhtmltopdf/wkhtmltopdf/releases
golang wrapper
https://github.com/SebastiaanKlippert/go-wkhtmltopdf
## Process Manager
https://github.com/Unitech/pm2
- its nodeJS but seems to work !
<file_sep>/print/google/Makefile
GO111MODULE=on
NAME=cloud-print-connector
LIB=github.com/google/$(NAME)
LIB_FSPATH=$(GOPATH)/src/$(LIB)
git-clone:
go get github.com/google/cloud-print-connector/...
#mkdir -p $(LIB_FSPATH)
#cd $(LIB_FSPATH) && cd .. && rm -rf $(NAME) && git clone ssh://git@$(LIB).git
git-clean:
rm -rf $(LIB_FSPATH)
code:
code $(LIB_FSPATH)
build:
cd $(LIB_FSPATH) && go build -o $(PWD)/bin/print .
run-util:
# 1. init to make a config
gcp-connector-util
run-conn:
# 2 Run with the config
gcp-cups-connector --config-filename $(PWD)/gcp-cups-connector.config.json --log-to-console
tail-log:
tail -f /tmp/cloud-print-connector
send-job:
try-listprinter:
cd $(PWD)/try/listprinter && go run main.go
vagrant-win:
# - Freaking need windows
# https://app.vagrantup.com/gusztavvargadr/boxes/windows-10/
vagrant init gusztavvargadr/windows-10
vagrant up
<file_sep>/pdf/pdf-to-pdf/readme.md
# pdf templater
Users get PDF's from lots of places.
We also make them.
We have Zephr for Rich Text Editing, and we can get that to output a PDF.
What we need is a way to use the PDF's as templates and databind to values
- Will need tags in them.
https://github.com/signintech/pdft
- look good.
- Can also gen PDF from scratch using : https://github.com/signintech/gopdf
- I use Flutter version because Widgets get it automatically., but good for Server side !!
https://github.com/oneplus1000?tab=repositories
- More examples from the authour !!
https://github.com/silenceqi/gopdf
- Fork that added 3 files to work with Chinese UTf
<file_sep>/pdf/pdf-to-raster/cmd/watermark/main.go
package main
import (
"log"
"github.com/sibosendteam/pdfmarker"
"gopkg.in/gographics/imagick.v2/imagick"
)
func main() {
pdfmarker.EnableLog = true
imagick.Initialize()
defer imagick.Terminate()
src := "ref.pdf"
dst := "ref-marked.pdf"
xRes := float64(297) // unimplemented
yRes := float64(210) // unimplemented
outScale := 1.0
opacity := .33
size := pdfmarker.ImageIOSize{InResolution: &pdfmarker.Coordinate{X: xRes, Y: yRes}, OutScale: outScale}
watermarkStyle := pdfmarker.WatermarkStyle{Opacity: opacity, Degrees: -20, Autofit: true}
// use text as watermark
textStyle := pdfmarker.TextStyle{Size: &pdfmarker.Coordinate{X: 640, Y: 104}, Font: "Arial", PointSize: 96, Weight: 1, Color: "grey", Opacity: opacity}
watermark := pdfmarker.TextWatermark{Style: &watermarkStyle, TextStyle: &textStyle, Text: "example.com"}
watermarkMW, _ := watermark.NewWatermark()
// use image as watermark
// watermark := &ImageWatermark{watermarkStyle, "example.com.png"}
if err := pdfmarker.AddWatermark(src, dst, &size, watermarkMW, &watermarkStyle); err != nil {
log.Fatal(err)
}
}
<file_sep>/print/Makefile
print:
## Prints to names Print. No dialog.
lpr -P printername pdf-test.pdf
print1:
## Prints to default. No dialog.
lpr pdf-test.pdf
preview:
## OS X's Preview app, and then use can pritn from there !!
# Works !! This it.
open pdf-test.pdf
win-preview:
# Does it have one ?
# https://stackoverflow.com/questions/6557920/how-to-open-a-pdf-in-fullscreen-view-via-command-line
# Need to test each.
<file_sep>/README.md
# Flutter PDF & Printing for Mobile and Desktop
## Status
Planning and getting approach together with code.
Please feel free to add any tips, info you can see or critique the approach.
NOTE: repo is a mess right now :) Doing experiments.
## Pipeline
HTML --> FL Widgets --> PDF Widgets --> PDF --> Printer
# Notes
Whats the big deal ?
For Mobile and Desktop.
This is the lib: https://github.com/DavBfr/dart_pdf
Its good but just needs a bit more:
Flutter
- Choose Printer before PDF output.
- Is the wrong way around currently it seems.
- Parametrics for Flutter Widgets
- When you make a flutter widget you have to provide the PDF Rendering for that Widget. The Standard Flutter Rendering tree is then used for Screen and Printing - its nice.
- But Layout needs work. Orientation and Sizes, just like we have different Screen sizes, we have different Paper sizes.
- Make examples
- Test it out.
Desktop Integration
- Use Google Cloud Connector lib.
- https://github.com/google/cloud-print-connector
- It has the code to get a Desktops and RaspberryPIโs printer list, options and print spoolers
- Make a Printer dialogue exactly how Google Chrome does it. They had the same issue actually.
- https://i.stack.imgur.com/pHFNs.png
- Flow:
- User selects Printer and then options (paper size, etc).
- Code asks Flutter PDF to rerender. We display Render as a PDF โ Raster (GhostScript golang plug can do this) in the right pane. And round and round it goes.
- When User clicks Print, We pass the PDF to the local print spooler.
There is a Half way house too
- Spit out the PDF and use local PDF Previewer. This sucks though because its spewing medical data onto disk !! Also its breaks the UX experience.
<file_sep>/pdf/pdf-to-raster/readme.md
For Print Preview, We need to convert the PDF to raster
https://github.com/DavBfr/dart_pdf/issues/63
ImageMagick
https://imagemagick.org/script/download.php
brew install --with-ghostscript imagemagick
magick --version
LIBS
https://github.com/catherinelu/evangelist<file_sep>/pdf/viewer/Makefile
## https://github.com/albo1337/flutter_full_pdf_viewer
PDFV_LIB_NAME=flutter_full_pdf_viewer
PDFV_LIB=github.com/albo1337/$(PDFV_LIB_NAME)
PDFV_LIB_PATH=$(GOPATH)/src/$(PDFV_LIB)
PDFV_LIB_DOC=https://$(PDFV_LIB)
help: ## Display this help
# from: https://suva.sh/posts/well-documented-makefiles/
@awk 'BEGIN {FS = ":.*##"; printf "\nUsage:\n make \033[36m<target>\033[0m\n\nTargets:\n"} /^[a-zA-Z_-]+:.*?##/ { printf " \033[36m%-10s\033[0m %s\n", $$1, $$2 }' $(MAKEFILE_LIST)
print:
@echo
@echo /PDFV pdfveek
@echo 'PDFV_LIB_NAME $(PDFV_LIB_NAME)'
@echo 'PDFV_LIB $(PDFV_LIB)'
@echo 'PDFV_LIB_PATH $(PDFV_LIB_PATH)'
@echo 'PDFV_LIB_DOC $(PDFV_LIB_DOC)'
@echo
git-clone: pdfv-git-clone ### git-clone
# all
git-clean: pdfv-git-clean ### git-clean
# all
pdfv-git-clone: ### pdfv-git-clone
mkdir -p $(PDFV_LIB_PATH)
cd $(PDFV_LIB_PATH) && cd .. && rm -rf $(PDFV_LIB_NAME) && git clone ssh://git@$(PDFV_LIB).git
pdfv-git-clean: ### pdfv-git-clean
rm -rf $(PDFV_LIB_PATH)
pdfv-doc-open: ### pdfv-doc-open
open $(PDFV_LIB_DOC)
pdfv-code-open: ### pdfv-code-open
code $(PDFV_LIB_PATH)
pdfv-flu-mob-run: ### pdfv-flu-mob-run
cd $(PDFV_LIB_PATH)/example && Flutter run -d all
<file_sep>/pdf/viewer/epub/ex/Makefile
include ../Makefile
# rebase path
ROOT_APP_PATH=$(PWD)
LIBPATH=$(LIB_PATH)
APPPATH=$(CENF_EX_CALPROTO_FSPATH)
# names
NAME=epub
ORG=com.example.$(NAME)
DESC='Example of $(NAME)'
print:
@echo
@echo 'ROOT_APP_PATH $(ROOT_APP_PATH)'
@echo 'LIBPATH $(LIBPATH)'
@echo 'APPPATH $(APPPATH)'
@echo 'NAME $(NAME)'
@echo 'ORG $(ORG)'
@echo 'DESC $(DESC)'
@echo
flu-create:
# make new
cd $(ROOT_APP_PATH) && flutter create --org $(ORG)-i --description $(DESC) $(NAME)
hover-init:
cd $(APPPATH) && hover init $(LIBPATH)
hover-init-clean:
rm -rf $(APPPATH)/desktop
inject-cenf:
# stardard cenf stuff
cp ../../injects/pubspec.yaml $(APPPATH)
code --goto $(APPPATH)/pubspec.yaml:1
cp ../../injects/main.dart $(APPPATH)/lib
cp ../../injects/main_desktop.dart $(APPPATH)/lib
cp ../../injects/app.dart $(APPPATH)/lib
inject-icon:
# Mobile App Icon
# https://dev.to/rkowase/how-to-generate-flutter-app-icons-for-ios-and-android-11gc
#code --goto $(APPPATH)/pubspec.yaml:27
#code --goto ../../injects/fluttericons.yaml
mkdir -p $(APPPATH)/icon
cp ../../injects/logo.png $(APPPATH)/icon/icon.png
cd $(APPPATH) && flutter pub get
cd $(APPPATH) && flutter pub pub run flutter_launcher_icons:main
inject-appbar:
# App Bar Text
code --goto $(APPPATH)/lib/main.dart:18
code --goto $(APPPATH)/lib/main_desktop.dart:28
# App Bar Logo
code --goto $(APPPATH)/lib/src/full_page.dart:14
# Document Text
# get from doc.dart
code --goto $(APPPATH)/lib/src/full_page.dart:26
code --goto $(APPPATH)/lib/src/view.dart:14
|
6ac904a4ade0c3164c02204bd09f402dcc304e5c
|
[
"Go",
"Makefile",
"Markdown"
] | 17 |
Makefile
|
joeblew99/printing
|
30638aa3473b98b28d95502ff7d8faf00d12f82a
|
bd28cfe2e53c868a5c639376c52f3230ccee8fa3
|
refs/heads/master
|
<repo_name>pmartinez85/Socket.io<file_sep>/server/standalone.js
var io = require('socket.io')();
io.on('connection', function(client){
console.log('new connection revceived');
});
io.listen(3000);
|
21a4fa2d026ee1350d67018451a1f8c1ae353039
|
[
"JavaScript"
] | 1 |
JavaScript
|
pmartinez85/Socket.io
|
3b3a2f05bf50c4e99a17f7e850ce7c0a29e9d154
|
3333c989abc54cbd0207ef14f457946fd95048e2
|
refs/heads/master
|
<repo_name>ShantanuPhadke/ios-decal-proj2<file_sep>/Hangman/HangmanViewController.swift
//
// ViewController.swift
// Hangman
//
// Created by <NAME> on 10/13/15.
// Copyright ยฉ 2015 cs198-ios. All rights reserved.
//
import UIKit
var myHangman: Hangman = Hangman();
class HangmanViewController: UIViewController {
@IBOutlet var past_guesses: UILabel!;
@IBOutlet var new_guess: UITextField!;
@IBOutlet var guess_btn: UIButton?;
@IBOutlet var new_game: UIButton?;
@IBOutlet var hangview: UIImageView!;
@IBOutlet var currentword: UILabel!;
@IBOutlet var start_over: UIButton!;
var wrong_guesses = 0;
override func viewDidLoad() {
super.viewDidLoad()
wrong_guesses = 0;
let xNSNumber = wrong_guesses as NSNumber;
self.hangview.image = UIImage(named: "hangman" + xNSNumber.stringValue + ".gif");
myHangman = Hangman();
// Do any additional setup after loading the view, typically from a nib.
self.new_guess.text = " ";
myHangman.start();
currentword.text = myHangman.knownString;
self.past_guesses.text = " ";
}
@IBAction func newGuess (sender: UIButton){
let new_character = new_guess.text?.uppercaseString
if myHangman.guessLetter(new_character!){//If letter guessed is in answer
currentword.text = myHangman.knownString;
if currentword.text == myHangman.answer{
//Get the pop-up
let winner = UIAlertController(title: "Winner!", message: "You guessed the word correctly and won the game.", preferredStyle: .Alert);
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
self.viewDidLoad();
}
winner.addAction(OKAction);
self.presentViewController(winner, animated: true){
}
}
}else{//If the wrong letter guessed
wrong_guesses++;
past_guesses.text = past_guesses.text! + new_character!;
let xNSNumber = wrong_guesses as NSNumber;
self.hangview.image = UIImage(named: "hangman" + xNSNumber.stringValue + ".gif");
if(wrong_guesses == 7){
//Get the 'bad' popup to come
let loser = UIAlertController(title:"Loser!", message: "You didn't guess the secret word correctly in time, so you lost!", preferredStyle: .Alert);
let OKAction = UIAlertAction(title: "OK", style: .Default) { (action) in
self.viewDidLoad();
}
loser.addAction(OKAction);
self.presentViewController(loser, animated: true){
}
}
}
new_guess.text = "";
}
@IBAction func newGame (sender: UIButton){
self.viewDidLoad();
}
@IBAction func startOver (sender: UIButton){
self.past_guesses.text = "";
self.new_guess.text = "";
var reset = "";
for (var i = 0; i < myHangman.knownString!.characters.count; i+=1){
reset = reset + "_";
}
currentword.text = reset;
wrong_guesses = 0;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
|
36e942d1fb89d78bf96a841481d3d2be8f811c21
|
[
"Swift"
] | 1 |
Swift
|
ShantanuPhadke/ios-decal-proj2
|
cc755a5e2f1385d2d8c5f9b864805fe59b2f5229
|
e23a2a32b2bb9f92b69eb04c941a451ef411a522
|
refs/heads/master
|
<repo_name>mateuszarchicinski/Kickstart-Templates<file_sep>/README.md
# Kickstart Templates
<blockquote>
<p>Project Kickstart Template consists of three templates web pages:</p>
<ul>
<li>Angular 1.x,</li>
<li>Normal,</li>
<li>Mail.</li>
</ul>
<p>Each template has an own environment which is built on the <a href="https://nodejs.org/en/" target="_blank" rel="help">NodeJS</a> platform providing functioning <a href="https://www.npmjs.com/" target="_blank" rel="help">NPM</a>, <a href="https://bower.io/" target="_blank" rel="help">Bower</a>, <a href="http://gulpjs.com/" target="_blank" rel="help">GulpJS</a> and <a href="https://karma-runner.github.io/1.0/index.html" target="_blank" rel="help">Karma</a>.</p>
</blockquote>
I decided to move each template to a new repository. Templates are available at the following addresses of repository:
- <a href="https://github.com/mateuszarchicinski/Angular1.x-Template" target="_blank" rel="help">Angular 1.x - Template</a> (Available right now),
- <a href="https://github.com/mateuszarchicinski/Normal-Template" target="_blank" rel="help">Normal - Template</a> (Still in progress),
- <a href="https://github.com/mateuszarchicinski/Mail-Template" target="_blank" rel="help">Mail - Template</a> (Still in progress).
This repository will serve me for testing and further study of interesting technology.<file_sep>/Normal/src/js/main.js
function greet(name) {
return 'Hello, ' + name + '!';
}
window.addEventListener('load', function () {
console.info('JS running...');
});<file_sep>/Angular1.x/project.config.js
// PROJECT CONFIG
module.exports = {
HOST: 'http://localhost:3000/', // Example host which is required for search engine optimization (SEO) ---> http://www.example-host.pl/
APP_NAME: "app",
LANGUAGES: [ // Required to create templates in different languages. Remember to create directories with the same name (src/template/views/pl - en) and to configure Data File
'pl', // First element is default variable
'en'
],
BASE_URL: 'http://localhost:3000/', // Adds tag <base href="BASE_URL"> inside <head> only when a variable is not empty
CONFIG_FILE: 'project.config.js',
DATA_FILE: 'project.data.json', // Data object which are passing to pug (Dynamic templates)
DIRECTORY: {
WORK_DIR: 'src',
DIST_DIR: 'dist',
TEST_DIR: 'test'
},
FTP_CONFIG: { // All variables required to upload files to FTP Server
HOST: '',
USER: '',
PASSWORD: '',
DESTINATION: '/public_html/'
},
API_KEYS: {
TINIFY: ''
},
GOOGLE_ANALYTICS: {
TRACKING_ID: '' // Adds tracking script only when a variable is not empty
},
FACEBOOK_APPS: {
APP_ID: '' // Adds tag <meta property="fb:app_id" content="FACEBOOK_APPS.APP_ID"> inside <head> only when a variable is not empty
}
};<file_sep>/Normal/gulpfile.js
'use strict';
// NODE MODULES
var gulp = require('gulp'),
$ = require('gulp-load-plugins')({
lazy: true
}),
jshintStylish = require('jshint-stylish'),
htmlhintStylish = require('htmlhint-stylish'),
browserSync = require('browser-sync'),
del = require('del'),
imageminGifsicle = require('imagemin-gifsicle'),
imageminJpegtran = require('imagemin-jpegtran'),
imageminOptipng = require('imagemin-optipng'),
imageminSvgo = require('imagemin-svgo'),
ftp = require('vinyl-ftp'),
argv = require('yargs').argv,
runSequence = require('run-sequence'),
fs = require('fs'),
karma = require('karma').Server;
// PROJECT CONFIG
var PROJECT_CONFIG = require('./project.config');
// PROJECT DATA
var DATA = JSON.parse(fs.readFileSync('./' + PROJECT_CONFIG.DATA_FILE, 'utf8'));
// GULP TASKS
gulp.task('css', function () {
$.util.log($.util.colors.green('CSS TASK RUNNING...'));
return gulp.src(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/sass/main.scss')
.pipe($.plumber())
.pipe($.sourcemaps.init())
.pipe($.sassLint({
options: {
'formatter': 'stylish',
'merge-default-rules': false
},
rules: {
'extends-before-mixins': 2,
'extends-before-declarations': 2,
'placeholder-in-extend': 2,
'mixins-before-declarations': 2,
'no-color-literals': 2,
'no-warn': 1,
'no-debug': 1,
'no-ids': 2,
'no-important': 2,
'hex-notation': 2,
'indentation': 0,
'property-sort-order': 1,
'variable-for-property': 2
}
}))
.pipe($.sassLint.format())
.pipe($.sass.sync({
outputStyle: 'nested' // compact - compressed - expanded - nested
}))
.pipe($.autoprefixer({
browsers: ['last 5 version'],
cascade: false,
stats: ['> 1%']
}))
.pipe($.sourcemaps.write('./maps'))
.pipe(gulp.dest(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/css/'))
.pipe(browserSync.stream());
});
gulp.task('js:hint', function () {
$.util.log($.util.colors.cyan('JS HINT TASK RUNNING...'));
return gulp.src(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/js/**/*.js')
.pipe($.plumber())
.pipe($.jshint())
.pipe($.jshint.reporter(jshintStylish));
});
gulp.task('js:test', function () {
$.util.log($.util.colors.cyan('JS TEST TASK RUNNING...'));
return new karma({
configFile: __dirname + '/' + PROJECT_CONFIG.DIRECTORY.TEST_DIR + '/karma.conf.js'
}).start();
});
gulp.task('jade:pug', function() {
$.util.log($.util.colors.green('JADE TO PUG TASK RUNNING...'));
gulp.src(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/template/**/*.jade', {
base: PROJECT_CONFIG.DIRECTORY.WORK_DIR
})
.pipe($.rename({
extname: '.pug'
}))
.pipe(gulp.dest(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/'))
.on('end', function(){
del(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/template/**/*.jade')
});
});
// To get a parameter after comand option
function getOption(option){
var elem = process.argv.indexOf(option);
return elem !== -1 ? process.argv[elem + 1] : false;
};
gulp.task('pug', function () {
$.util.log($.util.colors.green('PUG TASK RUNNING...'));
if(!getOption('--lang')){
$.util.log($.util.colors.green('Default data object configuration [PL] passed to puge. To change that, add command arguments to gulp task ---> gulp [TASK NAME = puge / default / build / build:server] --lang [LANGUAGE = pl/en]. Before that, do not forget a specify translation in ' + PROJECT_CONFIG.DATA_FILE + ' file.'));
}
return gulp.src(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/template/*.pug')
.pipe($.plumber())
.pipe($.data(function(){
var lang = !getOption('--lang') ? 'pl' : getOption('--lang');
return DATA.lang[lang];
}))
.pipe($.pug({
pretty: true,
compileDebug: true
}))
.pipe(gulp.dest(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/'));
});
gulp.task('html', function () {
$.util.log($.util.colors.green('HTML TASK RUNNING...'));
return gulp.src(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/*.html')
.pipe($.plumber())
.pipe($.useref())
.pipe($.if('*.css', $.cleanCss()))
.pipe($.if('*.js', $.uglify()))
.pipe(gulp.dest(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/'));
});
gulp.task('html:hint', function () {
$.util.log($.util.colors.cyan('HTML HINT TASK RUNNING...'));
return gulp.src(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/*.html')
.pipe($.plumber())
.pipe($.htmlhint({
'tagname-lowercase': true,
'attr-lowercase': true,
'attr-value-double-quotes': true,
'attr-no-duplication': true,
'doctype-first': true,
'tag-pair': true,
'tag-self-close': false,
'spec-char-escape': false,
'id-unique': true,
'src-not-empty': true,
'title-require': true
}))
.pipe($.htmlhint.reporter(htmlhintStylish));
});
gulp.task('html:minify', function () {
$.util.log($.util.colors.green('HTML MINIFY TASK RUNNING...'));
return gulp.src(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/*.html')
.pipe($.plumber())
.pipe($.htmlmin({
minifyCSS: true
}))
.pipe(gulp.dest(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/'));
});
gulp.task('server', function () {
$.util.log($.util.colors.red('SERVER TASK RUNNING...'));
return browserSync.init({
server: PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/'
});
});
gulp.task('watch', function () {
$.util.log($.util.colors.blue('WATCH TASK RUNNING...'));
gulp.watch(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/sass/**/*.s+(a|c)ss', ['css']);
gulp.watch(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/js/**/*.js', ['js:hint', browserSync.reload]);
gulp.watch(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/template/**/*.pug', ['pug']);
gulp.watch(PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/*.html', ['html:hint', browserSync.reload]);
});
gulp.task('clean', function () {
$.util.log($.util.colors.gray('CLEAN TASK RUNNING...'));
return del(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/');
});
gulp.task('copy', function () {
$.util.log($.util.colors.grey('COPY TASK RUNNING...'));
return gulp.src([PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/files/**/*', PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/fonts/**/*', PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/img/**/*', PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/*.png', PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/*.xml', PROJECT_CONFIG.DIRECTORY.WORK_DIR + '/*.ico'], {
base: PROJECT_CONFIG.DIRECTORY.WORK_DIR
})
.pipe($.plumber())
.pipe(gulp.dest(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/'));
});
gulp.task('images', function () {
$.util.log($.util.colors.magenta('IMAGES TASK RUNNING...'));
return gulp.src(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/img/**/*', {
base: PROJECT_CONFIG.DIRECTORY.DIST_DIR
})
.pipe($.plumber())
.pipe($.imagemin([
imageminGifsicle(),
imageminJpegtran(),
imageminOptipng(),
imageminSvgo()
]))
.pipe(gulp.dest(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/'));
});
gulp.task('images:optimized', function () {
$.util.log($.util.colors.magenta('IMAGES OPTIMIZED TASK RUNNING...'));
if(!PROJECT_CONFIG.API_KEYS.TINIFY){
return $.util.log($.util.colors.magenta('Task can not be complited. Rememeber to set up your TINIFY API KEY in ' + PROJECT_CONFIG.CONFIG_FILE + ' file.'));
}
return gulp.src(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/img/**/*', {
base: PROJECT_CONFIG.DIRECTORY.DIST_DIR
})
.pipe($.tinify(PROJECT_CONFIG.API_KEYS.TINIFY))
.pipe(gulp.dest(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/'));
});
gulp.task('upload', function () {
$.util.log($.util.colors.yellow('UPLOAD TASK RUNNING...'));
var ftpConfig = {
host: PROJECT_CONFIG.FTP_CONFIG.HOST,
user: PROJECT_CONFIG.FTP_CONFIG.USER,
password: PROJECT_CONFIG.FTP_CONFIG.PASSWORD
};
if(!ftpConfig.host || !ftpConfig.user || !ftpConfig.password || !argv.upload){
return $.util.log($.util.colors.yellow('Task can not be complited. Rememeber to set up your FTP CONFIG in ' + PROJECT_CONFIG.CONFIG_FILE + ' file. Then add command argument to gulp task ---> gulp [TASK NAME = upload / build / build:server] --upload.'));
}
var conn = ftp.create(ftpConfig);
return gulp.src(PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/**/*')
.pipe($.plumber())
.pipe(conn.dest('/public_html/'));
});
gulp.task('build', function (cb) {
$.util.log($.util.colors.red('BUILD TASK RUNNING...'));
runSequence('clean', 'css', 'js:hint', 'pug', 'html:hint', 'html', 'html:minify', 'copy', 'upload', cb);
});
gulp.task('build:server', ['build'], function () {
$.util.log($.util.colors.red('BUILD SERVER TASK RUNNING...'));
browserSync.init({
server: PROJECT_CONFIG.DIRECTORY.DIST_DIR + '/'
});
});
gulp.task('default', function (cb) {
$.util.log($.util.colors.red('DEFAULT TASK RUNNING...'));
runSequence('css', 'js:hint', 'pug', 'html:hint', 'server', 'watch', cb);
});
|
f0200a82395264c03237dc95c717812b4f39c212
|
[
"Markdown",
"JavaScript"
] | 4 |
Markdown
|
mateuszarchicinski/Kickstart-Templates
|
17b5cd1045c5616dc70621d64062c8142abd4893
|
6e61c3e502307ed74b6f0e1cbc77906ac2e4a1f1
|
refs/heads/master
|
<file_sep>import './reports/reports.js';
import './reports/report/report.js';<file_sep>import { Template } from 'meteor/templating';
import { TAPi18n } from 'meteor/tap:i18n';
import { Session } from 'meteor/session';
import { Gembas } from 'meteor/igoandsee:gembas-collection';
import { Locations } from 'meteor/igoandsee:locations-collection';
import generator from './chartsGenerator.js'
import moment from 'moment';
import Highcharts from 'highcharts/highstock';
require('highcharts/modules/exporting')(Highcharts);
import './report.html';
Template.report.created = function() {
$.fn.form.settings.rules.validDate = function(value) {
let startDate = $('#filtro-reports').form('get value','startDate');
let finishDate = $('#filtro-reports').form('get value','finishDate');
return (moment(startDate) < moment(finishDate));
};
this.showNoData = new ReactiveVar();
this.showNoData.set(false);
this.showChart = new ReactiveVar();
this.showChart.set(false);
}
Template.report.rendered = function() {
$('#loadingReport').hide();
$('.dropdown').dropdown();
$('.ui.checkbox').checkbox();
$('.timepickers').datetimepicker();
const type = Router.current().params.type;
let keysToValidate = getKeysByType(type);
const fields = pickFieldsToValidate(keysToValidate);
console.log('Fields => ', fields);
$('#filtro-reports').form({
inline : true,
on : 'blur',
fields : fields
});
};
Template.report.helpers({
getTitle() {
const type = Router.current().params.type;
switch (type) {
case '1':
return TAPi18n.__('report_title_3');
case '2':
return TAPi18n.__('report_title_4');
case '3':
return TAPi18n.__('report_title_6');
case '4':
return TAPi18n.__('on_time_completion');
case '5':
return TAPi18n.__('compliance_by_gembas');
case '6':
return TAPi18n.__('report_on-time_completion');
};
},
getIconClass() {
const type = Router.current().params.type;
if(type <= 4 ) {
return 'fa-line-chart'
}
return 'fa-bar-chart';
},
showComponent(name) {
const type = Router.current().params.type;
let componentsAllowed = getKeysByType(type);
return componentsAllowed.includes(name);
},
showTextNoData(){
return Template.instance().showNoData.get();
},
showChartContainer(){
return Template.instance().showChart.get();
},
showCheck() {
return false;
},
getGembaWalks() {
return Gembas.find();
},
getLocations() {
return Locations.find();
},
getCategories() {
return [];
}
});
Template.report.events({
'click #btnGenerate'(e, template) {
e.preventDefault();
if ( !$('#filtro-reports').form('is valid') ) {
return;
}
const type = Router.current().params.type;
let keys = getKeysByType(type);
const data = {};
keys.forEach(key => {
let rule = `[name="${key}"]`;
console.log('Rule ', rule);
let value = $(rule).val();
if (key == 'startDate' || key == 'finishDate') {
value = (new Date(value)).getTime();
}
data[key] = value;
});
console.log('Data => ', data);
$('#loadingReport').show();
Meteor.call('getDataChartByType', type, data, function(error, result) {
$('#loadingReport').hide();
if (error) {
console.log('Error => ', error);
Session.set('ERROR_MESSAGE', TAPi18n.__('error_generating_report'));
$('#modalError').modal('show');
}
let options = generator.getDataFromChartType(type, result);
template.showChart.set(true);
//Wait to render chart
setTimeout(() => {
Highcharts.chart('chartContainer', options);
}, 200);
});
}
});
function getKeysByType(type) {
type = Number(type);
switch (type) {
case 1: //Compliance trend by Gemba Walk
return ['startDate', 'finishDate', 'gembaWalks'];
case 2: //Compliance trend by Location
return ['startDate', 'finishDate', 'locations'];
case 3: //On time completion trend by leader
return ['startDate', 'finishDate'];
case 4: //On-time completion trend by Gemba Walk
return ['startDate', 'finishDate', 'gembaWalks'];
case 5: //Compliance by Gemba Walks (Bar)
return ['startDate', 'finishDate', 'gembaWalks'];
case 6: //On-time completion by leader
return ['startDate', 'finishDate'];
default:
return [];
}
}
function pickFieldsToValidate(keys) {
const allFields = {
categories: {
identifier : 'categories',
rules: [
{
type : 'empty',
prompt : TAPi18n.__('categories')
}
]
},
startDate: {
identifier : 'startDate',
rules: [
{
type : 'empty',
prompt: TAPi18n.__('from_date')
}
]
},
finishDate: {
identifier : "finishDate",
rules: [
{
type : 'empty',
prompt: TAPi18n.__('until_date')
},
{
type: "validDate",
prompt : TAPi18n.__('valid_date')
}
]
},
gembaWalks : {
identifier : 'gembaWalks',
rules: [
{
type : 'empty',
prompt : TAPi18n.__('gemba_walk')
}
]
},
status : {
identifier : 'status',
rules: [
{
type : 'empty',
prompt : TAPi18n.__('status')
}
]
},
locations : {
identifier : 'check',
rules: [
{
type : 'empty',
prompt : TAPi18n.__('locations')
}
]
}
};
return Object.keys(allFields)
.filter((key) => keys.includes(key))
.reduce((newObj, key) => Object.assign(newObj, { [key]: allFields[key] }), {});
}
<file_sep>รltimo commit de dev 7 Marzo 2018
-- 3b0535ddbf4d3217845afd5c2cbf81a2f4a81e22 --
Versiรณn individual: no posee selects de usuarios
|
780f1e376fc53205843e84d92723aa491ed2b51a
|
[
"JavaScript",
"Markdown"
] | 3 |
JavaScript
|
LindaLopezR/reports-individual-module
|
aa9c50a7f3ef9e4304fe6ef2ca5c33b650d609f6
|
be1b68809e24943c2798806b760aae838774c1a4
|
refs/heads/master
|
<repo_name>LeoFagundo/final<file_sep>/createdb.rb
# Set up for the application and database. DO NOT CHANGE. #############################
require "sequel" #
connection_string = ENV['DATABASE_URL'] || "sqlite://#{Dir.pwd}/development.sqlite3" #
DB = Sequel.connect(connection_string) #
#######################################################################################
# Database schema - this should reflect your domain model
DB.create_table! :coffee do
primary_key :id
String :shop_name
String :city
String :state
end
DB.create_table! :reviews do
primary_key :id
foreign_key :coffee_id
foreign_key :users_id
Integer :rating
String :comments, text: true
String :date
end
DB.create_table! :users do
primary_key :id
String :name
String :email
String :password
end
# Insert initial (seed) data
coffee_table = DB.from(:coffee)
coffee_table.insert(shop_name: "Newport Coffee",
city: "Evanston",
state: "IL")
coffee_table.insert(shop_name: "Mojo Coffeehouse",
city: "New Orleans",
state: "LA")
puts "success"
<file_sep>/app.rb
# Set up for the application and database. DO NOT CHANGE. #############################
require "sinatra" #
require "sinatra/reloader" if development? #
require "sequel" #
require "logger" #
require "twilio-ruby" #
require "bcrypt"
require "geocoder" #
connection_string = ENV['DATABASE_URL'] || "sqlite://#{Dir.pwd}/development.sqlite3" #
DB ||= Sequel.connect(connection_string) #
DB.loggers << Logger.new($stdout) unless DB.loggers.size > 0 #
def view(template); erb template.to_sym; end #
use Rack::Session::Cookie, key: 'rack.session', path: '/', secret: 'secret' #
before { puts; puts "--------------- NEW REQUEST ---------------"; puts } #
after { puts; } #
#######################################################################################
coffee_table = DB.from(:coffee)
reviews_table = DB.from(:reviews)
users_table = DB.from(:users)
before do
@current_user = users_table.where(id: session["users_id"]).to_a[0]
end
# homepage and list of events (aka "index")
get "/" do
puts "params: #{params}"
@coffee = coffee_table.all.to_a
pp @coffee
view "coffee"
end
# coffee details (aka "show")
get "/coffee/:id" do
puts "params: #{params}"
@users_table = users_table
@coffee = coffee_table.where(id: params[:id]).to_a[0]
pp @coffee
# google maps api
@maps = ENV["MAPS_KEY"]
@reviews = reviews_table.where(coffee_id: @coffee[:id]).to_a
@avg_rating = reviews_table.where(coffee_id: @coffee[:id]).avg(:rating)
view "coffee_shop"
end
# display the review form
get "/coffee/:id/reviews/new" do
puts "params: #{params}"
@coffee = coffee_table.where(id: params[:id]).to_a[0]
view "new_review"
end
# receive the submitted review form (aka "create")
post "/coffee/:id/reviews/create" do
puts "params: #{params}"
# first find the coffee that reviewing for
@coffee = coffee_table.where(id: params[:id]).to_a[0]
# next we want to insert a row in the review table with the rewview form data
reviews_table.insert(
coffee_id: @coffee[:id],
users_id: session["users_id"],
comments: params["comments"],
rating: params["rating"]
)
redirect "/coffee/#{@coffee[:id]}"
end
# display the review form (aka "edit")
get "/reviews/:id/edit" do
puts "params: #{params}"
@reviews = reviews_table.where(id: params["id"]).to_a[0]
@coffee = coffee_table.where(id: @reviews[:coffee_id]).to_a[0]
view "edit_review"
end
# receive the submitted reviews form (aka "update")
post "/reviews/:id/update" do
puts "params: #{params}"
# find the reviews to update
@reviews = reviews_table.where(id: params["id"]).to_a[0]
# find the review's coffee shop
@coffee = coffee_table.where(id: @reviews[:coffee_id]).to_a[0]
#in case user bug lets them edit another review
if @current_user && @current_user[:id] == @reviews[:id]
reviews_table.where(id: params["id"]).update(
rating: params["rating"],
comments: params["comments"]
)
redirect "/coffee/#{@coffee[:id]}"
else
view "error"
end
end
# delete the reviews (aka "destroy")
get "/reviews/:id/destroy" do
puts "params: #{params}"
@reviews = reviews_table.where(id: params["id"]).to_a[0]
@coffee = coffee_table.where(id: @reviews[:coffee_id]).to_a[0]
reviews_table.where(id: params["id"]).delete
redirect "/coffee/#{@coffee[:id]}"
end
# display the signup form (aka "new")
get "/users/register" do
view "register"
end
# receive the submitted signup form (aka "create")
post "/users/create" do
puts "params: #{params}"
# if there's already a user with this email, skip!
existing_user = users_table.where(email: params["email"]).to_a[0]
if existing_user
view "error"
else
users_table.insert(
name: params["name"],
email: params["email"],
password: <PASSWORD>(params["password"])
)
redirect "/logins/new"
end
end
# display the login form (aka "new")
get "/logins/new" do
view "new_login"
end
# receive the submitted login form (aka "create")
post "/logins/create" do
puts "params: #{params}"
# step 1: user with the params["email"] ?
@users = users_table.where(email: params["email"]).to_a[0]
if @users
# step 2: if @user, does the encrypted password match?
if BCrypt::Password.new(@users[:password]) == params["password"]
# set encrypted cookie for logged in user
session["users_id"] = @users[:id]
redirect "/"
else
view "register_failed"
end
else
view "register_failed"
end
end
# logout user
get "/logout" do
# remove encrypted cookie for logged out user
session["users_id"] = nil
redirect "/logins/new"
end
# display the review form
get "/new_shop" do
puts "params: #{params}"
@coffee = coffee_table.where(id: params[:id]).to_a[0]
view "new_coffee_shop"
end
# receive the submitted coffee form (aka "create")
post "/new_shop/create" do
puts "params: #{params}"
# next we want to insert a row in the coffee table with the coffee form data
coffee_table.insert(
state: params["state"],
city: params["city"],
shop_name: params["shop_name"]
)
# find the coffee that reviewing for
@coffee = coffee_table.max(:id)
redirect "/coffee/#{@coffee}"
end
|
ab220cebae48f6aa15e10917258cd1281a1fddac
|
[
"Ruby"
] | 2 |
Ruby
|
LeoFagundo/final
|
73f7a2b7c05aa1aac4f87e469933facdafc9a422
|
a97607aa95892f57a9a9258dcd7bc0987df5e165
|
refs/heads/master
|
<repo_name>anvitha-jain/SmartDoor<file_sep>/scripts/run.sh
!/bin/sh
aws s3 cp s3://smartdoor-logo1/index.html /var/www/html/index.html
service httpd restart
<file_sep>/raspberrypie_scripts/newIndex.py
import boto3
import json
session = boto3.Session(aws_access_key_id='', aws_secret_access_key='', region_name='us-east-1')
bucket="test-reko-mybucket"
key="p1.jpg"
customName = "poorva"
bucket='test-reko-mybucket'
collectionId='friends_collection'
photo='nk4.jpg'
photoName = 'NightKing'
reko_client=session.client('rekognition')
response=reko_client.index_faces(CollectionId=collectionId,
Image={'S3Object':{'Bucket':bucket,'Name':photo}},
ExternalImageId=photoName,
MaxFaces=1,
QualityFilter="AUTO",
DetectionAttributes=['ALL'])
print ('Results for ' + photo)
print('Faces indexed:')
for faceRecord in response['FaceRecords']:
print(' Face ID: ' + faceRecord['Face']['FaceId'])
print(' Location: {}'.format(faceRecord['Face']['BoundingBox']))
print('Faces not indexed:')
for unindexedFace in response['UnindexedFaces']:
print(' Location: {}'.format(unindexedFace['FaceDetail']['BoundingBox']))
print(' Reasons:')
for reason in unindexedFace['Reasons']:
print(' ' + reason)
<file_sep>/raspberrypie_scripts/msesnortest.py
import RPi.GPIO as GPIO
import time
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import json
import time
sensor = 16
GPIO.setmode(GPIO.BOARD)
GPIO.setup(sensor,GPIO.IN)
clientId = "myClientID"
thingEndpoint = ''
certificatePath = ''
privateKeyPath = ''
rooCACertPath = ''
print "before setup1 ..."
myMQTTClient = AWSIoTMQTTClient(clientId)
myMQTTClient.configureEndpoint(thingEndpoint, 8883)
myMQTTClient.configureCredentials(rooCACertPath, privateKeyPath, certificatePath)
myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish q myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
print "before connection..."
myMQTTClient.connect()
print "connected"
myTopic = "sendButtonClick"
message = {}
message['text'] = "This is message"
message['type'] = "This is message type"
messageJson = json.dumps(message)
print "Initialzing PIR Sensor......"
time.sleep(12)
print "PIR Ready..."
print " "
try:
while True:
if GPIO.input(sensor):
print "Motion Detected"
myMQTTClient.publish(myTopic, messageJson, 0)
while GPIO.input(sensor):
time.sleep(0.2)
else:
print "No motion"
except KeyboardInterrupt:
GPIO.cleanup()
<file_sep>/raspberrypie_scripts/pollytest.py
import boto3
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient
import json
import time
import os
def customCallback(client, userdata, message):
print("Received a new message: ")
print("from topic: ")
print(message.topic)
print("--------------\n\n")
print(message.payload)
data = message.payload
jsonData = json.loads(data)
speechText = "We have a guest."
if(jsonData['visitior_name'] != 'guest'):
speechText = "We have " + jsonData['visitior_name'] + " at the door."
response = polly_client.synthesize_speech(VoiceId='Joanna', OutputFormat='mp3', Text = speechText)
file = open('speech9.mp3', 'w')
file.write(response['AudioStream'].read())
file.close()
os.system('mpg123 -q speech9.mp3')
clientId = "myClientID4"
thingEndpoint = ''
certificatePath = ''
privateKeyPath = ''
rooCACertPath = ''
polly_client = boto3.Session(
aws_access_key_id='',
aws_secret_access_key='',
region_name='us-east-1').client('polly')
print "before setup1 ..."
myMQTTClient = AWSIoTMQTTClient(clientId)
myMQTTClient.configureEndpoint(thingEndpoint, 8883)
myMQTTClient.configureCredentials(rooCACertPath, privateKeyPath, certificatePath)
myMQTTClient.configureAutoReconnectBackoffTime(1, 32, 20)
myMQTTClient.configureOfflinePublishQueueing(-1) # Infinite offline Publish queueing
myMQTTClient.configureDrainingFrequency(2) # Draining: 2 Hz
myMQTTClient.configureConnectDisconnectTimeout(10) # 10 sec
myMQTTClient.configureMQTTOperationTimeout(5) # 5 sec
myMQTTClient.connect()
print "connected"
myTopic = "imageLinkSend"
myMQTTClient.subscribe(myTopic, 0, customCallback)
while True:
None
|
f635d63421ceb9b0e7477487db8c40176ae8d2f3
|
[
"Python",
"Shell"
] | 4 |
Shell
|
anvitha-jain/SmartDoor
|
bcdd9cc74169bf7b9e3241d456edd44100a9a4ae
|
f4dc1dd957993a6273ee8f65c38dea8b1805e0b4
|
refs/heads/master
|
<repo_name>davidsmiles/restapi-with-sqlalchemy<file_sep>/resources/user.py
from flask_restful import Resource, reqparse
from models.user import UserModel
class UserRegister(Resource):
parser = reqparse.RequestParser()
parser.add_argument('username',
type=str,
help='This field should not be left blank',
required=True)
parser.add_argument('password',
type=str,
help='This field should not be left blank',
required=True)
def post(self):
data = UserRegister.parser.parse_args()
username = data['username']
password = data['<PASSWORD>']
user = UserModel.find_by_username(username)
if not user:
user = UserModel(**data)
user.add_to_db()
return {'message': 'successfully created'}
return {'message': 'user already exists'}
class User(Resource):
@classmethod
def get(cls, username):
user = UserModel.find_by_username(username)
if not user:
return {'message': 'user not found.'}, 404
return user.json()
@classmethod
def delete(cls, username):
user = UserModel.find_by_username(username)
if not user:
return {'message': 'user not found.'}, 404
user.delete()
return {'message': 'user has been deleted'}
class UsersList(Resource):
def get(self):
return [user.json() for user in UserModel.find_all()]<file_sep>/resources/index.py
from flask_restful import Resource, reqparse
class Index(Resource):
def get(self):
return {
'message': 'welcome to the stores-rest-api'
}<file_sep>/README.md
# `A Simple RESTful API`
Implemented using Flask-RESTFul, Flask-JWT and Flask-SQLAlchemy.
Hosted on Heroku https://api-david.herokuapp.com/
Has the following resources and endpoints respectively:
1. UserRegister `POST /signup {"username": string, "password": string}`
2. UsersList `GET /users `
3. User `GET /user/<string:name>`
4. ItemList `GET /items`
5. Item `GET or DELETE /item/<string:name>`
6. Item `POST or PUT /item/<string:name> {"price": float, "store_id": int}`
7. StoresList `GET /stores`
8. Store `GET or POST or DELETE /item/<string:name>`
###### Not an API in production though, but for learning purpose only
<file_sep>/resources/item.py
from flask_jwt import jwt_required
from flask_restful import Resource, reqparse
from models.item import ItemModel
class Item(Resource):
parser = reqparse.RequestParser()
parser.add_argument('price',
type=float,
required=True,
help='This field cannot be left blank')
parser.add_argument('store_id',
type=int,
required=True,
help='Every item needs a store_id')
def get(self, name):
item = ItemModel.find_by_name(name)
return {'item': item.json() if item else None}, 200 if item else 404
def post(self, name):
item = ItemModel.find_by_name(name)
if item:
error_msg = {'message': f'item with name {name} already exists'}
return error_msg, 400
data = Item.parser.parse_args()
# price = data['price']
# store_id = data['store_id']
item = ItemModel(name, **data)
try:
item.upsert()
return item.json()
except:
return {'message': 'internal server error'}, 500
def delete(self, name):
item = ItemModel.find_by_name(name)
if item:
item.delete()
return item.json()
return {'message': f'no item with name {name} in database'}, 200
def put(self, name):
data = Item.parser.parse_args()
price = data['price']
# store_id = data['store_id']
item = ItemModel.find_by_name(name)
if not item: # if dont exists, then add
item = ItemModel(name, **data)
else:
item.price = price # else update data
item.upsert()
return {'message': 'item has been put'}, 200
class ItemList(Resource):
@jwt_required()
def get(self):
items = ItemModel.find_all()
items = [item.json() for item in items]
response = {'items': items}
return response, 200
|
3be7fa897a8ba4d9c4c745e83e8eec956b37258f
|
[
"Markdown",
"Python"
] | 4 |
Python
|
davidsmiles/restapi-with-sqlalchemy
|
6a95172123c0b5d75a7ba7b9e992562db9569c92
|
c82c2e61bbeb462d637129b8b31e484d530d38b2
|
refs/heads/master
|
<repo_name>ssong0122/mynodetest<file_sep>/Day4/functionhooksapp/src/UseEffectHook.js
import React, { useState, useEffect, useRef } from "react";
//UseEffect Hook์ ํจ์ํ ์ปดํฌ๋ํธ์์์ ์ปดํฌ๋ํธ ์์ ์ฃผ๊ธฐ ๋ฐ ๋ฐ์ดํฐ (state)๋ณ๊ฒฝ ๊ฐ์ง
//์ด๋ฒคํธ ๊ธฐ๋ฅ์ ์ ๊ณตํฉ๋๋ค.
const UseEffectHook = () => {
//state๋ช
๊ณผ ์ธํฐ ํจ์๋ช
์ ๋ฌ๋ผ๋ ๋จ
//๊ทธ๋ ์ง๋ง ๋ค๋ฆฌ๊ณ state๊ฐ ๋ง์์ง๋ฉด ํท๊ฐ๋ฆฌ๊ฒ ์ง์?
const [testString, setTest] = useState("ํ
์คํธ1");
//dom์ ์ฐธ์กฐํ ์์๋ฅผ ์ ์ธํ๋ค.
const testRef = useRef();
const [testString1, setTest2] = useState("ํ
์คํธ2");
const onTestChange = (e) => {
//๊ฐ์ ๋ณ๊ฒฝ ์ ์ฉํ๋ค.
setTest(e.target.value);
};
//์ปดํฌ๋ํธ์ ์ํ๊ฐ(state, layout,html) ๋ณ๊ฒฝ๋ ๋๋ง๋ค ํธ์ถ๋จ
useEffect(() => {
console.log(
"์ปดํฌ๋ํธ์ ์ํ๊ฐ(state, jsx, html) ๋ณ๊ฒฝ๋ ๋๋ง๋ค ํธ์ถ๋ฉ๋๋ค. "
);
});
//ํด๋น ์ปดํฌ๋ํธ๊ฐ ์ต์ด ํธ์ถ๋ ๋ ํ ๋ฒ๋ง ์คํ
//ํด๋น ์ปดํฌ๋ํธ๊ฐ ์ต์ด ๋ก๋๋๋ฉด ์ดํ ์ปดํฌ๋ํธ๊ฐ ํ๋ฉด์์ ์ฌ๋ผ์ง ๋๊น์ง ์คํ๋์ง ์์
//ํ๋ฉด ๋ก๋ ์๋ฃ ํ ์ปค์ ํฌ์ปค์ฑ์ด๋ ๋ฐฑ์๋ ๋ฐ์ดํฐ ์กฐํ ํ state๊ฐ์ ์ฑ์์ค๋ค๊ฑฐ๋ ํ๋ ๊ฒฝ์ฐ ์ฃผ๋ก ์ฌ์ฉ
useEffect(() => {
console.log("ํด๋น ์ปดํฌ๋ํธ๊ฐ ์ต์ด ํธ์ถ๋ ๋ 1ํ๋ง ์คํ.");
testRef.current.focus();
testRef.current.style.background = "red";
}, []);
//์ง์ ๋ state๊ฐ์ด ๋ณ๊ฒฝ๋ ๋๋ง๋ค ์คํ๋๋ค.
//ui์์์ ๋ฐ์ธ๋ฉ๋ ํน์ state๊ฐ์ด ๋ณ๊ฒฝ๋ ๋ ๋ก์ง์ ์ ์ฉํ๊ฑฐ๋ ๋ฐฑ์๋์์ ๋ฐ์ดํฐ๋ฅผ ํธ์ถํ๊ฑฐ๋ ํ๋ ๊ฒฝ์ฐ ์ฃผ๋ก ์ฌ์ฉ
useEffect(() => {
console.log("์ง์ ๋ state๊ฐ์ด ๋ณ๊ฒฝ๋ ๋๋ง๋ค ์คํ๋๋ค.00000");
}, [testString, testString1]);
useEffect(() => {
console.log("์ง์ ๋ state๊ฐ์ด ๋ณ๊ฒฝ๋ ๋๋ง๋ค ์คํ๋๋ค.111111");
}, [testString1]);
return (
<div>
<input
type="text"
ref={testRef}
value={testString}
onChange={onTestChange}
/>
</div>
);
};
export default UseEffectHook;
<file_sep>/Day6/reduxsampleapp/src/components/Todos.js
import React, { useState } from "react";
//dispatch๊ด๋ จ) ๋ฆฌ๋์ค : ์ก์
์คํ ํจ์๋ฅผ ์์
๊ฒ ํธ์ถํ๊ธฐ ์ํ useDispatchํ
์ ์ฐธ์กฐํ๋ค.
import { useDispatch } from "react-redux";
//dispatch๊ด๋ จ) ๋์คํจ์น๋ฅผ ์ํ ๋ฆฌ๋์ค ์ก์
์คํ ํจ์๋ฅผ ์ฐธ์กฐํ๋ค.
import { addTodoList } from "../redex/todos/actions";
const Todos = () => {
//๋จ์ผ ํ ์ผ ์ ๋ณด ๋ฐ์ดํฐ ๊ตฌ์กฐ ์ ์ ๋ฐ ์ด๊ธฐ๊ฐ ์ธํ
const [todo, setTodo] = useState({
title: "",
order: 0,
});
//ํ ์ผ ๋ชฉ๋ก : ํ์ฌ๋ ํด๋น ์ปดํฌ๋ํธ์์ ๊ด๋ฆฌํ์ง๋ง ์ถํ์๋ ์ ์ญ ๋ฐ์ดํฐ๋ก ์ด๊ด ์์
const [todoList, setTodoList] = useState([]);
//dispatch๊ด๋ จ) ์ ์ญ ๋ฐ์ดํฐ ์ ์ด์ฉ ๋์คํจ์น ์์ ์์ฑ
const globalDispatch = useDispatch();
//ํ ์ผ ๋ฐ์ดํฐ ๋ฐ์ธ๋ฉ ํจ์
const onTodoChange = (e) => {
setTodo({ ...todo, [e.target.name]: [e.target.value] });
};
//ํ ์ผ ์ถ๊ฐ ํจ์
const onAddTodo = () => {
setTodoList([...todoList, todo]);
console.log("ํ์ฌ ์ถ๊ฐ๋ ํ ์ผ ์นด์ดํธ : ", todoList.length);
//dispatch๊ด๋ จ)
//์ ์ญ ํ ์ผ ๋ชฉ๋ก ์นด์ดํธ ์ ๋ณด์ ์ก์
์์ฑ ํจ์๋ฅผ ํธ์ถํ์ฌ ์ ์ญ ์นด์ดํธ๋ฅผ ๊ฐฑ์ ์ํจ๋ค.
//globalDispatch๋ฅผ ์ด์ฉํด ์ฐธ์กฐํ addTodoList() ์ก์
์์ฑ ํจ์๋ฅผ ํธ์ถํ๋ค.
//addTodoList์ก์
ํจ์ ํธ์ถ ์ ์ก์
์ ์ ๋ฌํ ๋ฐ์ดํฐ์ธ ํ ์ผ ๋ชฉ๋ก ๊ฑด์๋ฅผ ์ ๋ฌํ๋ค.
globalDispatch(addTodoList((todoList.length + 1).toString()));
};
return (
<div>
ํ ์ผ ์ด๋ฆ :
<input
type="text"
name="title"
value={todo.title}
onChange={onTodoChange}
/>
<br></br>
์ฒ๋ฆฌ ์ฐ์ ์์:
<input
type="text"
name="order"
value={todo.order}
onChange={onTodoChange}
/>
<button onClick={onAddTodo}>์ถ๊ฐํ๊ธฐ</button>
<hr></hr>
{todoList.map((item, index) => (
<li key={index}>
{item.title} --- {item.order}
</li>
))}
</div>
);
};
export default Todos;
<file_sep>/Day4/reactroutingapp/src/WithRouterSample.js
import React from "react";
//history ๊ธฐ๋ฅ ์ฌ์ฉ์ ์ํ withRouter ๊ฐ์ฒด ์ฐธ์กฐ
import { withRouter } from "react-router-dom";
//ํจ์ํ ์ปดํฌ๋ํธ์์์ ๊ธฐ๋ณธ์ ์ธ history์ฌ์ฉ๋ฒ(๋งํฌ ์ปดํฌ๋ํธ/ํ์ด์ง ๊ฐ ์ด๋ )
const WithRouterSample = ({ location, match, history }) => {
const onMoveToHome = () => {
//history.push()๋ฉ์๋๋ ํด๋น ๊ฒฝ๋ก๊ฐ ์์ผ๋ฉด ์ด๋ ๊ฒฝ๋ก ๋ด์ญ ๋ชฉ๋ก์ ํด๋น ๋งํฌ ์ฃผ์ ์ถ๊ฐ
//์์ผ๋ฉด ๋ฑ๋ก๋ ๋ผ์ฐํ
์ฃผ์ URL์ ๊ทธ๋ฅ ์ฌ์ฉํ์ฌ ํด๋น ์ปดํฌ๋ํธ๋ก ์ด๋ํ๊ฒ ํจ
history.push("/");
};
return (
<div>
<button
onClick={() => {
history.push("/");
}}
>
ํ์ผ๋ก ์ด๋
</button>
{/* withRouter๊ฐ์ฒด๋ฅผ ์ด์ฉํด history๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๋ ๋ฐ๋์ export์ถ๋ ฅ์์ withRouter๊ฐ์ฒด๋ก ์ปดํฌ๋ํธ๋ฅผ ๊ฐ์ธ์ค๋ค. */}
<button onClick={onMoveToHome}>ํ์ผ๋ก ์ด๋</button>
</div>
);
};
//withRouter๊ฐ์ฒด๋ฅผ ์ด์ฉํด history๋ฅผ ์ฌ์ฉํ๋ ๊ฒฝ์ฐ๋ ๋ฐ๋์ export์ถ๋ ฅ์์ withRouter๊ฐ์ฒด๋ก ์ปดํฌ๋ํธ๋ฅผ ๊ฐ์ธ์ค๋ค. โ์ฌ๊ธฐ ๋งํ๋ ๊ฑฐ
export default withRouter(WithRouterSample);
<file_sep>/Day4/reactroutingapp/src/UseHistoryHook.js
import React, { useState, useMemo } from "react";
//์ปดํฌ๋ํธ ๋ผ์ฐํ
๋ฐ ํ๋ฉด์ด๋ ์ ์ด๋ฅผ ์ํ ์ ๊ท ๋ผ์ฐํ
ํ
๊ธฐ๋ฅ ์ ๊ณต
//useHistory, useLocation ์ ๊ท hook ์ ๊ณต
import { useHistory, useLocation } from "react-router-dom";
const UseHistoryHook = () => {
//history ์์ ์ ์
const history = useHistory();
//ํ์ฌ ๋ณด๊ณ ์๋ ๋ธ๋ผ์ฐ์ ์ URL ์ฃผ์/PARAMS/QueryString๊ฐ์ ์ฝ๊ฒ ์ถ์ถ/ ์ ์ดํ ์ ์๋ ํ
์ ๊ณต
const location = useLocation();
const onMoveToCompany = () => {
history.push("/company");
};
return (
<div>
<button
onClick={() => {
history.push("/");
}}
>
ํ ์ด๋
</button>
<button onClick={onMoveToCompany}>ํ์ฌ์๊ฐ ์ด๋</button>
<button
onClick={() => {
history.push({ pathname: "/about", search: "?qid=vvvvvv" });
}}
>
ํ์ฌ์๊ฐ ์ด๋ with QueryString
</button>
</div>
);
};
export default UseHistoryHook;
<file_sep>/Day5/reactaxiosapp/src/pages/members/MemberList.js
import React from "react";
const MemberList = () => {
return (
<div>
<h1>ํ์ ๋ชฉ๋ก ํ์ด์ง</h1>
</div>
);
};
export default MemberList;
<file_sep>/Day6/reduxsampleapp/src/constants/actionTypes.js
//๊ฐ ์ข
๋ฆฌ๋์ค ์ก์
ํ์
(=์ก์
์ด๋ฆ)์ ์์๊ฐ์ผ๋ก ์ ์ํด์ ์ ์ญ์ผ๋ก ์ฌ์ฉํ ์ ์๋ ํ๊ฒฝ ์ ๊ณต
//ํ ์ผ ๋ชฉ๋ก ์ ๊ท ์ถ๊ฐ ์ ํธ์ถํ ์ก์
ํ์
์ ์
export const TODO_ADD = "TODO_ADD";
//๋จ์ผ ์ต์ ํ ์ผ ์ ๋ณด ๊ฐฑ์
export const TODO_NEW_ITEM = "TODO_NEW_ITEM";
//์ ์ญ ์ต์ ํ ์ผ ์ ๋ณด ๊ฐฑ์
export const TODO_LIST = "TODO_LIST";
//๋ก๊ทธ์ธ ์งํ ์ก์
ํ์
์ ์
export const LOGIN_USER = "LOGIN_USER";
//๋ก๊ทธ์ธ ์๋ฃ ์ก์
ํ์
์ ์
export const LOGIN_SUCCESS = "LOGIN_SUCCESS";
<file_sep>/Day5/reactaxiosapp/src/pages/members/MemberRegist.js
import React from "react";
const MemberRegist = () => {
return <div></div>;
};
export default MemberRegist;
<file_sep>/Day7/webzineadminapp/routes/articleAPI.js
var express = require("express");
var router = express.Router();
var jwt = require("jsonwebtoken");
var multer = require("multer");
var storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, "public/upload/");
},
filename(req, file, cb) {
cb(null, `${Date.now()}__${file.originalname}`);
},
});
var upload = multer({ storage: storage });
//ORM ์ฐธ์กฐํ๊ธฐ
var db = require("../models/index");
var Article = db.Article;
//์ ์ฒด ๊ฒ์๊ธ ๋ชฉ๋ก ๋ฐ์ดํฐ ๋ฐํ ๋ผ์ฐํ
๋ฉ์๋
//๋ผ์ฐํ
์ฃผ์: localhost:3005/api/articles
//๋ฐํ๊ฐ: JSON ํฌ๋งท ๊ฒ์๊ธ ๋ชฉ๋ก
//๋น๋๊ธฐ ๋ฐฉ์์ผ๋ก ๋ผ์ฐํ
๋ฉ์๋ ํจ์ ์ ์ํ๊ธฐ
router.get("/", async (req, res) => {
//๋ธ๋ผ์ฐ์ ์์ AJAX ํค๋์ ํฌํจ๋์ด ์ ๋ฌ๋๋ JWT ํ ํฐ์ ์ถ์ถํ๋ค.
const token = req.headers["x-access-token"];
//const token = req.headers.authorization.split("Bearer ")[1];
console.log("ํด๋ผ์ด์ธํธ ํ ํฐ ๊ฐ :", token);
let result = { code: "", data: [], msg: "" };
//๋ฐ๊ธ๋ ํ ํฐ์ ๋ณด๊ฐ ์กด์ฌํ์ง ์์๊ฒฝ์ฐ
if (token == undefined) {
result.code = "404";
result.data = [];
result.msg = "์ธ์ฆ๋์ง ์์ ์ฌ์ฉ์ ์
๋๋ค.(ํ ํฐ์์)";
return res.json(result);
}
//ํ ํฐ์์ ์ฌ์ฉ์์ ๋ณด ์ถ์ถํ์ฌ ํด๋ผ์ด์ธํธ ์ฌ์ฉ์๊ฐ ๋๊ตฌ์ธ์ง๋ฅผ ํ์
ํ๋ค.
try {
var currentMember = jwt.verify(token, process.env.JWT_SECRET);
console.log("API ํธ์ถ ์ฌ์ฉ์์ ๋ณด:", currentMember);
} catch (err) {
result.code = "404";
result.data = [];
result.msg = "์ ํจํ์ง ์์ ํ ํฐ์
๋๋ค.";
return res.json(result);
}
//์์ธ์ฒ๋ฆฌํ๊ธฐ
try {
const articleList = await Article.findAll();
result.code = "200";
result.data = articleList;
result.msg = "Ok";
return res.json(result);
} catch (err) {
//์๋ฌ ๋ฌด์ํ๊ธฐ
console.log("์๋ฒ์๋ฌ ๋ฐ์");
//์๋ฌ๋ด์ฉ์ธ err์ DB/WAS์๋ฒ๋ด FILE๋ก ๊ธฐ๋กํ๊ฑฐ๋/SMS/๋ฉ์ผ๋ก ์๋ฌ๋ฐ์
//์ฌ์ค์ ์๋ฆผ(Notification) ์ฒ๋ฆฌํด์ค๋ค.
result.code = "500";
result.data = [];
result.msg = "์๋ฒ์๋ฌ๋ฐ์";
return res.json(result);
}
});
//๋จ์ผ ๊ฒ์๊ธ ๋ฑ๋ก API
//์ฌ์ฉ์ ๋ธ๋ผ์ฐ์ (AJAX)์์ ๋จ์ผ ๊ฒ์๊ธ JSON๋ฐ์ดํฐ๊ฐ ์ ๋ฌ๋๋ค.
//๋ผ์ฐํ
์ฃผ์: localhost:3005/api/articles
//๋ฐํ๊ฐ : ๋ฐ์ดํฐ ๋ฑ๋ก ์ฒ๋ฆฌ ๊ฒฐ๊ณผ ๊ฐ
router.post("/", async (req, res) => {
let article = {
title: req.body.title,
boardid: 1,
contents: req.body.contents,
viewcount: 0,
displayyn: req.body.displayyn,
ipaddress: req.ip,
createduid: 1,
updateduid: 1,
};
console.log("๋ฑ๋ก์ฝ์ํ๋๋ฐ์ดํฐ:", article);
try {
//DB์ ํด๋น ๋ฐ์ดํฐ๋ฅผ ์ ์ฅํ๊ณ ์ ์ฅ๊ฒฐ๊ณผ๋ฅผ ๋ค์๋ฐ์์จ๋ค.
const savedArticle = await Article.create(article);
return res.json({ code: "200", data: savedArticle, msg: "Ok" });
} catch (err) {
console.log("์๋ฒ์๋ฌ๋ด์ฉ:", err);
return res.json({ code: "500", data: {}, msg: "์๋ฒ์๋ฌ๋ฐ์" });
}
});
//๋จ์ผ๊ฒ์๊ธ ์์ API ๋ผ์ฐํ
๋ฉ์๋
//์ฌ์ฉ์ ๋ธ๋ผ์ฐ์ ์์ ์์ ๋ ๊ฒ์๊ธ JSON๋ฐ์ดํฐ๊ฐ ์๋ ์ฃผ์๋ก ์ ๋ฌ๋๋ค.
//ํธ์ถ๋๋ ๋ผ์ฐํ
์ฃผ์๊ฐ ๋์ผํด๋ ๋ผ์ฐํ
๋ฉ์๋๋ ๋ฉ์๋์ ํ(get,post,put,delete)์ด ๋ค๋ฅด๋ฉด ์ฃผ์๋ฅผ ๋์ผํ๊ฒ ์ฌ์ฉ๊ฐ๋ฅํ๋ค.
//๋ผ์ฐํ
์ฃผ์ : localhost:3000/api/articles
router.put("/", async (req, res) => {
try {
//updatedId๋ ์ ์ฉ๊ฑด์๊ฐ์ ๋ฐ์์จ๋ค.
//์ ์ฉ๋ pk(id)๊ฐ์ด ์๋๋ค์..
const updatedId = await Article.update(
{
title: req.body.title,
contents: req.body.contents,
displayyn: req.body.displayyn,
ipaddress: req.ip,
updateduid: 1,
},
{ where: { boardid: 1, id: req.body.id } }
);
console.log("์์ ๊ฒฐ๊ณผ ๋ฐํ๊ฐ:", updatedId);
console.log("์ง์ง ๋ฐ์ดํฐ ์์ ์๋ฃ");
return res.json({
code: "200",
data: updatedId,
msg: "์ ์์ ์ผ๋ก ์์ ์๋ฃ๋์์ต๋๋ค.",
});
} catch (err) {
return res.json({ code: "500", data: 0, msg: "์๋ฒ์๋ฌ๋ฐ์" });
}
});
//ํ์ผ ์
๋ก๋ ์ฒ๋ฆฌ OPEN API ์๋น์ค
//localhsot:3000/api/article/upload
router.post("/upload", upload.single("file"), async (req, res) => {
console.log("์๋ฒ ํ์ผ ์
๋ก๋ ํธ์ถ๋จ=================>");
const uploadFile = req.file;
let filePath = "/upload/" + uploadFile.filename;
return res.json(filePath);
//return res.json(uploadFile);
});
//๋จ์ผ ๊ฒ์๊ธ์ ๋ณด ์กฐํ API ๋ผ์ฐํ
๋ฉ์๋
//๋ผ์ฐํ
์ฃผ์: localhost:3000/api/articles/1000
//url ํธ์ถ์ฒด๊ณ๋ด์ ๋ฐ์ดํฐ๋ฅผ ๋ด์ ์ ๋ฌํ๋ ๋ฐฉ์์ ์์ผ๋์นด๋ ๋ฐฉ์์ด๋ผํจ.
//์์ผ๋ ์นด๋๋ก ๋์ด์จ ๋ฐ์ดํฐ๋ :๋ณ์๋ช
์ผ๋ก ์ ์ํด์ ์ฌ์ฉํ๋ค.
router.get("/:id", async (req, res) => {
const articleIdx = req.params.id;
try {
const article = await Article.findOne({ where: { id: articleIdx } });
return res.json({ code: 200, data: article, msg: "Ok" });
} catch (error) {
return res.json({
code: 500,
data: {},
msg: "๊ด๋ฆฌ์์๊ฒ ๋ฌธ์ํ์ธ์. 010-2222-333",
});
}
});
//๊ฒ์๊ธ ์ญ์ API ๋ผ์ดํ
๋ฉ์๋
//์ฌ์ฉ์ ๋ธ๋ผ์ฐ์ ์์ URL ์ฃผ์๋ฅผ ํตํด ์ญ์ ํ๋ ๊ฒ์๊ธ ๋ฒํธ๋ฅผ ์ ๋ฌํด์จ๋ค.
//๋ผ์ฐํ
์ฃผ์: localhost:3000/api/articles/1
router.delete("/:id", async (req, res) => {
const articleIdx = req.params.id;
try {
const affectedCnt = await Article.destroy({ where: { id: articleIdx } });
if (affectedCnt == 1) {
console.log("์ง์ง๋ก ๋ฐ์ดํฐ๊ฐ ์ญ์ ๋จ");
return res.json({ code: "200", data: affectedCnt, msg: "Ok" });
} else {
console.log("delete query๊ฐ ์คํ๋์์ง๋ง ์กฐ๊ฑด์ด ๋ง์ง์์ ์ญ์ ๋ ์๋จ...");
return res.json({ code: "500", data: affectedCnt, msg: "Delete Failed" });
}
} catch (err) {
return res.json({ code: "500", data: 0, msg: "์๋ฒ DB์ฒ๋ฆฌ ์คํ ์๋ฌ" });
}
});
module.exports = router;
<file_sep>/Day5/reactaxiosapp/src/components/TopMenu.js
import React from "react";
import { Link } from "react-router-dom";
const TopMenu = () => {
return (
<div style={{ width: "100%", height: "50px", backgroundColor: "gray" }}>
<span>
<Link to="/">ํ</Link>
</span>
<span>
<Link to="/about">ํ์ฌ ์๊ฐ</Link>
</span>
<span></span>
<span>
<Link to="/article/list">๊ฒ์๊ธ ๋ชฉ๋ก</Link>
</span>
<span>
<Link to="/member/list">
<span>ํ์ ๋ชฉ๋ก</span>
</Link>
</span>
<span>
<Link to="/member/login">๋ก๊ทธ์ธ</Link>
</span>
</div>
);
};
export default TopMenu;
<file_sep>/Day7/reactaxiosapp/src/helpers/authUtils.js
//jwt ํ ํฐ ํฐ์ฝ๋ฉ ํจํค์ง ์ฐธ์กฐ
import jwtDecode from "jwt-decode";
//์ฌ์ฉ์ ์ธ์ฆ ํ ํฐ ์กฐํํ๊ธฐ ์ ํธ ํจ์
const getJWTToken = () => {
const storageToken = window.localStorage.getItem("jwttoken");
if (storageToken != undefined) {
return storageToken;
} else {
return "";
}
};
//ํ์ฌ ์ฌ์ฉ์ ๋ก๊ทธ์ธ ์ฌ๋ถ ์ฒดํฌ ํจ์
const isMemberLogined = () => {
const storageToken = window.localStorage.getItem("jwttoken");
console.log("๋ก๊ทธ์ธ ์ํ ์ฒดํฌ ํ ํฐ =====>", storageToken);
if (storageToken != null) {
return true;
} else {
return false;
}
};
//JWT ํ ํฐ ๊ธฐ๋ฐ ๋ก๊ทธ์ธ ์ฌ์ฉ์ ์ ๋ณด ์ถ์ถ ํจ์
const getLoginMember = () => {
const storageToken = window.localStorage.getItem("jwttoken");
if (storageToken == undefined) {
return null;
}
//ํ ํฐ์์ ๋์ฝ๋ฉ๋ ๊ฐ์ ์ถ์ถํ๋ค.
const decoded = jwtDecode(storageToken);
const member = { email: decoded.email, username: decoded.username }; //TopMenu์์ ํธ์ถํ ๋ ํจ์๋ช
.email , ํจ์๋ช
.username ์ด๋ ๊ฒ ํธ์ถํด์ผ๊ฒ ์ฅฌ
return member;
};
//๋ชจ๋๋ก ์ถ๋ ฅํ๊ธฐ
export { getJWTToken, isMemberLogined, getLoginMember };
<file_sep>/Day4/reactroutingapp/src/About2.js
import React from "react";
//๋ผ์ฐํ
URL ์ฃผ์ ์ ๋ณด๋ฅผ ์์ฝ๊ฒ ๋ค๋ฃฐ ์ ์๋ useLocation ์ ๊ท ํ
์ฐธ์กฐ
import { useLocation } from "react-router-dom";
const About2 = () => {
const location = useLocation();
return <div>์ ์ฒด ์ฟผ๋ฆฌ์คํธ๋ง ๋ฌธ์์ด : {location.search}</div>;
};
export default About2;
<file_sep>/Day7/webzineadminapp/bin/www
#!/usr/bin/env node
/**
* Module dependencies.
*/
//๋
ธ๋ app.js ๋ชจ๋์ ์ฐธ์กฐํ๋ค.
//app.js ๋ชจ๋์ ๋
ธ๋ ์ดํ๋ฆฌ์ผ์ด์
์ ๊ฐ์ฅ ์ค์ํ ๋ชจ๋ํ์ผ๋ก ๋
ธ๋์ฑ์ ์๋น์ค ํ๊ฒฝ์ ๋ณด๋ฅผ ์ธํ
ํ๊ณ
//๋
ธ๋์ฑ ์ดํ๋ฆฌ์ผ์ด์
์ ๊ด๋ฆฌํ๋ ๋ชจ๋ํ์ผ์ด๋ค.
//app ์ node application ์ด๋ค
var app = require("../app");
//๋
ธ๋ ์ฑ์์ ๋๋ฒ๊น
์ ๋ณด๋ฅผ ์ฌ์ฉํ๊ณ ์ถ์๋ ์ฐธ์กฐ
var debug = require("debug")("webzineadminapp:server");
//๋
ธ๋ ํ๋ ์์ํฌ๋ด์ http์น์๋ฒ ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๋ค.
//htt๊ฐ์ฒด๋ฅผ ํตํด ๋
ธ๋์น์ฌ์ดํธ๋ฅผ ๊ตฌ์ฑํ๊ณ ์๋น์คํ๋ค.
var http = require("http");
/**
* Get port from environment and store in Express.
*/
//๋
ธ๋์ฑ ์๋น์ค ํฌํธ ์ง์ ํ๊ธฐ
//
var port = normalizePort(process.env.PORT || "3005");
app.set("port", port);
/**
* ๋
ธ๋์ฑ์ ์๋น์คํ ์น์๋ฒ ๋ฐ ์น์ฌ์ดํธ ๊ตฌ์ฑ
*/
var server = http.createServer(app);
/**
* Listen on provided port, on all network interfaces.
*/
//์๋ฒ์ ์ฌ๋ผ์จ ๋
ธ๋์ฑ์ ์ง์ ํ ํฌํธ๋ฅผ ํตํด ์ฌ์ฉ์ ํธ์ถ์ ์์ ๋๊ธฐํ๋ค.
server.listen(port);
//๋
ธ๋์ฑ์ ๋ํ ํธ์ถ์๋ฌ๊ฐ ๋ฐ์ํ๋ฉด onError ์ด๋ฒคํธ ์ฒ๋ฆฌ ํจ์์ ๊ด๋ จ์๋ฌ์ ๋ณด๋ฅผ ์ ๋ฌํ๋ค.
server.on("error", onError);
//์ฌ์ฉ์ ์์ฒญ์ ๋ํ ์ธ์์ ์ํด ๋ฆฌ์ฐ๋ ์ด๋ฒคํธ๋ฅผ ๊ฑธ๊ณ ๋ชจ๋ ์ฌ์ฉ์ ์์ฒญ์ ๋ชจ๋ํฐ๋งํ๊ณ
//๋ชจ๋ ์ฌ์ฉ์ ์์ฒญ์ ๋ํ ์ ์ด๊ฐ ๊ฐ๋ฅํ๋ค.
server.on("listening", onListening);
/**
* Normalize a port into a number, string, or false.
* ๊ธฐ๋ณธ ํฌํธ ์ค์ ํจ์
*/
function normalizePort(val) {
var port = parseInt(val, 10);
if (isNaN(port)) {
// named pipe
return val;
}
if (port >= 0) {
// port number
return port;
}
return false;
}
/**
* ์ฌ์ฉ์ ์์ฒญ์ ๋ํ ์๋ฒ์์์ ์๋ฌ ๊ฐ์ง ๋ฐ ์ฒ๋ฆฌ๋ฅผ ์ํ ์๋ฌ๋ฐ์ ์ด๋ฒคํธ ์ฒ๋ฆฌ ํจ์
* ์น์๋ฒ ๋ฐ ์น์ฌ์ดํธ ํต์ ์์ ์๋ฌ๋ฐ์ํ๋ฉด ํด๋น ์๋ฌ๋ฅผ ๊ฐ์งํ๊ณ ์ฒ๋ฆฌํ๋ค.
*/
function onError(error) {
if (error.syscall !== "listen") {
throw error;
}
var bind = typeof port === "string" ? "Pipe " + port : "Port " + port;
// handle specific listen errors with friendly messages
switch (error.code) {
case "EACCES":
console.error(bind + " requires elevated privileges");
process.exit(1);
break;
case "EADDRINUSE":
console.error(bind + " is already in use");
process.exit(1);
break;
default:
throw error;
}
}
/**
* Event listener for HTTP server "listening" event.
* ๋ชจ๋ ์ฌ์ฉ์ ์์ฒญ์ ๋ํ ๋ชจ๋ํฐ๋ง ํจ์(ํ์์ ์์ฒญ์ ๋ณด ๊ธฐ๋ก ๋ฐ ๋๋ฒ๊น
๊ฐ๋ฅ)
*/
function onListening() {
var addr = server.address();
var bind = typeof addr === "string" ? "pipe " + addr : "port " + addr.port;
debug("Listening on " + bind);
}
<file_sep>/Day6/reduxsampleapp/src/redex/todos/reducers.js
//STEP1)TODO_ADD ์ก์
ํ์
์์ ์ฐธ์กฐ
import {
TODO_ADD,
TODO_NEW_ITEM,
TODO_LIST,
} from "../../constants/actionTypes";
//STEP2-1) ๋ฆฌ๋์ ํจ์์์ ์ฌ์ฉํ ์ ์ญ ๋ฐ์ดํฐ์ ๊ตฌ์กฐ ์ ์ ๋ฐ ๊ฐ ์ด๊ธฐํ
const INIT_STATE = {
todoCount: 0,
todoItem: {},
todoList: [],
};
//STEP2-2)์ก์
์ ํ์คํ๋ ๊ธฐ๋ณธ ํ์์ ์ ์ํ๋ค.
type TodoAction = { type: string, payload: {} | string };
//์ด๊ธฐ๊ฐ ์ธํ
์์ญ
//type State = { todoCount?: 0 | null }; //, todoList?: [] | null
//STEP3) ๋ฆฌ๋์ ํจ์ ์ ์ ๋ฐ ๊ธฐ๋ฅ ๊ตฌํ
//๋ฆฌ๋์ ํจ์๋ช
= (state: ์ ์ญ ๋ฐ์ดํฐ ๊ตฌ์กฐ ์ ์ ๋ฐ ์ด๊ธฐ๊ฐ ์ธํ
ํ๊ธฐ = INIT_STATE, action: ๋ฆฌ๋์์์ ์ฌ์ฉํ๋ ์ก์
ํจ์) => {์ก์
ํ์
๋ณ ๊ธฐ๋ฅ ์ ์};
//๋ฆฌ๋์ ํจ์์ ์ ๋ฌ๋๋ ๋ฐ์ดํฐ๋ ์ ์ํ ๊ฐ์ฒด ๊ตฌ์กฐ ๋ฐ ์ด๊ธฐํ ์ธํ
, ์ก์
ํ์
//๋ฆฌ๋์ ํจ์ (state: ์ ์ญ ๋ฐ์ดํฐ ๊ตฌ์กฐ ์ ์ ๋ฐ ์ด๊ธฐํ ๊ฐ์ฒด, action:๋งตํ๋๋ ์ก์
ํ์
)
//ํ ์ผ ๊ฑด์๋ง ์ ์ญ์ผ๋ก ๊ด๋ฆฌํ๋ ๋ฆฌ๋์ ํจ์
const ToDo = (state: INIT_STATE, action: TodoAction) => {
switch (action.type) {
case TODO_ADD:
//todoCount๋ฅผ ๊ด๋ฆฌํ๋ ์ ์ญ state์ ๋ณต์ฌ๋ณธ์ ๋ง๋ค๊ณ , ์์ todoCount์์ฑ๊ฐ์ action์์ ์ ๋ฌ๋ count๊ฐ์ผ๋ก ์
๋ฐ์ดํธ ํ๋ค.
return { ...state, todoCount: action.payload.todoCount };
case TODO_NEW_ITEM:
return { ...state, todoItem: action.payload.todoItem };
case TODO_LIST:
return { ...state, todoList: action.payload.todoList };
default:
return { ...state };
}
};
//Todo๋ฆฌ๋์ ํจ์๋ฅผ ๋
ธ์ถํ๋ค
export default ToDo;
<file_sep>/Day7/webzineadminapp/models/articlefile.js
module.exports = (sequelize,DataTypes)=>{
return sequelize.define('articlefile',{
articleid:{
type:DataTypes.INTEGER,
allowNull:false
},
filepath:{
type:DataTypes.STRING(200),
allowNull:false
},
filename:{
type:DataTypes.STRING(200),
allowNull:false
}
},{
timestamps:true,
paranoid:true
});
};<file_sep>/Day7/reactaxiosapp/src/redux/reducers.js
//์
๋ฌด ๋ณ๋ก ์์ฑํ ๊ฐ ์ข
์ก์
ํ์ผ์ ํ๋์ ์ก์
ํ์ผ๋ก ํตํฉํ๋ค.
//import Article from "./article/reducers";
//๊ฐ ์ข
๋ฆฌ๋์ ํ์ผ์ ํตํฉํด์ฃผ๋ combineReducersํจ์๋ฅผ ์ฐธ์กฐํ๋ค.
import { combineReducers } from "redux";
import Login from "./login/reducers";
export default combineReducers({ Login });
//export default combineReducers({Login, Article}); ๋ ๊ฐ ํ ๋๋ ์ด๋ ๊ฒ
<file_sep>/Day6/reduxsampleapp/src/redex/actions.js
//์
๋ฌด ๋ณ๋ก ์์ฑํ ๊ฐ ์ข
์ก์
ํ์ผ์ ํ๋์ ์ก์
ํ์ผ๋ก ํตํฉํ๋ค.
export * from "./todos/actions/";
//export * from "./login/actions/";
<file_sep>/Day6/reduxsampleapp/src/redex/reducers.js
//์
๋ฌด ๋ณ๋ก ์์ฑํ ๊ฐ ์ข
์ก์
ํ์ผ์ ํ๋์ ์ก์
ํ์ผ๋ก ํตํฉํ๋ค.
//๊ฐ ์ข
๋ฆฌ๋์ ํ์ผ์ ํตํฉํด์ฃผ๋ combineReducersํจ์๋ฅผ ์ฐธ์กฐํ๋ค.
import { combineReducers } from "redux";
//todos/reducer.jsํ์ผ์์ ๋
ธ์ถํ ToDo ๋ฆฌ๋์ ํจ์๋ฅผ ์ฐธ์กฐํ๋ค.
import ToDo from "./todos/reducers";
//import Login from "./login/reducers";
export default combineReducers({ ToDo });
//export default combineReducers({ ToDo ,Login});
<file_sep>/Day7/webzineadminapp/models/member.js
module.exports = (sequelize,DataTypes)=>{
return sequelize.define('member',{
email:{
type:DataTypes.STRING(50),
allowNull:false
},
userpwd:{
type:DataTypes.STRING(100),
allowNull:false
},
nickname:{
type:DataTypes.STRING(50),
allowNull:false
},
entrytype:{
type:DataTypes.STRING(10),
allowNull:false
},
snsid:{
type:DataTypes.STRING(50),
allowNull:true
},
username:{
type:DataTypes.STRING(50),
allowNull:true
},
telephone:{
type:DataTypes.STRING(20),
allowNull:true
},
photo:{
type:DataTypes.STRING(100),
allowNull:false
},
lastip:{
type:DataTypes.STRING(20),
allowNull:false
},
usertype:{
type:DataTypes.STRING(1),
allowNull:false
},
userstate:{
type:DataTypes.STRING(1),
allowNull:false
}
},{
timestamps:true,
paranoid:true
});
};<file_sep>/Day4/reactroutingapp/src/Profiles.js
import React from "react";
import { Link, Route } from "react-router-dom";
// ์์ ์ปดํฌ๋ํธ ์ฐธ์กฐ
import Profile from "./Profile";
import WithRouterSample from "./WithRouterSample";
//์ด๋ฏธ ๋ผ์ฐํ
๋ ์ปดํฌ๋ํธ ์์์ ๋ค๋ฅธ ์ปดํฌ๋ํธ๋ฅผ ๋ผ์ฐํ
ํ ์ ์๋ค.
//SubRouting์ ์ด์ฉํด ๋ผ์ฐํ
๋ ์ปดํฌ๋ํธ ์์์ ์๋ธ ๋ผ์ฐํ
์ ์ค์ํ๋ค.
const Profiles = () => {
return (
<div>
<h3>์ฌ์ฉ์ ๋ชฉ๋ก</h3>
<ul>
<li>
<Link to="/profiles/user1">user1</Link>
</li>
<li>
<Link to="/profiles/user2">user2</Link>
</li>
</ul>
{/* ์๋ธ ๋ผ์ฐํ
์ ์ด์ฉํด ์ง์ ์ปดํฌ๋ํธ๋ฅผ ๋ก๋ฉํ๋ค. */}
<Route path="/profiles/:username" component={Profile}></Route>
<WithRouterSample></WithRouterSample>
</div>
);
};
export default Profiles;
<file_sep>/Day4/functionhooksapp/src/UseCallbackHook.js
import React, {
useState,
useReducer,
useMemo,
useRef,
useCallback,
} from "react";
//useCallback ํ
์ ์ด๋ฒคํธ ๋ฐ์ ์ ํธ์ถํ๋ ์ด๋ฒคํธ ์ฒ๋ฆฌ (ํธ๋ค๋ฌ) ํจ์์ ์์ฑ์
//์ปดํฌ๋ํธ๊ฐ ๋๋๋ง ๋ ๋๋ง๋ค ํด๋น ํจ์๊ฐ ์์ฑ๋๋ ๊ฒ์ ๋ฐฉ์งํ์ฌ ๋ฆฌ์กํธ ์ฑ๋ฅ์ ๊ฐ์ ์์ผ์ค๋ค.
const getAverage = (numbers) => {
console.log("ํ๊ท ๊ฐ ๊ณ์ฐํ๋ ์ค.....");
if (numbers.length === 0) return 0;
//๋ฐฐ์ด์ reduce๋ฉ์๋๋ ๋ฐฐ์ด ์์ ๊ฐ์ ๋ชจ๋ ํฉ์น ์ดํฉ๊ณ๋ฅผ ๋ฐํํ๋ค.
const sum = numbers.reduce((a, b) => a + b);
//๋ฐฐ์ด์ ๊ฑด์๋ก ์ดํฉ์ ๋๋์ด ํ๊ท ๊ฐ์ ๋ฐํํ๋ค.
return sum / numbers.length;
};
const UseCallbackHook = () => {
const [list, setList] = useState([]);
const [number, setNumber] = useState("");
const avg = useMemo(() => getAverage(list), [list]);
console.log(
"ํ๋ฉด์ ๋ณ๊ฒฝ์ด ๋ฐ์ํ ๋๋ง๋ค ํ๊ธฐ onChangeData, onInsert ์ด๋ฒคํธ ์ฒ๋ฆฌ๊ธฐ ํจ์๋ฅผ ์์ฑํฉ๋๋ค."
);
//ํด๋น ์ปดํฌ๋ํธ๊ฐ ์ต์ด ์ฒซ๋ฒ์งธ๋ก ๋๋๋ง ๋ ๋๋ง ํด๋น ์ด๋ฒคํธ ํจ์๋ฅผ ์ถ๊ฐํด์ค๋ค.
//onChangeData ์ด๋ฒคํธ ์ฒ๋ฆฌํจ์๋ฅผ ํด๋น ์ปดํฌ๋ํธ๊ฐ ์ต์ด ์์ฑ๋ ๋์๋ง ํจ์๋ฅผ ์์ฑํ๋ค.
//์ต์ด ๋๋๋ง ์ดํ UI์์์ ๋ณ๊ฒฝ์ด ๋ฐ์ํ ๋๋ง๋ค ํด๋น ์ด๋ฒคํธ ์ฒ๋ฆฌํจ์๋ ์์ฑ๋์ง ์๋๋ค.
const onChangeData = useCallback((e) => {
setNumber(e.target.value);
}, []); //[]:๋น ๋ฐฐ์ด ==> ์ต์ด ์คํ ์ ํ ๋ฒ
//number,list useState์ ๊ฐ์ด ๋ณ๊ฒฝ๋ ๋๋ง๋ค ํด๋น ์ด๋ฒคํธ ์ฒ๋ฆฌ ํจ์๊ฐ ์์ฑ๋๋ค.
const onInsert = useCallback(() => {
const nextList = list.concat(parseInt(number));
setList(nextList);
setNumber("");
}, [number, list]);
return (
<div>
<input type="text" value={number} onChange={onChangeData}></input>
<button onClick={onInsert}>๋ฑ๋ก</button>
<hr></hr>
{list.map((value, index) => (
<li key={index}>{value}</li>
))}
<hr></hr>
<div>
<b>ํ๊ท ๊ฐ : {avg}</b>
</div>
</div>
);
};
export default UseCallbackHook;
<file_sep>/Day7/reactaxiosapp/src/pages/members/Login.js
import React, { useState } from "react";
import axios from "axios";
//dispatch๊ด๋ จ) ๋ฆฌ๋์ค : ์ก์
์คํ ํจ์๋ฅผ ์์
๊ฒ ํธ์ถํ๊ธฐ ์ํ useDispatchํ
์ ์ฐธ์กฐํ๋ค.
import { useDispatch } from "react-redux";
//dispatch๊ด๋ จ) ๋์คํจ์น๋ฅผ ์ํ ๋ฆฌ๋์ค ์ก์
์คํ ํจ์๋ฅผ ์ฐธ์กฐํ๋ค.
import { memberLogin } from "../../redux/actions";
const Login = () => {
const [login, setLogin] = useState({
email: "",
userpwd: "",
});
//dispatch๊ด๋ จ) ์ ์ญ ๋ฐ์ดํฐ ์ ์ด์ฉ ๋์คํจ์น ์์ ์์ฑ
const globalDispatch = useDispatch();
const onLoginChange = (e) => {
setLogin({ ...login, [e.target.name]: e.target.value });
};
const onLogin = () => {
// ๋ฐฑ์๋ ๋ก๊ทธ์ธ ํ ์ฌ์ฉ์ ์ ๋ณด์ ํ ํฐ์ ๋ณด๋ฅผ ๊ฐ์ ธ์จ๋ค.
axios
.post("http://localhost:3005/api/member/login", login)
.then((res) => {
if (res.data.code === "200") {
console.log("JWTํ ํฐ๊ฐ: ", res.data.data.token);
console.log("๋ก๊ทธ์ธ ์ฌ์ฉ์ ์ ๋ณด : ", res.data.data.member);
//ํ ํฐ ์ ์ฅ ๋ฐฉ๋ฒ 2)์น ๋ธ๋ผ์ฐ์ ๋ก์ปฌ ์คํ ๋ฆฌ์ง์ ํ ํฐ ๊ฐ ๋ณด๊ดํ๊ธฐ //๋ก์ปฌ ์คํ ๋ฆฌ์ง์ ๋ณด๊ดํ๋ฉด ์ด๋ค ์ปดํฌ๋ํธ์์๋ ํ ํฐ ๊ฐ ๊ฐ์ง ์ ์์(์ฐฝ์ ๋ซ์๋ ์ ์ง๊ฐ ๋จ : ๊ฐ๋ฐ์๋ชจ๋(F12) ->Application->storage์์ ํ์ธ ๊ฐ๋ฅ )
window.localStorage.setItem("jwttoken", res.data.data.token);
const storageToken = window.localStorage.getItem("jwttoken");
console.log("๋ธ๋ผ์ฐ์ ๋ก์ปฌ ์คํ ๋ฆฌ์ง์ ์ ์ฅ๋ ํ ํฐ : ", storageToken);
//ํ ํฐ ์ ์ฅ ๋ฐฉ๋ฒ 1)
//์ฌ์ฉ์ ํ ํฐ ๋ฐ๊ธ ํ ๋ฐฑ์๋ API ํธ์ถ ์ ๋ฐ๊ธ๋ JWT ํ ํฐ์ Ajax ํค๋์ "x-access-token" ์์ญ์ ๊ธฐ๋ณธ ํฌํจ์์ผ ๋ฐฑ์๋ ์๋น์ค๋ฅผ ํธ์ถํ๊ธฐ ํ๋ค.
//์คํAPI ์ฌ์ฉ ์ ํ ํฐ์ด ์๋ ์ฌ๋๋ง ์ ๊ทผํ ์ ์๊ฒ ํ๊ธฐ ์ํจ.
axios.defaults.headers.common[
"x-access-token"
] = `${res.data.data.token}`;
//dispatch๊ด๋ จ)globalDispatch(์ก์
์์ฑ ํจ์๋ช
(์ก์
์์ฑ ํจ์์ ์ ๋ฌ๋ ๋ฐ์ดํฐ))
globalDispatch(memberLogin(res.data.data.token));
alert("์ ์ ๋ก๊ทธ์ธ ๋์์ต๋๋ค.");
} else {
// ์๋ฒ์ธก ์๋ฌ ๋ฉ์ธ์ง ์ถ๋ ฅ
alert(res.data.msg);
}
})
.catch(() => {});
// ๊ฐ์ ธ์จ ์ ๋ณด๋ฅผ ์ ์ญ ๋ฐ์ดํฐ ์ ์ฅ์์ ์ ์ญ์คํ
์ดํธ ์ ๋ณด๋ก ์
๋ฐ์ดํธ ํ๋ค.
};
return (
<div>
<h1>๋ก๊ทธ์ธ ํ์ด์ง</h1>
<span>๋ฉ์ผ ์ฃผ์</span>
<input
type="text"
name="email"
value={login.email}
onChange={onLoginChange}
/>
<br></br>
<span>์ํธ</span>
<input
type="password"
name="userpwd"
value={login.userpwd}
onChange={onLoginChange}
/>
<br></br>
<button onClick={onLogin}>๋ก๊ทธ์ธ</button>
</div>
);
};
export default Login;
<file_sep>/Day4/reactroutingapp/src/About.js
import React from "react";
//querystring ํจํค์ง ์ฐธ์กฐ
import qs from "qs";
//๋ฆฌ์กํธ์์ URL QueryString๊ฐ์ ์ฝ๊ฒ ์ถ์ถํ๊ธฐ ์ํด qs ๋
ธ๋ ํจํค์ง๋ฅผ ํ๋ก์ ํธ์ ์ถ๊ฐ ์ค์นํ๋ค.
//yarn add qs
//ํ์ฌ ์๊ฐ ํ๋ฉด ์ปดํฌ๋ํธ
const About = ({ location }) => {
//qs.parse(URL๋ด querystring ๋ฌธ์์ด์ ํ์ฑํ์ฌ key๊ฐ์ผ๋ก ์ถ์ถํ ์ ์๊ฒ query ๊ฒฐ๊ณผ๋ฌผ์ ์์ฑํ๋ค.);
//ex) ?test=a&uid=test&stock=3
//ignoreQueryPrefix:true ์ด๋ฉด ์๊ธฐ query๋ฌธ์์ด์์ ?์ ์ ๊ฑฐํ๋ ๊ฒ
const query = qs.parse(location.search, { ignoreQueryPrefix: true });
//query์กฐํ ๊ฒฐ๊ณผ๊ฐ์ด ๋ฌธ์์ด๋ก ๋ฐํ๋๋ค.
//?detail=aaa ์ผ ๋, showDetail ๊ฐ์ aaa๊ฐ ๋๋ค.
//query.์ฟผ๋ฆฌ๊ฐ์ ์ง์ ํด ํด๋น ๊ฐ์ ์ถ์ถํ๊ณ ๋ฌธ์์ด๋ก ํด๋น๊ฐ์ ๋ฐ๋๋ค.
//query.detail ๊ฐ์ ๋ฌด์กฐ๊ฑด ๋ฌธ์์ด ture๋ก ๋ณํ.
const showDetail = query.detail === "true";
const qid = query.qid;
return (
<div>
<h1>ํ์ฌ ์๊ฐ</h1>
<p>ํ์ฌ์๊ฐ ํ์ด์ง์
๋๋ค. </p>
<p>{showDetail && <p>detail ๊ฐ์ true๋ก ์ค์ ํ๋ค์.</p>}</p>
<p>์ ๋ฌ ํ๋ผ๋ฉํฐ QID = {qid}</p>
</div>
);
};
export default About;
<file_sep>/Day4/functionhooksapp/src/UseReducerHook.js
//useReducer์ ์ฐธ์กฐํ๋ค.
import React, { useReducer } from "react";
//UseReducer ํ
์ useState์ ๋์ผํ๊ฒ ๋ฐ์ดํฐ ์ํ๊ด๋ฆฌ๋ฅผ ๋ชฉ์ ์ผ๋ก ํ๋ฉฐ, ์ํ๊ด๋ฆฌ ๋ฐ ์ฒ๋ฆฌ ์์ญ์ ๋ณ๋์ reducerํจ์๋ฅผ ์ ์ํด์ ์ฒ๋ฆฌํ๊ณ
//ํจ์ํ ์ปดํฌ๋ํธ ์ธ๋ถ์์ ์ ์ํ๊ธฐ์ ํด๋น reducerํจ์์ ์ฌ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค.
//useState๋ ํด๋น ์ปดํฌ๋ํธ ๋ด์์๋ง ์ฌ์ฉ์ด ๊ฐ๋ฅํ์ง๋ง, UseReducer ํจ์๋ ์ฌ๋ฌ ์ปดํฌ๋ํธ์์ ์ฌ์ฉ์ด ๊ฐ๋ฅํ๋ค.
//reducerํจ์์ ์ก์
๊ธฐ๋ฅ์ ์ด์ฉํด์ ํ๋์ ํจ์์์ ์ฌ๋ฌ ์์ฑ์ ์กฐ๊ฑด๋ณ ์ํ๊ฐ ๊ด๋ฆฌ๊ฐ ๊ฐ๋ฅํจ.
//reducerํจ์ (์ํ๊ฐ, ์ก์
ํจ์){}
//reducerํจ์์ action์ type์ ์ด์ฉํด์ ์ํ๊ฐ์ ๋ฐํ๋ฐ๋๋ฐ,
//useState๋ฅผ ์ด์ฉํ๋ฉด ๊ฐ๋ณ๋ก ์ธํฐํจ์๋ฅผ ์ ์ํด์ผ ํจ
//useReducer๋ฅผ ์ด์ฉํ๋ฉด ๋ค์ํ ์ผ์ด์ค ๋ณ๋ก ์ํ๊ฐ ์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅํ๋ค.
function counterReducer(state, action) {
//์ก์
์ ์ ํ๋ณ๋ก ์ํ๊ฐ์ ๊ตฌ๋ถํ์ฌ ์ ๋ฌํ ์ ์๋ค.
switch (action.type) {
case "INCREMENT":
return { value: state.value + 1 };
case "DECREMENT":
return { value: state.value - 1 };
case "INIT":
//๋ค์ํ ์ผ์ด์ค ๋ณ๋ก ์ํ๊ฐ์ ๋น์ฆ๋์ค ๋ก์ง์ ์ ์ฉํ๊ณ ์ถ์ ๋
return { value: 0 };
case "PLUS1000":
//๋ค์ํ ์ผ์ด์ค ๋ณ๋ก ์ํ๊ฐ์ ๋น์ฆ๋์ค ๋ก์ง์ ์ ์ฉํ๊ณ ์ถ์ ๋
return { value: state.value + 1000 };
case "DIVIDE":
//๋ค์ํ ์ผ์ด์ค ๋ณ๋ก ์ํ๊ฐ์ ๋น์ฆ๋์ค ๋ก์ง์ ์ ์ฉํ๊ณ ์ถ์ ๋
return { value: state.value / 2 };
default:
return state;
}
}
//์ฌ์ฉ์ ์ ๋ณด ๊ด๋ฆฌ reducerํจ์ /// ์ฌ์ฉ์ ์ ๋ณด ๊ด๋ฆฌ useReducer์ ์ํ user ๊ฐ์ฒด๊ฐ state๋ก ๋์ด์ด
//ํ๋ฉด ์
๋ ฅ ์์์ ๊ฐ์ ์กฐ๊ฑด๋ณ๋ก ์ด๊ธฐํํ๊ฑฐ๋ ์
๋ ฅ ์์ ์ ํ์ ๋ฐ๋ฅธ state๊ฐ์ ์ ์ดํ๋ ๋ค์ํ ์ผ์ด์ค ๋ณ๋ก user์ ๋ณด๋ฅผ ๊ด๋ฆฌํ๋ค.
function userReducer(state, action) {
switch (action.type) {
case "init":
return { ...state, userid: "", username: "", email: "", isadmin: false };
case "text":
return { ...state, [action.name]: action.value };
case "checkbox":
return { ...state, [action.name]: action.checked };
case "changeadmin":
return { ...state, isadmin: true };
default:
return state;
}
}
const UseReducerHook = () => {
//const[ ์ํ๋ช
, reducerํจ์ ์คํ ์ฒ๋ฆฌ ๋ช
๋ น์ด(ํต์์ ์ผ๋ก dispatch~ ๋ง๋ฆ) ] = useReducer(reducerํจ์, ์ด๊ธฐ๊ฐ ์ค์ );
const [counter, dispatchCounter] = useReducer(counterReducer, { value: 0 });
//์ฌ์ฉ์ ์ ๋ณด ๊ด๋ฆฌ useReducer์ ์
const [user, dispatchUser] = useReducer(userReducer, {
userid: "",
username: "",
email: "",
isadmin: false,
});
const onChangeUser = (e) => {
//reducerํจ์๋ฅผ ์คํ์ํจ๋ค.
dispatchUser(e.target);
};
const onSave = () => {};
const onInit = () => {
dispatchUser({ type: "init" });
};
return (
<div>
<p>
ํ์ฌ ์นด์ดํฐ ๊ฐ์ :<b>{counter.value}</b>
</p>
{/* reducer dispatchํจ์๋ช
์ ์ธํ
๋ reducerํจ์๋ฅผ ํธ์ถํ ๋ ์ฌ์ฉํ๋ค.
dispatchํจ์๋ช
์ ํ๋ผ๋ฉํฐ๋ก action type ์์ฑ์ ๊ฐ์ ์ง์ ํด ์ ๋ฌํ ์ ์๋ค. */}
<button onClick={() => dispatchCounter({ type: "INCREMENT" })}>
์ฆ๊ฐ
</button>
<button onClick={() => dispatchCounter({ type: "DECREMENT" })}>
๊ฐ์
</button>
<button onClick={() => dispatchCounter({ type: "INIT" })}>์ด๊ธฐํ</button>
<button onClick={() => dispatchCounter({ type: "PLUS1000" })}>
1000+
</button>
<button onClick={() => dispatchCounter({ type: "DIVIDE" })}>
2๋ก ๋๋๊ธฐ
</button>
<hr></hr>
์ฌ์ฉ์ ์์ด๋ :
<input
type="text"
name="userid"
value={user.userid}
onChange={onChangeUser}
/>
์ฌ์ฉ์ ์ด๋ฆ :
<input
type="text"
name="username"
value={user.username}
onChange={onChangeUser}
/>
์ฌ์ฉ์ ๋ฉ์ผ ์ฃผ์ :
<input
type="text"
name="email"
value={user.email}
onChange={onChangeUser}
/>
๊ด๋ฆฌ์ ์ฌ๋ถ :
<input
type="checkbox"
name="isadmin"
checked={user.isadmin}
onChange={onChangeUser}
/>
<button onClick={onSave}>์ ์ฅ</button>
<button onClick={onInit}>์ด๊ธฐํ</button>
<button onClick={() => dispatchUser({ type: "changeadmin" })}>
๊ด๋ฆฌ์๋ก ๋ณ๊ฒฝํ๊ธฐ
</button>
</div>
);
};
export default UseReducerHook;
<file_sep>/Day4/reactroutingapp/src/App.js
import logo from "./logo.svg";
import "./App.css";
//๋ผ์ฐํ
์ ์ํ Router ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๋ค.
import { Route, Link } from "react-router-dom";
//ํ๋ฉด ์ปดํฌ๋ํธ๋ฅผ ์ฐธ์กฐํ๋ค.
import Home from "./Home";
import About from "./About";
import Profile from "./Profile";
import Profiles from "./Profiles";
import About2 from "./About2";
function App() {
return (
<div>
<ul>
<li>
<Link to="/">ํ</Link>
</li>
<li>
<Link to="/about?detail=true&qid=aaaaaa">ํ์ฌ์๊ฐ</Link>
</li>
<li>
<Link to="/company?qid=bbbb">ํ์ฌ์๊ฐ2-company</Link>
</li>
<li>
{/* profile ๋ผ์ฐํ
์ฃผ์์ user1์ด๋ผ๋ ํ๋ผ๋ฉํฐ ์ ๋ฌ */}
<Link to="/profile/user1">ํ์์๊ฐ</Link>
</li>
<li>
<Link to="/about2?detail=true&qid=aaaaaa">ํ์ฌ์๊ฐ</Link>
</li>
</ul>
<hr></hr>
{/* Route ๊ฐ์ฒด์ path๋ routing ์ฃผ์๋ฅผ ์ ์ํ๊ณ ํด๋น ์ฃผ์๋ฅผ ๋ธ๋ผ์ฐ์ ์์ ์กฐํํ๋ฉด ํด๋น ์ง์ ๋ ์ปดํฌ๋ํธ๊ฐ App์ ๋
ธ์ถ๋๋ค. */}
{/* /about ๊ฒฝ๋ก๋ ๊ธฐ๋ณธ์ ์ผ๋ก /๊ฒฝ๋ก๋ฅผ ํฌํจํ๊ณ ์์ด ํ๊ณผ ํ์ฌ์๊ฐ ์ปดํฌ๋ํธ๊ฐ ๋ ๋ค ๋ํ๋๊ฒ ๋๋ค.
ํ ์ปดํฌ๋ํธ ๋ผ์ฐํ
์์ฝpropst ์ค์ exact๊ฐ์ true๋ก ์ค์ ํ๊ฒ ๋๋ฉด /๋ง ํ๊ธฐํ์ ๋๋ง ํ์ด ๋ํ๋๊ฒ ๋๋ค. */}
<Route path="/" component={Home} exact={true}></Route>
{/* ๋์ผํ ํ๋ฉด ์ปดํฌ๋ํธ๋ฅผ ์ฌ๋ฌ ๊ฐ์ ๋ผ์ฐํ
์ฃผ์๋ก ์๋น์คํ ์ ์๋ค. */}
<Route path="/company" component={About}></Route>
<Route path="/about" component={About}></Route>
<Route path="/about2" component={About2}></Route>
{/* URL์ฃผ์์ ํฌํจ์์ผ ์ ๋ฌํ ํ๋ผ๋ฉํฐ ๊ฐ์ ๋ํด ์์ผ๋์นด๋๋ก ํ๋ผ๋ฉํฐ๋ช
์ ๋ช
์ํ๋ค. */}
<Route path="/profile/:username" component={Profile}></Route>
{/* ์๋ธ ๋ผ์ฐํ
์์ ์ปดํฌ๋ํธ */}
<Route path="/profiles" component={Profiles}></Route>
</div>
);
}
export default App;
<file_sep>/Day7/reactaxiosapp/src/pages/members/MemberList.js
import React, { useEffect, useState } from "react";
import axios from "axios";
import { useHistory } from "react-router";
const MemberList = () => {
const [memberList, setMemberList] = useState([]); //์๋ฒ์์ ๊ฐ์ ธ์ฌ ๊ฑฐ๋๊น ๋น ๋ฐฐ์ด๋ก
//useHistory ์ฌ์ฉ
const history = useHistory();
//์ต์ด ์ปดํฌ๋ํธ๊ฐ ๋๋๋ง ๋ ๋ ๋ฐฑ์๋์์ ์ฌ์ฉ์ ๋ชฉ๋ก ๋ฐ์ดํฐ๋ฅผ ๊ฐ์ ธ์จ๋ค.
useEffect(() => {
//axios๋ก ์ฌ์ฉ์ ๋ชฉ๋ก์ ํธ์ถํ๋ค.
axios
.get("http://localhost:3005/api/member")
.then((res) => {
console.log("๋ฐฑ์๋์์ ์ ๊ณต๋ ํ์ ์ ์ฒด ๋ฐ์ดํฐ : ", res);
if (res.data.code === "200") {
//๋ฐฑ์๋ ํ์ ๋ชฉ๋ก ๋ฐ์ดํฐ ๋ฐ์ธ๋ฉ ์ฒ๋ฆฌ
setMemberList(res.data.data);
} else {
alert("๋ฐฑ์๋ ์๋ฌ ๋ฐ์");
}
})
.catch(() => {});
}, []);
return (
<div>
<h1>ํ์ ๋ชฉ๋ก ํ์ด์ง</h1>
<button
onClick={() => {
history.push("/member/regist");
}}
>
ํ์ ๋ฑ๋ก
</button>
<table>
<thead>
<tr>
<th>๊ณ ์ ๋ฒํธ</th>
<th>๋ฉ์ผ์ฃผ์</th>
<th>์ด๋ฆ</th>
<th>์ ํ๋ฒํธ</th>
<th>๊ฐ์
์ผ์</th>
</tr>
</thead>
<tbody>
{memberList.map((item, index) => (
<tr key={index}>
<td>{item.id}</td>
<td>{item.email}</td>
<td>{item.username}</td>
<td>{item.telephone}</td>
<td>{item.createdAt}</td>
</tr>
))}
</tbody>
</table>
</div>
);
};
export default MemberList;
<file_sep>/Day7/reactaxiosapp/src/pages/members/MemberRegist.js
import React, { useState } from "react";
import axios from "axios";
import { useHistory } from "react-router";
//๊ฐ ์ข
์ ํธ๋ฆฌํฐ ํจ์๋ฅผ ์ฐธ์กฐํ๋ค.
import {
getJWTToken,
isMemberLogined,
getLoginMember,
} from "../../helpers/authUtils";
const MemberRegist = () => {
const [member, setMember] = useState({
email: "",
userpwd: "",
nickname: "",
telephone: "",
username: "",
entrytype: "1",
photo: "",
});
const history = useHistory();
//๋ก๊ทธ์ธ ์ฌ๋ถ ์ฒดํฌ
const isLogin = isMemberLogined();
//๋ก๊ทธ์ธ์ด ์ ๋ ์ํ๋ก ํ์ ๋ฑ๋ก ํ์ด์ง์ ์์ ๊ฒฝ์ฐ ๋ก๊ทธ์ธ ํ ์ ์๊ฒ ๋ก๊ทธ์ธ ํ์ด์ง๋ก ๋ณด๋
if (isLogin === false) {
history.push("/login");
}
const onMemberChange = (e) => {
setMember({ ...member, [e.target.name]: e.target.value });
};
const onSave = () => {
//ํ์ ์ ๋ณด ์ ์ฅํ๊ธฐ
axios
.post("http://localhost:3005/api/member", member)
.then((res) => {
console.log("๋ฐ์ดํฐ ์ฒ๋ฆฌ ๊ฒฐ๊ณผ : ", res.data);
alert("ํ์ ๋ฑ๋ก ์๋ฃ");
history.push("/member/list");
})
.catch((err) => {
console.error(err);
});
};
return (
<div>
<h1>ํ์ ๋ฑ๋ก ํ์ด์ง</h1>
์ด๋ฉ์ผ:
<input
type="text"
name="email"
value={member.email}
onChange={onMemberChange}
/>
<hr></hr>
์ํธ:
<input
type="text"
name="userpwd"
value={member.userpwd}
onChange={onMemberChange}
/>
<hr></hr>
๋๋ค์:
<input
type="text"
name="nickname"
value={member.nickname}
onChange={onMemberChange}
/>
<hr></hr>
์ ํ๋ฒํธ:
<input
type="text"
name="telephone"
value={member.telephone}
onChange={onMemberChange}
/>
<hr></hr>
์ด๋ฆ:
<input
type="text"
name="username"
value={member.username}
onChange={onMemberChange}
/>
<hr></hr>
<button onClick={onSave}>์ ์ฅ</button>
</div>
);
};
export default MemberRegist;
<file_sep>/Day7/webzineadminapp/routes/article.js
//node express ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๋ค.
//๋
ธ๋์์ ํน์ ํฉํค์ง ๋๋ ํ๋ ์์ํฌ์ ๊ธฐ๋ฅ์ ๋ถ๋ฌ์ ์ฌ์ฉํ๊ณ ์ํ ๋๋
//require๋ ๋ช
๋ น์ด ์ฌ์ฉํฉ๋๋ค.
var express = require('express');
//express๊ฐ์ฒด์ Router๋ฉ์๋๋ฅผ ํธ์ถํด ๋ผ์ฐํ
๊ฐ์ฒด๋ฅผ ์์ฑํ๋ค.
//๋ผ์ฐํ
๊ฐ์ฒด๋ ์ฌ์ฉ์ ์์ฒญ URL์ ๋ํ ์ฒ๋ฆฌ๋ฅผ ๋ด๋นํ๋ ๊ฐ์ข
๊ธฐ๋ฅ์ ์ ๊ณตํ๋ค.
var router = express.Router();
var multer = require('multer');
//์ฒจ๋ถํ ํ์ผ๋ช
์ผ๋ก ์
๋ก๋ํ๊ธฐ
var storage = multer.diskStorage({
destination(req, file, cb) {
cb(null, 'public/upload/');
},
filename(req, file, cb) {
cb(null, `${Date.now()}__${file.originalname}`);
},
});
var upload = multer({ storage: storage });
//db๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๋ค.
var db = require('../models/index');
//DB ํ๋ก๊ทธ๋๋ฐ์ ์ํ ๋ชจ๋ธ ๊ฐ์ฒด(DB๊ฐ์ฒด์ ์์ฑ๋ช
)๋ฅผ ์ฐธ์กฐํ๋ค.
//var Board = require('../models/index').Board;
var Board = db.Board;
var Article = db.Article;
var ArticleFile = db.ArticleFile;
//๋ผ์ฐํ
๊ฐ์ฒด๋ฅผ ์ด์ฉํด get ๋ฐฉ์ ํธ์ถ ๋ผ์ฐํ
๋ฉ์๋ ์ ์
//get๋ฉ์๋('์ฌ์ฉ์๊ฐ ํธ์ถํ url์ฃผ์',urlํธ์ถ์ ์คํ๋ ๊ธฐ๋ฅ(ํจ์)์ ์)
//urlํธ์ถ์ ์คํ๋ ๊ธฐ๋ฅ(ํจ์)์๋ ์ฌ์ฉ์๋ธ๋ผ์ฐ์ ๋ก๋ถํฐ ์ ๋ฌ๋๋ ๊ฐ์ข
์ ๋ณด(req๊ฐ์ฒด=httprequest๊ฐ์ฒด) ์
//ํจ์๊ฐ ์คํํ์ ๋ธ๋ผ์ฐ์ ์ ์ ๋ฌ๋ ์๋ต๊ฐ์ฒด(res= httpresponse ๊ฐ์ฒด)๊ฐ ๋งค๊ฐ๋ณ์=ํ๋ผ๋ฉํฐ๋ก ์ ๋ฌ๋๋ค.
//๋ธ๋ผ์ฐ์ ์์ ๋ฐ์ดํฐ๋ฅผ ๋ณด๋ผ๋ get๋ฐฉ์์ผ๋ก ์ ๋ฌํ๋ฉด ์๋ฒ ๋ผ์ฐํ
๋ฉ์๋์์๋ get๋ฉ์๋๋ก ๋ฐ์์ผํ๋ค.
//post๋ฐฉ์์ผ๋ก ๋ณด๋ด๋ฉด post๋ก put๋ฐฉ์์ผ๋ก ๋ณด๋ด๋ฉด put์ผ๋ก delete์ผ๋ก๋ณด๋ด๋ฉด delete๋ก ๋ผ์ฐํ
๋ฉ์๋๋ฅผ ์ ์ํฉ๋๋ค.
//router.get๋ฉ์๋๋ ์น๋ธ๋ผ์ฐ์ ๊ฐ ์ต์ด๋ก ์นํ์ด์ง๋ฅผ ํธ์ถํ ๋ ์ฌ์ฉํ๋๋ฐฉ์
// router.get('/list',function(req,res,next){
// //response๊ฐ์ฒด์ render()๋ฉ์๋๋ ๋ทฐํ์ผ(views/~.ejs)์ ํธ์ถํ๊ณ
// //VIEWํ์ผ์ ์ต์ข
HTML๊ฒฐ๊ณผ๋ฌผ์ ์น๋ธ๋ผ์ฐ์ ๋ก ์ ๋ฌํ๋ค.
// //res.render("ํด๋น๋ทฐํ์ผ","๋ทฐํ์ผ์ ์ ๋ฌํ ๋ฐ์ดํฐ");
// res.render("article/list");
// });
//๋ผ์ฐํฐ ํ์ผ์ ๋ง๋ค๋ฉด ๋ฐ๋์ app.js ํ์ผ๋ด์ ๋ผ์ฐํ
ํ์ผ์ ๋ฑ๋กํด์ค๋ค.
//๋ฑ๋ก ํ ๊ธฐ๋ณธ ๋ผ์ฐํ
์ฃผ์๋ฅผ ์ ์ํ๋ค.
//๊ฒ์๊ธ ๋ชฉ๋ก ํ๋ฉด ๋ฐํ
//localhost:3000/article/list
router.get('/list',function(req,res,next){
const articleList = Article.findAll().then((result)=>{
console.log("๊ฒ์๊ธ๋ชฉ๋ก:",result);
return res.render("article/list",{ data:result });
}).catch((err)=>{
//์๋ฌ๋ฅผ app.js ๋ด ์ ์ญ์์ธ์ฒ๋ฆฌ๊ธฐ๋ก ์ ์กํ๋ค.
next(err);
});
});
//๊ฒ์๊ธ ๋ฑ๋กํ๋ฉด ์ต์ดํธ์ถ์ ๋ฐํ
//localhost:3000/article/regist
router.get('/regist', function(req, res, next) {
res.render('article/regist');
});
//๋ธ๋ผ์ฐ์ ์์ post ๋ฐฉ์์ผ๋ก ๋ฐ์ดํฐ๋ฅผ ์ ์กํ๋ ๊ฒฝ์ฐ ํด๋น ๋ผ์ฐํ
๋ฉ์๋๊ฐ ๋ฐ์ดํฐ ์์
//post('URL์ฃผ์',์ฒ๋ฆฌํจ์(req,res))
//์ฌ์ฉ์๊ฐ ์
๋ ฅํ ๊ฒ์๊ธ ๋ฐ์ดํฐ๋ฅผ DB์ ์ ์ฅํ๊ณ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค.
router.post('/regist',upload.single('file'),function(req,res,next){
//์
๋ก๋๋ ํ์ผ์ ์ ์ฒด์ ๋ณด ์ ๊ณต
const uploadedFile = req.file;
//db์ ์ ์ฅํ ์
๋ก๋ ํ์ผ ๊ฒฝ๋ก์ ๋ณด
let uploadFilePath = "/upload/"+uploadedFile.filename;
console.log("์๋ฒ์ ์
๋ก๋๋ ํ์ผ์ ์ ๋ณด",uploadedFile);
//๋ชจ๋ธ ๊ฐ์ฒด
var article = {
title:req.body.title,
boardid:1,
contents:req.body.contents,
viewcount:0,
ipaddress:req.ip,
displayyn:req.body.display == "1" ? true : false,
createduid:1,
updateduid:1
};
//1์ฐจ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
Article.create(article).then((savedArticle)=>{
console.log("๋ฑ๋ก๊ฒ์๊ธ:",savedArticle);
//2์ฐจ ๋ฐ์ดํฐ ์ฒ๋ฆฌ
let articleFile = {
articleid:savedArticle.id,
filepath:uploadFilePath,
filename:uploadedFile.filename
}
ArticleFile.create(articleFile).then((savedFile)=>{
//์ฒจ๋ถํ์ผ ๋ฐ์ดํฐ ๋ฑ๋ก์ด ์๋ฃ๋๋ ์์ ์์ ์ต์ข
ํ์ด์ง ์ด๋
console.log("ํ์ผ ์ ์ฅ ๋ฐ์ดํฐ: ",savedFile);
return res.redirect("/article/list");
}).catch((err)=>{
next(err);
});
}).catch((err)=>{
next(err);
});
});
//๋น๋๊ธฐ๋ฐฉ์์ผ๋ก ๋ฐ์ดํฐ ์ฒ๋ฆฌํ๊ธฐ ์์
router.post('/regist1',upload.single('file'),async(req,res,next)=>{
//์
๋ก๋๋ ํ์ผ์ ์ ์ฒด์ ๋ณด ์ ๊ณต
const uploadedFile = req.file;
//db์ ์ ์ฅํ ์
๋ก๋ ํ์ผ ๊ฒฝ๋ก์ ๋ณด
let uploadFilePath = "/upload/"+uploadedFile.filename;
console.log("์๋ฒ์ ์
๋ก๋๋ ํ์ผ์ ์ ๋ณด",uploadedFile);
//๋ชจ๋ธ ๊ฐ์ฒด
var article = {
title:req.body.title,
boardid:1,
contents:req.body.contents,
viewcount:0,
ipaddress:req.ip,
displayyn:req.body.display == "1" ? true : false,
createduid:1,
updateduid:1
};
const savedArticle = await Article.create(article);
let articleFile = {
articleid:savedArticle.id,
filepath:uploadFilePath,
filename:uploadedFile.filename
}
const savedFile = await ArticleFile.create(articleFile);
return res.redirect("/article/list");
});
//๊ฒ์๊ธ ์์ ํ์ด์ง ํธ์ถ
//localhost:3000/article/modify?id=1
//async/await ๋น๋๊ธฐ ๋ฐฉ์์ผ๋ก DB ์์
ํ๊ธฐ
//๋น๋๊ธฐ ๋ฐฉ์์ผ๋ก ๋ผ์ฐํ
๋ฉ์๋๋ฅผ ํธ์ถํ๋ค
router.get('/modify', async(req, res, next)=> {
//๋น๋๊ธฐ ๋ฐฉ์์ผ๋ก ๋จ์ผ๊ฒ์๊ธ ์กฐํํ๊ณ ๋ฐํ๋ฐ๊ธฐ
let article = await Article.findOne({where:{id:req.query.id}});
article.viewcount +=1;
//๋น๋๊ธฐ๋ฐฉ์์ผ๋ก ๋จ์ผ ๊ฒ์๊ธ ์์ ํ๊ธฐ
const updatedArticleId = await Article.update({viewcount:article.viewcount},{where:{id:article.id}});
return res.render("article/modify",{article:article});
});
//๊ฒ์๊ธ ์ ๋ณด ์์ ์ ์ฅ์ฒ๋ฆฌ
router.post('/modify', function(req, res, next) {
//ํ๋ ํ๊ทธ์์ ๊ฒ์๊ธ ๊ณ ์ ๋ฒํธ๋ฅผ ์กฐํํจ
var articleIdx = req.body.articleIdx;
Article.update({
title:req.body.title,
contents:req.body.contents,
displayyn:req.body.display
},{
where:{id:articleIdx}
}).then((changedId)=>{
console.log("์์ ๋ ๊ฒ์๊ธ ๊ณ ์ ๋ฒํธ:",changedId);
res.redirect("/article/list");
}).catch((err)=>{
next(err);
});
});
//๋ชจ๋ ๊ฒ์ํ ๋ชฉ๋ก์ ๋ณด ์กฐํ
//localhost:3000/article/ormsample
router.get('/ormsample', function(req, res, next) {
//๊ฒ์ํ ์ ๋ณด ๋ฑ๋กํ๊ธฐ
var board ={
boardname:"๊ณต์ง๊ฒ์ํ",
desc:"์ค๋ช
์
๋๋ค.",
useyn:true,
createduid:1
}
//๊ฒ์ํ ์ ๋ณด ๋ฑ๋กํ๊ธฐ : ๋๊ธฐ ๋ฐฉ์์ผ๋ก ๋ฐ์ดํฐ ๋ฑ๋กํ๊ธฐ
// Board.create(board).then((result)=>{
// console.log("๋ฐ์ดํฐ ๋ฑ๋ก๊ฒฐ๊ณผ: ",result);
// //์ ๊ท ๋ฐ์ดํฐ ๋ฑ๋กํ ๊ฒ์๊ธ ๋ชฉ๋ก์ผ๋ก ๋ฐ๋ก์ด๋ํ๊ธฐ
// //res.redirect("์ด๋์ํค๊ณ ์ ํ๋ URL์ฃผ์")
// return res.redirect("/article/list");
// }).catch((error)=>{
// console.error("๋ฐ์ดํฐ ๋ฑ๋ก์ค ์๋ฌ๊ฐ ๋ฐ์ํ์ต๋๋ค.");
// next(error);
// });
//๊ฒ์ํ ์ ๋ณด ๋ชจ๋ ์กฐํํ๊ธฐ:๋๊ธฐ๋ฐฉ์
// Board.findAll().then((list)=>{
// console.log("๋ชจ๋ ๊ฒ์ํ๋ชฉ๋ก ์กฐํ๊ฒฐ๊ณผ: ",list);
// return res.json(list);
// });
//๋จ์ผ ๊ฒ์ํ ์ ๋ณด ์กฐํํ๊ธฐ: ๋๊ธฐ๋ฐฉ์
// const boardIdx = 1;
// Board.findOne({where:{id:boardIdx}}).then((board)=>{
// console.log("๋จ์ผ๊ฒ์๊ธ์ ๋ณด:",board);
// return res.json(board);
// });
//๊ฒ์ํ ์ ๋ณด ์์ ํ๊ธฐ
// const boardIdx =3;
// let boardName = "๋ธ๋ก๊ทธ๊ฒ์ํ";
// //update๋ฉ์๋({๋ณ๊ฒฝํ๊ณ ์ํ๋ ์์ฑ๋ช
๊ณผ ๊ฐ์ ์},{์กฐ๊ฑด์ });
// Board.update({
// boardname:boardName,
// desc:"๋ธ๋ก๊ทธ ๊ฒ์ํ ์ค๋ช
์
๋๋ค."
// },{
// where:{id:boardIdx}
// }).then((result)=>{
// //์์ ์ด ์๋ฃ๋๋ฉด ์์ ๊ฒฐ๊ณผ๊ฐ์ด ๋์ด์จ๋ค.
// //์์ ๊ฒฐ๊ณผ๋ฌผ์ ์์ ๋ ๋ก์ฐ์ PK๊ฐ์ ๋ฐํํ๋ค. ๊ฒ์ํ ๊ณ ์ ๋ฒํธ
// console.log("์์ ๊ฒฐ๊ณผ๊ฐ:",result);
// return res.json(result);
// }).catch((error)=>{
// console.error("์์ ์ ์๋ฒ์๋ฌ ๋ฐ์");
// //์๋ฌ๊ฒฐ๊ณผ๋ฅผ app.js๋ก ์ ๋ฌํ๋ค.
// next(error);
// });
//๊ฒ์ํ ์ ๋ณด ์ญ์ ํ๊ธฐ
const boardIdx = 2;
Board.destroy({where:{id:boardIdx}}).then((result)=>{
//์ญ์ ๋ ๊ฒฐ๊ณผ๊ฐ์ ์ ์ฉ๊ฑด์: ์ฆ,์ญ์ ๋ ๊ฑด์๊ฐ ๋ฐํ๋๋ค.
console.log("์ญ์ ๊ฒฐ๊ณผ:",result);
return res.redirect("/article/list");
}).catch((err)=>{
next(err);
});
//๋ฐํ๊ฐ ์ค์
//res.json(board);
});
//๊ฒ์๊ธ ์ญ์ ํ๊ธฐ:๋๊ธฐ๋ฐฉ์
//localhost:3000/article/remove/1
router.get('/remove/:id',function(req,res){
var articleId = req.params.id;
Article.destroy({where:{id:articleId}}).then((result)=>{
return res.redirect("/article/list");
}).catch((err)=>{
next(err);
});
});
//๊ฒ์๊ธ ์ญ์ ํ๊ธฐ:๋น๋๊ธฐ๋ฐฉ์
//localhost:3000/article/remove?id=1
router.get('/remove',async(req,res)=>{
var articleId = req.query.id;
var deletedCnt = await Article.destroy({where:{id:articleId}});
res.redirect("/article/list");
});
//๊ฒ์๊ธ ์์ ํ๋ฉด ์ต์ดํธ์ถ์ ๋ฐํ
//ํ๋ผ๋ฉํฐ๋ฐฉ์์ผ๋ก ๋ผ์ฐํ
ํ๋ ๋ฉ์๋๋ ๋ผ์ฐํ
ํ์ผ์ ๋งจ ํ๋จ์ ์ ์ํ ๊ฒ..
//localhost:3000/article/1
//๋ผ์ฐํ
ํ๋ผ๋ฉํฐ ๋ฐฉ์์ผ๋ก ํธ์ถํ๋ ๋ผ์ฐํ
๋ฉ์๋๋
//ํด๋น ๋ผ์ฐํ
ํ์ผ์ ์ตํ๋จ์ ๋ฐฐ์น์ํจ๋ค.
router.get('/:id', function(req, res, next) {
//๋๊ธฐ๋ฐฉ์์ผ๋ก DB์ฒ๋ฆฌ๋ฅผ ํ๋ฉด(ํ๋ฒ ๋ผ์ฐํ
์ฝ๋ก ์ฌ๋ฌ๊ฐ์ DB์์
์ ์งํํ ๊ฒฝ์ฐ)
//๋จ๊ณ๋ณ DB์ฒ๋ฆฌ ์์
์ด ์๋ฃ๋์ด์ผ ๋ค์๋จ๊ณ์ ๋ํ DB์ฒ๋ฆฌ๊ฐ ๊ฐ๋ฅํ DB์ฒ๋ฆฌ์ ์ฝ๋ฐฑ์ง์ฅํจ์์ ๋ง์ ๋ณผ์์๋ฐ.
//๋๊ธฐ๋ฐฉ์ DB์ฒ๋ฆฌ๋ ์ฝ๋๋ ๊ธธ์ด์ง๊ณ ์ฒ๋ฆฌ์๋ฃ์์ ์์ ๋๋ค์ ํจ์๋ฅผ ํธ์ถํ๋ ๋ฐฉ์์ด๋ผ ๋ค์ค์์
์ ๋ถํธํ๋ค.
//๊ทธ๋์ async/await๊ณผ ๊ฐ์ ์ต์ ์ node(javascript) ๋น๋๊ธฐ ํ๋ก๊ทธ๋๋ฐ ๊ธฐ๋ฒ์ ์ฌ์ฉํด ์ฌํํ๊ฒ ์ฒ๋ฆฌํ๋ค.
//Step1: ๋จ์ผ๊ฒ์๊ธ ์ ๋ณด๋ฅผ ์กฐํํ๋ค.
Article.findOne({
where:{ id:req.params.id}
}).then((result)=>{
//STEP2: ๋จ์ผ๊ฒ์๊ธ ์ ๋ณด๊ฐ ์กฐํ๊ฐ ์๋ฃ๊ฐ ๋๋ฉด
//ํ์ฌ ์กฐํ๋ ๋จ์ผ๊ฒ์๊ธ ํ์ฌ ๋ทฐ์นด์ดํธ๊ฐ์ ์ถ์ถํ๋ค.
let currentViewCount = result.viewcount + 1;
//STEP3:ํด๋น ๊ฒ์๊ธ์ ๋ณด์ ๋ทฐ์นด์ดํธ๊ฐ์ 1 ๋ํด์ DB์ ๊ฒ์๊ธ ์ ๋ณด๋ฅผ ์์ ํ๋ค.
//๊ฒ์๊ธ ๋ทฐ์นด์ดํธ +1 ์ ์ฉ ์
๋ฐ์ดํธ
Article.update({
viewcount:currentViewCount
},{
where:{id:req.params.id}
}).then((changedId)=>{
//STEP4:์กฐํ๋ ๋จ์ผ๊ฒ์๊ธ์ ๋ทฐ์นด์ดํธ๊ฐ์ ์์ ํ์ฌ ๋ทฐ์ ๋ฐ์ดํฐ๋ฅผ ์ ๋ฌํ๋ค.
result.viewcount = currentViewCount;
return res.render('article/modify',{article:result});
}).catch((err)=>{
next(err);
});
}).catch((err)=>{
next(err);
});
});
//์๋จ์ ์ ์ํ router๊ฐ์ฒด๋ฅผ ๋ชจ๋์ธ๋ถ๋ก ๋
ธ์ถ์ํจ๋ค.
//๋ชจ๋๋ด์ ์ ์๋ ๊ธฐ๋ฅ๊ณผ ์์ฑ์ ์ธ๋ถ์ ๋
ธ์ถํ๋ ค๋ฉด module.exports๋ฅผ ์ฌ์ฉํ๋ค.
module.exports = router;<file_sep>/Day7/webzineadminapp/models/board.js
//๋ชจ๋ธ ํด๋์ค๋ฅผ ํ์ดํ ํจ์๋ด์ ์ ์ํ๊ณ ๊ด๋ จ ๊ธฐ๋ฅ์ ์ธ๋ถ๋ก ๋
ธ์ถํ๋ค.
//ํ์ดํํจ์ ์
๋ ฅ๋งค๊ฐ๋ณ์๋ก๋ sequelize orm๊ฐ์ฒด์ sequelize Node DataType์ ๋ณด๋ฅผ ์ ๋ฌ๋ฐ๋๋ค.
//๋ฐ์ดํฐ ๋ชจ๋ธ์ ํด๋น ์ ๋ณด์ ๊ตฌ์กฐ๋ฅผ ๋
ธ๋๋ฐฑ์๋ ๊ฐ๋ฐ์ธ์ด๋ก ์ ์ํ๋ค.
module.exports = (sequelize,DataTypes)=>{
//ํ์ดํ ํจ์์ ๋ชจ๋ธ๊ตฌ์กฐ ์ ์ ๊ฒฐ๊ณผ๋ฅผ ๋ฐํํ๋ค.
//sequelize๊ฐ์ฒด์ define๋ฉ์๋('๋ฌผ๋ฆฌ์ ํ
์ด๋ธ ์ด๋ฆ',{ํด๋น ํ
์ด๋ธ๊ณผ ๋งตํ๋๋ ์ปฌ๋ผ๋ช
๊ณผ ๋ฐ์ดํฐ ํ์
์ ์},{๊ฐ์ข
์ต์
์ค์ })๋ฅผ
//์ด์ฉํด ๋ชจ๋ธ์ ๊ตฌ์กฐ๋ฅผ ์ ์ํ๋ค.
//return sequelize.define('board',{},{});
//Sequelize ORM์ ๊ธฐ์กด์ ํ
์ด๋ธ์ด ์์ผ๋ฉด ํ
์ด๋ธ์ ์๋์ผ๋ก ์์ฑํ๋๋ฐ
//id(Identity) ์ปฌ๋ผ์ ์๋์ผ๋ก ์์ฑํ๊ณ ์๋์ฑ๋ฒ(1,2,3(AI=Auto Increment)) ์์ฑ์ ์ปฌ๋ผ์ PK๋ก ๋ง๋ค์ด์ค๋ค.
//๋ชจ๋ธ ํด๋์ค์์ PK์ค์ ์ด ์์ผ๋ฉด ์๋ Id ์ปฌ๋ผ์ ์์ฑํด์ PK์ปฌ๋ผ์ผ๋ก ํ์ฉํ๋ค.
return sequelize.define('board',{
boardname:{
type:DataTypes.STRING(100),
allowNull:false
},
desc:{
type:DataTypes.STRING(500),
allowNull:true
},
useyn:{
type:DataTypes.BOOLEAN,
allowNull:false
},
createduid:{
type:DataTypes.INTEGER,
allowNull:false
}
},{
timestamps:true,
paranoid:true
});
//timestamps ์ต์
์ด true์ด๋ฉด ๋ฌผ๋ฆฌ์ ํ
์ด๋ธ์ ์๋์ผ๋ก createdAt,updatedAt ์ปฌ๋ผ์ ์๋์ถ๊ฐํด์ฃผ๊ณ
//๋ฐ์ดํฐ๊ฐ ์ถ๊ฐ๋ ์ผ์์ ๋ณด์ ์์ ๋ ์ผ์์ ๋ณด๋ฅผ ์๋์ผ๋ก ์
๋ ฅํด์ค๋ค.
//paranoid ์ต์
์ด true์ด๋ฉด deletedAt์ด๋ ์ปฌ๋ผ์ด ์๋์ถ๊ฐ๋๊ณ ๋ฐ์ดํฐ ์ญ์ ์
//๋ฌผ๋ฆฌ์ ํ
์ด๋ธ์์ ์ค์ ์ญ์ ํ์ง ์๊ณ deletedAt์ปฌ๋ผ์ ์ญ์ ์ผ์๊ฐ ๋งํฌ๋๊ณ NodeApp์์๋ ์ญ์ ๋๊ฒ์ผ๋ก ์ธ์ํ์ง๋ง
//์ค์ ๋ฌผ๋ฆฌ์ ํ
๋ธ์๋ ๋ฐ์ดํฐ๊ฐ ์ค์ ์กด์ฌํ๊ณ deletedAt์ปฌ๋ผ์ ์ญ์ ์ผ์๊ฐ ๋งํน๋์ด ์๋ค.
};
<file_sep>/Day7/reactaxiosapp/src/redux/store.js
//๋ฆฌ๋์ค ํจํค์ง ๋ด์์ ์ ๊ณตํ๋ createStore, compose ๊ฐ์ฒด ์ฐธ์กฐ
import { createStore } from "redux";
//Store์ ์ ์ฅํ ๋ฆฌ์กํธ App๋ด ๋ชจ๋ ๋ฆฌ๋์ ํ์ผ ์ฐธ์กฐ
import reducers from "./reducers";
//์คํ ์ด ์์ฑ ๋ฐ ํ๊ฒฝ ๊ตฌ์ฑํ๊ธฐ
export function configureStore(intialState) {
//์คํ ์ด์ ๊ด๋ จ ์ ๋ณด๋ฅผ ์ ๋ฌํด ์์ฑํ๋ค.
//createStore ์์ฑ ๊ธฐ๋ณธ ๋ฐฉ์1
//const store = createStore(reducers, intialState);
//REDUX CHROME DEVTOOLS์ ์ฐ๋๋๋ ์ถ๊ฐ ์ค์ ํ๋ ๋ฐฉ์2
const store = createStore(
reducers,
intialState,
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()
);
//์์ฑ๋ ์คํ ์ด ๊ฐ์ฒด ๋ฐํํ๋ค.
return store;
}
<file_sep>/Day4/reactroutingapp/src/Profile.js
import React from "react";
import UseHistoryHook from "./UseHistoryHook";
//์ ์ญ ๋ฐ์ดํฐ ๋ชฉ๋ก ์ ์
const data = {
user1: {
name: "์ฌ์ฉ์1",
description: "ํ์์
๋๋ค.",
},
user2: {
name: "์ฌ์ฉ์2",
description: "๊ต์์
๋๋ค.",
},
};
const Profile = ({ match }) => {
//URLํ๋ผ๋ฉํฐ์์ username๊ฐ์ ์ถ์ถํด์ username์ ํ ๋นํ๋ค.
//ex) user1
const { username } = match.params;
//ํ๋ผ๋ฉํฐ๋ก ์ ๋ฌ๋ username๊ฐ์ ํค๋ก data์์ ์ง์ ์ฌ์ฉ์ ์ ๋ณด๋ฅผ ์ถ์ถํ๋ค.
const profile = data[username];
//profile๊ฐ์ด ์กด์ฌํ์ง ์์ผ๋ฉด
if (!profile) {
return <div>์ฌ์ฉ์ ์ ๋ณด๊ฐ ์กด์ฌํ์ง ์์ต๋๋ค.</div>;
}
return (
<div>
<h3>
{/* ์ ๋ฌ๋ ํ๋ผ๋ฉํฐ ์ ๋ณด์ ์ ํ๋ ์ฌ์ฉ์ ์ด๋ฆ์ ์ถ๋ ฅํ๋ค. */}
{username}({profile.name})
</h3>
<p>{profile.description}</p>
<UseHistoryHook></UseHistoryHook>
</div>
);
};
export default Profile;
<file_sep>/Day5/reactaxiosapp/src/pages/members/MemberModify.js
import React from "react";
const MemberModify = () => {
return <div></div>;
};
export default MemberModify;
<file_sep>/Day7/reactaxiosapp/src/App.js
import logo from "./logo.svg";
import "./App.css";
//๋ผ์ฐํ
์ ์ํ Router ๊ฐ์ฒด๋ฅผ ์ฐธ์กฐํ๋ค.
import { Route, Link, BrowserRouter } from "react-router-dom";
//axios ์ฐธ์กฐ
import axios from "axios";
//๊ฐ์ข
์ฌ์ฌ์ฉ ์ปดํฌ๋ํธ์ ๋ํ ์ฐธ์กฐ
import TopMenu from "./components/TopMenu";
import Footer from "./components/Footer";
//๊ฐ์ข
ํ์ด์ง ์ปดํฌ๋ํธ์ ๋ํ ์ฐธ์กฐ
import Main from "./pages/Main";
import About from "./pages/About";
import ArticleList from "./pages/articles/ArticleList";
import ArticleModify from "./pages/articles/ArticleModify";
import ArticleRegist from "./pages/articles/ArticleRegist";
//ํ์ ์ ๋ณด ๊ด๋ จ UI ํ์ด์ง ์ปดํฌ๋ํธ ์ฐธ์กฐ
import Login from "./pages/members/Login";
import MemberList from "./pages/members/MemberList";
import MemberRegist from "./pages/members/MemberRegist";
import MemberModify from "./pages/members/MemberModify";
function App() {
//axios์ ์ ์ญ ๊ธฐ๋ณธ ์ฃผ์ ์ธํ
ํ๊ธฐ
axios.defaults.baseURL = "http://localhost:3005";
return (
<div>
<BrowserRouter>
<TopMenu></TopMenu>
{/* ๋ฉ์ธ ํ์ด์ง ๋ฐ ๊ฒ์๊ธ ๊ด๋ฆฌ ๋ผ์ฐํ
์ ์ */}
<Route path="/" component={Main} exact={true}></Route>
<Route path="/article/list" component={ArticleList}></Route>
<Route path="/article/regist" component={ArticleRegist}></Route>
<Route path="/article/modify/:idx" component={ArticleModify}></Route>
{/* querystring์ผ๋ก ๋์ด์ค๋ ๊ฑฐ ์ฒ๋ฆฌํ๋ ค๊ณ ํ๋๋ฐ ๋ค์์ ํ์..
<Route path="/article/modify/" component={ArticleModify}></Route> */}
{/* ํ์ ์ ๋ณด ๊ด๋ฆฌ ๋ผ์ฐํ
์ ์ */}
<Route path="/login" component={Login}></Route>
<Route path="/member/list" component={MemberList}></Route>
<Route path="/member/regist" component={MemberRegist}></Route>
<Route path="/member/modify/:idx" component={MemberModify}></Route>
<Route path="/about" component={About}></Route>
<Footer></Footer>
</BrowserRouter>
</div>
);
}
export default App;
<file_sep>/Day7/webzineadminapp/app.js
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
//express-ejs-layouts ๋
ธ๋ ํฉํค์ง๋ฅผ ์ฐธ์กฐํ๋ค.
var expressLayouts = require('express-ejs-layouts');
//cors ๋
ธ๋ ํฉํค์ง๋ฅผ ์ฐธ์กฐํ๋ค.
const cors = require('cors');
//.env ์ค์ ๊ธฐ๋ฅ ์ฐธ์กฐ์ ์ฉ
require('dotenv').config();
//MVC(Model์์ญ ๋ชจ๋ ์ฐธ์กฐ) ์ํ๋ผ์ด์ฆ ORM ๊ฐ์ฒด ์ฐธ์กฐํ๊ธฐ
var sequelize = require('./models/index.js').sequelize;
//๋ผ์ฐํ
ํ์ผ์ ๋ํ ์ฐธ์กฐ
//MVC(Controller=Routes์์ญ ๋ชจ๋ ์ฐธ์กฐ )
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
//์ฌ์ฉ์ ์ ๋ณด ๊ด๋ฆฌ ๋ผ์ฐํ
ํ์ผ ์ฐธ์กฐ(MVC,API)
var memberRouter = require('./routes/member');
//๊ฐ๋ฐ์ ์ ์ ๊ฒ์๊ธ ๋ผ์ฐํ
ํ์ผ์ ์ฐธ์กฐํ๋ค.
var articleRouter = require('./routes/article.js');
//๊ฒ์๊ธ์ ๋ณด ์ ๊ณต API ๋ผ์ฐํฐ๋ฅผ ์ฐธ์กฐํ๋ค.
var articleAPIRouter = require('./routes/articleAPI');
var memberAPIRouter = require('./routes/memberAPI');
//Node Express ์น๊ฐ๋ฐ ํ๋ ์์ํฌ๋ฅผ ์ด์ฉํด Node App๊ฐ์ฒด๋ฅผ ์์ฑํ๋ค.
//node app๊ฐ์ฒด๋ฅผ ์ด๊ธฐํํ๋ค.
var app = express();
//ํน์ ๋๋ฉ์ธ ์ฃผ์๋ง CORS ํ์ฉํ๊ธฐ
// const options ={
// origin:'http://localhost:5000',
// credentials:true,
// optionsSuccessStatus:200
// };
// app.use(cors(options));
//๋
ธ๋ ์ดํ๋ฆฌ์ผ์ด์
์ cors๊ธฐ๋ฅ ์ ์ฉ
//๋ชจ๋ ๋ฆฌ์์ค ์ ๊ทผ CORS ํ์ฉํ๊ธฐ
//CORS ๊ธฐ๋ฅ์ node app์ ์ถ๊ฐํ๋ค.
app.use(cors());
//์ํ๋ผ์ด์ฆ ORM๊ฐ์ฒด๋ฅผ ์ด์ฉํด ์ง์ ํ MySQL ์ฐ๊ฒฐ ๋๊ธฐํํ๊ธฐ
sequelize.sync();
// view engine setup
//viewํด๋์ ๊ธฐ๋ณธ๊ฒฝ๋ก๋ฅผ ์ธํ
ํ๋ค.
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
//๋
ธ๋ ์ฑ์์ ์ฌ์ฉํ layout ๊ด๋ จ ์ค์ ์ ์ถ๊ฐํ๋ค.
//๊ธฐ๋ณธ ๋ ์ด์์ ํ์ด์ง๋ฅผ viewsํด๋๋ด layout.ejsํ์ผ๋ก ์ง์ ํ๋ค.
app.set('layout','layout');
//์ฝํ
์ธ ํ์ด์ง๋ด ์คํฌ๋ฆฝํธ๋ฅผ ๋ ์ด์์ํ์ด์ง์์ ์ฌ์ฉํ ๊ฒํ๊ณ ์ธ๋ถ ์คํฌ๋ฆฝํธ ํ์ผ๋ ์ฌ์ฉํ ์ ์๊ฒ ์ค์
app.set('layout extractScripts',true);
//๋
ธ๋์ฑ์์ expressLayouts ์ฌ์ฉํ๊ฒ ์ต์ข
์ค์
app.use(expressLayouts);
//morgan ๋๋ฒ๊น
/๋ก๊น
์ ์ํ ๊ธฐ๋ฅ์ ์ฑ์ ์ถ๊ฐ
app.use(logger('dev'));
//json ์ ๊ณต ๊ธฐ๋ฅ ์ถ๊ฐ
app.use(express.json());
//url์ธ์ฝ๋ฉ ๊ธฐ๋ฅ์ถ๊ฐ
app.use(express.urlencoded({ extended: false }));
//์ฟ ํคํ์๊ธฐ๋ฅ ์ถ๊ฐ
app.use(cookieParser());
//์ ์ ์นํ์ด์ง๋ค ์ ์ฅ ๊ฒฝ๋ก ์ค์
//์ ์ ์นํ์ด์ง๋ค์ ๋๋ฉ์ธ ์ฃผ์๋ฅผ ํตํด ์ ๊ทผ๊ฐ๋ฅํ๊ฒ ํด์ค.
app.use(express.static(path.join(__dirname, 'public')));
//๋ผ์ฐํ
ํ์ผ์ ๊ธฐ๋ณธ ํธ์ถ์ฃผ์ ์ฒด๊ณ ์ ์
app.use('/', indexRouter);
app.use('/users', usersRouter);
//member ๋ผ์ฐํฐ ํ์ผ ๊ธฐ๋ณธ URL์ฃผ์ ์ ์
app.use('/member', memberRouter);
//๊ฒ์๊ธ ๋ผ์ฐํ
ํ์ผ์ ๊ธฐ๋ณธ์ฃผ์๋ฅผ article๋ก ์์ํ๊ฒ ์ค์
//http://localhost:3000/article/~~~~
app.use('/article', articleRouter);
//๊ฒ์๊ธ API ๋ผ์ฐํฐ ํ์ผ ๊ธฐ๋ณธ์ฃผ์ ์ ์
//localhost:3000/api/articles
app.use('/api/articles', articleAPIRouter);
app.use('/api/member', memberAPIRouter);
//404์๋ฌ(์๋ฒ์์ ์กด์ฌํ์ง ์์ ๋ฆฌ์์ค๋ฅผ ํธ์ถํ ๋ ์๋ฒ์์ ์ ๊ณตํ๋ ์๋ฌ)
app.use(function(req, res, next) {
//404์๋ฌ๋ง ๋ณ๋ ์ฒ๋ฆฌํด์ฃผ๋ ๋ฏธ๋ค์จ์ด
next(createError(404));
});
//์ ์ญ ๋
ธ๋ ์ดํ๋ฆฌ์ผ์ด์
์์ธ ์ฒ๋ฆฌ๊ธฐ
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
//๋
ธ๋ ์ฑ์ ๋ชจ๋ ๊ฒฐ๊ณผ๋ฌผ๋ก ์ ๊ณตํ๋ค.
module.exports = app;
<file_sep>/Day5/reactaxiosapp/src/pages/articles/ArticleModify.js
import React, { useState, useEffect, useRef } from "react";
import { useParams, useHistory } from "react-router-dom";
import axios from "axios";
const ArticleModify = () => {
const [article, setArticle] = useState({ title: "", contents: "" });
const [articleIdx, setArticleIdx] = useState(0);
//ํ๋ผ๋ฉํฐ๋ก ์ ๋ฌ๋๋ ์์ผ๋ ์นด๋ ๋ณ์๋ช
์ผ๋ก ์ ๋ฌ๋๋ ๊ฐ์ ๋ฐ์์จ๋ค.
const { idx } = useParams();
const titleRef = useRef();
const contentsRef = useRef();
const history = useHistory();
//์ต์ด ์ปดํฌ๋ํธ ๋ก๋ฉ ์์๋ง ํด๋น ๋จ์ผ ๊ฒ์๊ธ ์ ๋ณด๋ฅผ ์กฐํํ์ฌ ๋ฐ์ธ๋ฉ ์ฒ๋ฆฌํ๋ค.
useEffect(() => {
setArticleIdx(idx);
console.log("ArticleModify์์ ์์ ํ ๊ฒ์๊ธ ๊ณ ์ ๋ฒํธ๋ : ", idx);
axios
.get(`http://localhost:3005/api/articles/${idx}`)
.then((res) => {
console.log(res.data);
if (res.data.code === 200) {
setArticle(res.data.data);
} else {
alert("๋ฐฑ์๋ ์๋ฌ");
}
})
.catch((err) => {
alert("๋ฐฑ์๋ ํธ์ถ ์๋ฌ");
});
}, []);
//์
๋ ฅ์์์ useSate๊ฐ ๋ฐ์ดํฐ ๋ฐ์ธ๋ฉ ์ ์ฉ
const onArticleChange = (e) => {
setArticle({ ...article, [e.target.name]: e.target.value });
};
//๊ฒ์๊ธ ์ ์ฅ ์ด๋ฒคํธ ์ฒ๋ฆฌ๊ธฐ ํจ์
const onSaveArticle = () => {
if (article.title === "") {
alert("์ ๋ชฉ์ ์
๋ ฅํด์ฃผ์ธ์.");
//useRef๋ก ํฌ์ปค์ฑ ์ฒ๋ฆฌํ๊ธฐ
titleRef.current.focus();
return false;
}
if (article.contents === "") {
alert("๋ด์ฉ์ ์
๋ ฅํด์ฃผ์ธ์.");
//useRef๋ก ํฌ์ปค์ฑ ์ฒ๋ฆฌํ๊ธฐ
contentsRef.current.focus();
return false;
}
axios
.put("http://localhost:3005/api/articles", article)
.then((res) => {
console.log("๋ฐ์ดํฐ ์ฒ๋ฆฌ ๊ฒฐ๊ณผ : ", res.data);
alert("์์ ์๋ฃ");
history.push("/article/list");
})
.catch((err) => {
console.error(err);
});
};
//๊ฒ์๊ธ ์ญ์ ์ฒ๋ฆฌ ์ด๋ฒคํธ
const onDeleteArticle = () => {
axios
.delete(`http://localhost:3005/api/articles/${article.id}`)
.then((res) => {
console.log("๋ฐ์ดํฐ ์ฒ๋ฆฌ ๊ฒฐ๊ณผ : ", res.data);
alert("์ญ์ ์๋ฃ");
history.push("/article/list");
})
.catch((err) => {
console.error(err);
});
};
return (
<div>
<h1>์์ ํ์ด์ง</h1>
์ ๋ชฉ :
<input
type="text"
name="title"
value={article.title}
ref={titleRef}
onChange={onArticleChange}
></input>
<hr></hr>
๋ด์ฉ :
<textarea
name="contents"
value={article.contents}
ref={contentsRef}
rows="10"
cols="50"
onChange={onArticleChange}
/>
<hr></hr>
<button onClick={onSaveArticle}>์์ ํ๊ธฐ</button>
<button onClick={onDeleteArticle}>์ญ์ ํ๊ธฐ</button>
</div>
);
};
export default ArticleModify;
<file_sep>/Day7/reactaxiosapp/src/components/TopMenu.js
import React, { useEffect } from "react";
import { Link, useHistory } from "react-router-dom";
//๋ฆฌ๋์ค : ๊ตฌ๋
์ ์ํ useSelector ํ
์ฐธ์กฐ
import { useSelector } from "react-redux";
//๊ฐ ์ข
์ ํธ๋ฆฌํฐ ํจ์๋ฅผ ์ฐธ์กฐํ๋ค.
import {
getJWTToken,
isMemberLogined,
getLoginMember,
} from "../helpers/authUtils";
const TopMenu = () => {
//(state-์ต์์ ์ ์ญ ๋ฐ์ดํฐ ๊ฐ์ฒด=> state.๋ฆฌ๋์ ํจ์. ๋ฆฌ๋์ ํจ์๋ด ๋ฐ์ดํฐ ์์ฑ)
const token = useSelector((state) => state.Login.token);
const history = useHistory();
//์ฌ์ฉ์ ๋ก๊ทธ์์ ์ฒ๋ฆฌ - ๋ก์ปฌ ์คํ ๋ฆฌ์ง๋ฅผ ์ญ์ ํ๋ค.
const logOut = () => {
window.localStorage.removeItem("jwttoken");
//history.push("/"); //๋ก๊ทธ์์ ํ ๋ฉ์ธ์ผ๋ก ์ด๋
window.location = "/"; //์ด๋ ๊ฒ ํ๋ฉด ๋ชจ๋ ๋ฐ์ดํฐ๊ฐ ์์ด์ ธ์ ์ด๋ ๊ฒ ํ๋ฉด ์ ๋์ง๋ง ์ผ๋จ์ ์ด๋ ๊ฒ...
};
return (
<div style={{ width: "100%", height: "50px", backgroundColor: "gray" }}>
<span>
<Link to="/">ํ</Link>
</span>
<span>
<Link to="/about">ํ์ฌ ์๊ฐ</Link>
</span>
<span></span>
<span>
<Link to="/article/list">๊ฒ์๊ธ ๋ชฉ๋ก</Link>
</span>
<span>
<Link to="/member/list">
<span>ํ์ ๋ชฉ๋ก</span>
</Link>
</span>
<span>
{isMemberLogined() == true ? ( //์ฒ์์ ํ ํฐ์ผ๋ก ๋ฐ์์ฌ ๋ ์์ฑํ ์ฝ๋ ==> token != undefined : token ๊ฐ์ด ์กด์ฌํ๋ค๋ฉด
<button onClick={logOut}>๋ก๊ทธ์์</button>
) : (
<Link to="/login">๋ก๊ทธ์ธ</Link>
)}
<hr></hr>
{isMemberLogined() == true ? (
<b>๋ก๊ทธ์ธ ๋ ์ํ์
๋๋ค. </b>
) : (
<b>๋ก๊ทธ์ธ ์ ๋ ์ํ์
๋๋ค. </b>
)}
ํ์ฌ ๋ก๊ทธ์ธ ํ ํฐ ๊ฐ : {token}
{/* ๋์ด์จ ๊ฐ์ด ์์ผ๋ฉด ๋น ๋ฌธ์์ด/ ์์ผ๋ฉด ๋์ด์จ ๊ฐ ์ค username */}
ํ์ฌ ์ ์ ์ฌ์ฉ์ ์ด๋ฆ :
{getLoginMember() == null ? "" : getLoginMember().username}
</span>
</div>
);
};
export default TopMenu;
<file_sep>/Day7/webzineadminapp/models/article.js
module.exports = (sequelize,DataTypes)=>{
return sequelize.define('article',{
title:{
type:DataTypes.STRING(100),
allowNull:false
},
boardid:{
type:DataTypes.INTEGER,
allowNull:false
},
contents:{
type:DataTypes.TEXT,
allowNull:true
},
viewcount:{
type:DataTypes.INTEGER,
allowNull:false
},
ipaddress:{
type:DataTypes.STRING(20),
allowNull:false
},
displayyn:{
type:DataTypes.BOOLEAN,
allowNull:false
},
createduid:{
type:DataTypes.INTEGER,
allowNull:false
},
updateduid:{
type:DataTypes.INTEGER,
allowNull:false
}
},{
timestamps:true,
paranoid:true
});
};
|
fd7f78a04ed875d0570604859ce45a641444d145
|
[
"JavaScript"
] | 36 |
JavaScript
|
ssong0122/mynodetest
|
61a6180b0026a8ead081f9fa62a841451b49f2b6
|
f48705abd08ef726a74d7d024ada3152fc720494
|
refs/heads/master
|
<file_sep>import com.sun.source.tree.Tree;
import java.util.HashMap;
import java.util.TreeSet;
public class Main {
public static String displayArray(int[] array){
String result = "";
for (int i = 0; i < array.length; i++)
result += array[i] + " ";
return result;
}
public static void main(String[] args) {
Graph graph = new Graph(100);
System.out.println(graph);
// methode descente
System.out.println("==========Methode Descente==========");
Descente descente = new Descente(graph);
descente.solve();
// methode tabou
System.out.println("==========Methode Tabou==========");
Tabou tabou = new Tabou(graph);
tabou.solve();
// methode recuit simule
System.out.println("==============Methode Recuit Simule==================");
RecuitSimule recuitSimule = new RecuitSimule(graph);
recuitSimule.solve();
// methode VNS
System.out.println("==============Methode VNS==================");
VNS vns = new VNS(graph);
vns.solve();
}
}
<file_sep># tsp
Travral Selsman Problem solver
## Description:
The travelling salesman problem (also called the travelling salesperson problem or TSP) asks the following question: "Given a list of cities and the distances between each pair of cities, what is the shortest possible route that visits each city and returns to the origin city?" It is an NP-hard problem in combinatorial optimization, important in operations research and theoretical computer science. [more info](https://en.wikipedia.org/wiki/Travelling_salesman_problem)
In the following implemetation in Java we used:
<br/>
* [Gradient Descent](https://en.wikipedia.org/wiki/Gradient_descent)
* [Tabu search](https://en.wikipedia.org/wiki/Tabu_search)
* [Simulated Annealing](https://en.wikipedia.org/wiki/Simulated_annealing)
* [VNS](https://en.wikipedia.org/wiki/Variable_neighborhood_search)
## comparaison between methods
based on random generated graph with multiple insances size, we created the following graph to compare in term of time, solution quality and costs.
<br/>
* In term of time.

* In term of quality.

* In term of cost.

|
cf1dd1395b68eb78a08ac032d4d6b4c66dfe100e
|
[
"Markdown",
"Java"
] | 2 |
Java
|
ablil/tsp
|
895bba2876d6f989ca35ed2454689bed2d0ee09a
|
9f1d0ccfed10fbdf40048ba11277adeff56414ed
|
refs/heads/main
|
<file_sep>const express = require("express");
const http = require("http");
const socketIO = require("socket.io");
// const cors = require("cors");
const connectDB = require("./config/DB");
const Classroom = require("./models/Session");
const router = require("./router");
const userFunctions = require("./users");
const { getUser } = require("./users");
const app = express();
// app.use(cors({ origin: "*" }));
app.use(router);
connectDB();
const port = process.env.PORT || 8000;
const server = http.createServer(app);
const io = socketIO(server);
// const listenIO = require("socket.io").listen(server);
// io.set("origins", "*");
io.on("connection", async (socket) => {
socket.on("join", async ({ name, room, role }) => {
try {
await userFunctions.loginUser({ name, role, socketId: socket.id });
const { error, user } = await userFunctions.addUsers({
id: socket.id,
name,
room,
});
if (error) {
socket.emit("err", { error });
}
socket.emit("message", {
user: "admin",
text: `Hi ${name}, Welcome to the ${room} room.`,
});
socket.broadcast.to(room).emit("message", {
user: "admin",
text: `${name} has joined the room`,
});
socket.join(room);
let cur_session = await userFunctions.getUsersInRoom(room);
io.to(room).emit("totalMembers", { session: cur_session });
} catch (err) {}
});
// socket.on("removeUser", (name, room) => {
// const user = userFunctions.getUser(name);
// io.to(user.room).emit("message", {
// user: "admin",
// text: `${user.name} has been removed by admin`,
// });
// io.to(user.id).emit("deleteUser");
// userFunctions.removeUser(name, room);
// let totalMembers = userFunctions.getUsersInRoom(room);
// io.to(user.room).emit("totalMembers", { totalMembers });
// });
socket.on("startSession", async ({ room }) => {
const classroom = await Classroom.findOne({ name: room });
classroom.isStarted = true;
classroom.startTime = new Date();
await classroom.save();
let cur_session = await userFunctions.getUsersInRoom(room);
io.to(room).emit("totalMembers", { session: cur_session });
});
socket.on("endSession", async ({ room }) => {
const classroom = await Classroom.findOne({ name: room });
classroom.isStarted = false;
let date = new Date();
classroom.endTime = date;
classroom.students.forEach((student) => {
student.exitTime = date;
});
await classroom.save();
let cur_session = await userFunctions.getUsersInRoom(room);
io.to(room).emit("totalMembers", { session: cur_session });
socket.emit("SessionEnded");
});
socket.on("sendMessage", ({ message, name, room }) => {
try {
io.to(room).emit("message", { user: name, text: message });
} catch (err) {}
});
socket.on("disconnect", async ({ name, room }) => {
const user = getUser(name);
try {
io.to(user.room).emit("message", {
user: "admin",
text: `${name} has left the room`,
});
userFunctions.removeUser(name, room);
let cur_session = await userFunctions.getUsersInRoom(room);
io.to(room).emit("totalMembers", { session: cur_session });
} catch (err) {}
});
});
server.listen(port, () => {
console.log(`Listening on PORT: ${port}`);
});
<file_sep>
const mongoose = require('mongoose');
const SessionSchema = new mongoose.Schema(
{
//id has
name:{
type:String,
required : true
},
isStarted : {
type:Boolean,
default:true
},
teacher: {
teacherId: {
type: mongoose.Schema.ObjectId,
ref: 'User',
},
entryTime : { type : Date, default: Date.now }
// exitTime : { type : Date, default: Date.now }
},
students : [{
studentId: {
type: mongoose.Schema.ObjectId,
ref: 'User',
},
entryTime : { type : Date, default: Date.now },
exitTime : { type : Date, default: Date.now }
}],
startTime : { type : Date, default: Date.now },
endTime : { type : Date, default: Date.now }
}
)
module.exports = mongoose.model("Classroom" , SessionSchema)<file_sep>import React, { useState } from "react";
import { Link } from "react-router-dom";
import "../../assets/JoinRoom/JoinRoom.css";
const JoinRoom = () => {
const [name, setName] = useState("");
const [room, setRoom] = useState("");
const [role, setRole] = useState("student");
return (
<>
<div className="container">
<div className="join-room-inner">
<div className="card">
<div className="heading">Join Room</div>
<div className="content m-1">
Join any room by creating or using a room id
</div>
<div>
<input
type="text"
placeholder="Enter Your Name to display"
className="text-field"
value={name}
onChange={(e) => setName(e.target.value)}
/>
</div>
<div>
<input
type="text"
placeholder="Enter or create a Room ID"
className="text-field"
value={room}
onChange={(e) => setRoom(e.target.value)}
/>
</div>
<div>
<select
className="text-field"
value={role}
onChange={(e) => setRole(e.target.value)}
>
<option>student</option>
<option>teacher</option>
</select>
</div>
<Link
onClick={(e) => (!name || !room ? e.preventDefault() : null)}
to={`/room=${room}/name=${name}/role=${role}`}
>
<button>Join Room</button>
</Link>
</div>
</div>
</div>
</>
);
};
export default JoinRoom;
<file_sep>//const users = [];
const mongoose = require("mongoose");
const User = require("./models/User");
const Classroom = require("./models/Session");
const { use } = require("./router");
const userFunctions = {};
userFunctions.addUsers = async ({ id, name, room }) => {
try {
name = name.trim();
room = room.trim().toLowerCase();
// (user) => user.name === name && user.room === room
const IsExistingSession = await Classroom.findOne({ name: room });
if (!IsExistingSession) {
const user = await User.findOne({ name });
if (!user) return { error: "user doesn't exist try a valid Id" };
user.socketId = id;
await user.save();
let cur_date = new Date();
cur_date.setDate(cur_date.getDate() + 10);
if (user.role === "teacher") {
const newSession = new Classroom({
name: room,
isStarted: false,
teacher: { teacherId: user._id },
endTime: cur_date,
});
await newSession.save();
return user;
}
if (user.role === "student") return { error: "invalid meeting Id" };
else {
return { error: "don't have access" };
}
} else {
const user = await User.findOne({ name });
if (!user) return { error: "user doesn't exist try a valid Id" };
user.socketId = id;
await user.save();
if (
user.role === "student" &&
IsExistingSession.endTime.getTime() > new Date().getTime()
) {
if (!IsExistingSession.isStarted) {
return { error: "Meeting has not yet started" };
}
const hasUser = IsExistingSession.students.filter(
(c) => c.studentId.toString() === user._id.toString()
);
if (!hasUser.length) {
IsExistingSession.students.push({
studentId: user._id,
});
await IsExistingSession.save();
}
return user;
}
if (user.role === "student") {
return { error: "meeting ended" };
} else {
if (user.name === name) return user;
return { error: "session is taken by another teacher" };
} //teacher try to enter
}
} catch (err) {}
};
userFunctions.removeUser = async (name, room) => {
try {
const IsExistingSession = await Classroom.findOne({ name: room });
if (IsExistingSession) {
const existingUser = await User.findOne({ name });
let currentDate = new Date();
if (existingUser) {
if (existingUser.role === "teacher") {
IsExistingSession.endTime = currentDate;
IsExistingSession.isStarted = false;
IsExistingSession.students.forEach((c) => {
c.exitTime = currentDate;
});
} else {
const exist_id = IsExistingSession.students.findIndex(
(c) => c.studentId === existingUser._id
);
IsExistingSession.students[exist_id].exitTime = currentDate;
}
await IsExistingSession.save();
}
} else return { error: "session doesn't exists" };
} catch (err) {}
};
userFunctions.getUser = async (name) => {
try {
await User.findOne({ name });
} catch (err) {}
};
userFunctions.getUsersInRoom = async (room) => {
try {
let cur_session = await Classroom.findOne({ name: room })
.populate({
path: "students",
populate: {
path: "studentId",
},
})
.populate({
path: "teacher",
populate: { path: "teacherId" },
});
return cur_session;
} catch (err) {}
};
userFunctions.loginUser = async ({ name, role, socketId }) => {
try {
const userExist = await User.findOne({ name });
if (!userExist) {
const user = new User({
name,
role,
socketId,
});
await user.save();
} else {
userExist.socketId = socketId;
await userExist.save();
}
} catch (err) {}
};
module.exports = userFunctions;
<file_sep>import React, { useEffect, useState } from "react";
import io from "socket.io-client";
import "../../assets/ChatRoom/ChatRoom.css";
import swal from "sweetalert";
let socket;
let ENDPOINT = "https://camp12k-server.herokuapp.com/";
// let ENDPOINT = "http://localhost:8000/";
const ChatRoom = (props) => {
const [room, setRoom] = useState("");
const [message, setMessage] = useState("");
const [session, setSession] = useState({});
const [messages, setMessages] = useState([]);
const [isStarted, setIsStarted] = useState(false);
const [name, setName] = useState("");
useEffect(() => {
const { room, name, role } = props.match.params;
socket = io(ENDPOINT);
setRoom(room);
setName(name);
socket.on("SessionEnded", () => {
if (session.teacher && session.teacher.teacherId.name !== name) {
setTimeout(() => {
swal("Meeting has been ended", "", "warning").then(() => {
socket.off();
window.location.href = "/";
});
}, 2000);
}
});
socket.emit("join", { name, room, role });
socket.on("err", ({ error }) => {
swal(error, "", "error").then(() => (window.location.href = "/"));
});
socket.on("deleteUser", () => {
swal(
"Admin removed you",
"You have been removed from the room",
"error"
).then(() => {
socket.off();
window.location.href = "/";
});
});
return () => {
socket.emit("disconnect", { name, room });
socket.off();
};
}, [props.match.params, session]);
const handleSendButton = () => {
if (message) {
socket.emit("sendMessage", { name, room, message });
setMessage("");
} else {
swal("Empty Message Field", "", "warning");
}
};
const handleUserDelete = (id) => {};
const startSession = () => {
setIsStarted(true);
socket.emit("startSession", { room });
};
const endSession = () => {
setIsStarted(false);
socket.emit("endSession", { room });
};
useEffect(() => {
socket.on("totalMembers", ({ session }) => {
setSession({ ...session });
});
}, [session]);
useEffect(() => {
socket.on("message", ({ user, text, session }) => {
// setSession(session);
setMessages([...messages, { user, text }]);
});
}, [messages]);
return (
<>
<div className="container">
<div className="chat-room-main-grid">
<div className="card m-1">
<div className="chat-container">
<div>Room: {room}</div>
<div>
{session.isStarted ? (
<>
<div className="green circle"></div>Session is started
</>
) : (
<>
<div className="red circle"></div>
Session is ended or not started yet
</>
)}
</div>
<div className="chat-inner">
{/* Message container */}
{messages.map((data, index) => (
<div
className="m-1 chat-message-container"
key={`message-${index}`}
>
<div>{data.user}:</div>
<div>{data.text}</div>
</div>
))}
{/* Message container */}
</div>
<div className="chat-input-grid">
<div className="justify-center">
<input
className="text-field text-field-1"
value={message}
placeholder="Type a message to send"
onChange={(e) => setMessage(e.target.value)}
onKeyDown={(e) =>
e.keyCode === 13 ? handleSendButton() : null
}
/>
</div>
<div className="justify-center">
<button onClick={handleSendButton}>Send</button>
</div>
<div>
{session.teacher &&
session.teacher.teacherId.name === name ? (
<>
<button onClick={startSession} disabled={isStarted}>
Start Session
</button>
<br />
<button onClick={endSession} disabled={!isStarted}>
End Session
</button>
</>
) : null}
</div>
</div>
</div>
</div>
<div className="card m-1">
<div className="chat-container-1">
<div>Teacher in the room</div>
<div className="chat-inner p-0-5">
{session.teacher ? session.teacher.teacherId.name : null}
</div>
<div>Students in the room</div>
<div className="chat-inner p-0-5">
{session.students
? session.students.map((user, index) => (
<div
key={`users-${index}`}
onClick={() => handleUserDelete(user.id)}
className="strike-th p-0-5"
>
{user.studentId.name}
</div>
))
: null}
</div>
<div>
Total Members:{" "}
{session.teacher ? session.students.length + 1 : 0}
</div>
</div>
</div>
</div>
</div>
</>
);
};
export default ChatRoom;
<file_sep># Live-class-manager-Socket
front end - https://camp12-live-class.herokuapp.com/
back end - http://camp12k-server.herokuapp.com/
<file_sep>import React, { Component } from "react";
import { BrowserRouter as Router, Route } from "react-router-dom";
import JoinRoom from "./components/JoinRoom/JoinRoom";
import ChatRoom from "./components/ChatRoom/ChatRoom";
import "./assets/common/default.css";
class Routes extends Component {
state = {};
render() {
return (
<>
<Router>
<Route exact path="/" component={JoinRoom} />
<Route exact path="/room=:room/name=:name/role=:role" component={ChatRoom} />
</Router>
</>
);
}
}
export default Routes;
|
f9b5c60fe6524162c9b93eff0e1d124d9a42db52
|
[
"JavaScript",
"Markdown"
] | 7 |
JavaScript
|
rahulgarg28071998/Live-class-manager-Socket
|
ae7cd78003e96f12fc375286812a62b188b7d324
|
9f146675c32b10a6fb3b0590abf81eb960918e6f
|
refs/heads/master
|
<file_sep>console.log("<NAME>");
console.log("Subscribete al canal");
|
f0a3d9bfd673cfbaf3a2eea4a9055ad91e953aca
|
[
"JavaScript"
] | 1 |
JavaScript
|
Ruben1793/demo-repo
|
6dd727ab161062afcd6cd6097c8a335173d87a75
|
f9298119a231166f0c0aca82b5b770f30c37eebc
|
refs/heads/master
|
<repo_name>arafeenbd/whatsapp<file_sep>/README.md
npm i firebase, react-router-dom
# Enable Firebase Auth
Goto Firebase > Authentication
Authentication > Get Started > Sign-in method >
Google Enable
npm run build<file_sep>/src/firebase/ChatApi.js
import db from './firebase';
function createChatRoom(room) {
db.collection("rooms").add({
name:room
});
}
export { createChatRoom };
|
0921eae1b3839805c3ad54f812e917d0069da581
|
[
"Markdown",
"JavaScript"
] | 2 |
Markdown
|
arafeenbd/whatsapp
|
43c0f9063d8fffa93763273ce9d2c331ba81f5bb
|
d034887e36f2b08897cf38c40666d65f26f7fafb
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.