moving project SPECTRA to extras

git-svn-id: http://svn.eurecom.fr/openair4G/trunk@7400 818b1a75-f10b-46b9-bf7c-635c3b92a50f
This commit is contained in:
Florian Kaltenberger
2015-05-13 08:09:45 +00:00
parent 847a420395
commit 9f3364f02d
217 changed files with 0 additions and 62004 deletions
-674
View File
@@ -1,674 +0,0 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
Binary file not shown.
Binary file not shown.
@@ -1,270 +0,0 @@
########################################
#
# SPECTRA DEMO INSTALLATION AND RUN
#
#
#
# Rui Costa <ferreira@eurecom.fr>
#
# v1.13 (15 Oct 2014)
#
########################################
########################################
1. REQUIREMENTS
To properly run the demo these are the main pieces of software
that are required:
- OPENAIR4G (checkout the main trunk from the EURECOM SVN).
- ODTONE (Open 802.21 protocol from ITAveiro git server).
- Boost C++ Libraries are requested by ODTONE (v1.48 or higher)
- REST Toolkit (Codename "Casablanca")
- Adequate shell/bash start-up scripts for both eNB and UE.
BEFORE attempting any installation YOU MUST check your system for
any required software that these components require, as for
instance, a compatible GCC/G++ compiler, build tools, etc.
NOTES BEFORE INSTALLATION:
N1. Installation SHOULD NOT be done as ROOT. IF and WHEN super
user permissions are required you will be prompted for them.
N2. You MUST have a valid EURECOM SVN-enabled account for the
Openair4G code.
N3. For ODTONE software, you MUST have installed the ITAveiro
SSL/TLS certificates available at their webserver.
N4. You MUST have Internet access in order to properly build and
deploy the software, as some of the software is fetched online.
########################################
2. BUILD & INSTALL
2.1. PREPARATION
Start by creating a folder on a non-root directory, preferably
your home folder. Copy the <spectra_demo_prepare.sh> script into
the newly created folder, henceforth referred to as
<spectra_root_folder>.
2.2. INSTALLATION
There are two ways of processing the installation:
- If you already have performed a checkout of the OpenAir svn.
(Aimed at single installations for OAI developers.)
- If you only have the demonstration source code & scripts.
(To allow easier deployment over several machines, just copy
the demo's source folder, including the prepare and install
scripts to which ever machine you need and let the scripts do
the work for you)
2.2.1 From the OPENAIR SVN
Go to the folder:
<openair_root_folder>/trunk/targets/PROJECTS/SPECTRA/DEMO_SPECTRA
and run the installation script with the node type to install:
# ./spectra_demo_install.sh -oai_svn <node_type>
2.2.2 From the demo's source code and scripts.
Go to the <spectra_root_folder> and run:
# ./spectra_demo_install.sh -full <node_type>
If the previous step has been well performed, you should now have
a local working copy of the OpenAir SVN on your local machine, along
with additional code required for the demo.
2.3. CRM
This component of the demo MUST be compiled and installed separately.
Check <spectra_root_folder>/CRM/ for more details.
There is a google app that must be running in the google cloud,
and it's url configured in the source code. The local client is based
on the C++ REST framework codenamed "Casablanca".
Furthermore you need to compile the local client components
(CRMClient and CRMMain).
In the CRM client you will find a folder <tosend> which includes some
basic scripts that populate the google app database, and show how to
interact with it.
2.4. TVWS Sensing Measurements
There is a server and client for simulating the TVWS measurements and
run the cognitive algorithm to activate the required actions on the
LTE link. (this is the goal of the demo)
Copy the client & server located at <spectra_root_folder>/clientSensing/
into the ENB2 startup folder (<openair_root_folder>/targets/PROJECTS/SPECTRA)
2.5. TROUBLESHOOTING
If for some reason the installation does not run as expected, check
for permission-related issues or missing software packages.
Otherwise, try to install the components one by one, as defined in
the installation scripts.
(see <spectra_demo_prepare.sh> and <spectra_demo_install.sh> for
compilation and configuration details).
The preparation script will automatically call the installation
script, but in case it does not, run it manually, it is located at:
<spectra_root_folder>/openair4G/targets/PROJECTS/SPECTRA/
NOTE: During installation we apply a patch to ODTONE, due to the
lack of a definition for LTE links and their attributes.
However, as new versions are released the patch may need to
be adapted. Therefore, be aware of compilation issues
originating from the compilation of the ODTONE core functions.
########################################
3. CONFIGURATION
You MUST make sure that the configuration of your physical and
logical interfaces matches with your Open Air and ODTONE
configuration files. Take all parameters into account while
checking the configuration files and launch scripts, located in:
<spectra_root_folder>/openair4G/targets/PROJECTS/SPECTRA/
<spectra_root_folder>/ODTONE/dist/
3.1 Base Configuration
This is the network configuration on the config files:
UE1
eth0 (192.168.13.2) - oai0 (10.0.0.2) (LTE emulated link)
ENB1
eth0 (192.168.12.122) internet access gw (192.168.12.100)
eth1 (192.168.13.1) - oai0 (10.0.0.1) (LTE emulated link)
eth2 (192.168.14.3) (Internal Relay Connection)
UE2
eth0 (192.168.14.4) (Internal Relay Connection)
eth1 (192.168.15.5) - oai0 (10.0.2.3) (LTE emulated link)
ENB2
eth0 (192.168.15.6) - oai0 (10.0.2.4) (LTE emulated link)
########################################
4. RUNNING THE DEMO
1. We advise you to turn off the network manager service in order
for the startup script configuration to be effective and final.
This can be achieved by executing:
# sudo service network-manager stop
2. (On all machines) Go to OpenAir Launch folder:
<spectra_root_folder>/openair4G/targets/PROJECTS/SPECTRA/
3. Launch the eNB1 on eNB1 machine:
# sudo ./start_enb.bash
Wait for eNB1 to reach stand by mode.
4. Launch the UE1 on UE1 machine:
# sudo ./start_ue.bash
5. Launch the eNB2 on eNB2 machine:
# sudo ./start_enb.bash
Wait for eNB2 to reach stand by mode.
6. Launch the UE2 on UE2 machine:
# sudo ./start_ue.bash
7. Any other modules will be launched automatically
if present. (CRM client, TVWS sensing, MIHF, MIH Users, etc.)
Enjoy the demo!
################################################################################
CHANGELOG
v0.99 (03/09/2014)
- First <spectra_demo_prepare.sh> script and <README> file.
v1.00 (04/09/2014)
- Added compartmentalization for each sw component
- Added full installation procedure from scratch
- Fetching sw from repositories, compilation & installation
- Revisioned output
v1.01 (05/09/2014)
- Added OpenAir conf files <spectra_demo_src/openair_conf>
- Added MIHF Users <spectra_demo_src/mih_users>
- Reduced printed output
v1.02 (08/09/2014)
- Bug correcting on installation and configuration paths & scripts
- Patched Open Air script <targets/PROJECTS/SPECTRA/build_all.sh>
v1.03 (09/09/2014)
- Patched MIHF to support LTE link based on previous code
- Added <spectra_demo_src/mihf/>
with patch files: <link.hpp> <bin_query.hpp>
- Revisioned <spectra_demo_prepare.sh>
v1.04 (11/09/2014)
- Corrected MIHF patch bugs
- Added patch file <archive.hpp>
- Corrected path and filename bugs on <spectra_demo_prepare.sh>
v1.05 (15/09/2014)
- Corrected MIHF patch bugs
- Added a number of patch files
- Adjusted patch execution on <spectra_demo_prepare.sh>
v1.06 (17/09/2014)
- Working demo 1 eNB 1 UE
- Modified configuration files for UE and eNB
- Substituted overwrite of files into a Git patch for SPECTRA
v1.07 (19/09/2014)
- Expanded demo to 4 machines:
- 2 real: ue1, eNB1
- 2 virtual: eNB2, ue2 (both hosted by eNB1)
v1.08 (23/09/2014)
- Included CRM client and TVWS sensing modules.
v1.09 (24/09/2014)
- Final Demo setup ready.
v1.10 (29/09/2014)
- Updated RRC code for OpenAir.
- Code commit to OpenAir SVN trunk.
v1.11 (01/10/2014)
- Restructure of source code tree and installation files to
include the full demo (2 eNB and 2 ue)
- Splitted prepare and install scripts.
- Added colour coded steps and error stoppage on install script.
v1.12 (13/10/2014)
- Added bug fixes on launch and install scripts
- Added final version to openair svn
- Reworked README file.
v1.13 (15/10/2014)
- Polishing of the demo
- Added bug fixes on launch scripts for enb1
- Added feature to put measurements on CRM from enb1
- Changed readable output of received measurement reports on enb2
- Added more informative output on the sensingClient (TVWS)
- Demonstration now stops at end of MIH_Link_Actions.confirm
message on MIH_User of enb2
- Added info on sensing client and CRM
- Reworked README file.
################################################################################ EOF
@@ -1,290 +0,0 @@
#!/bin/bash
########################################
#
# SPECTRA DEMO INSTALLATION AND RUN
#
#
#
SCRIPT_VERSION="v1.12"
DATE="13 Oct 2014"
AUTHOR="Rui Costa"
EMAIL="ferreira@eurecom.fr"
########################################
OWN_TAG=$0
INSTALL_PATH=$PWD
OPENAIR_PATH=$INSTALL_PATH/openair4G
ODTONE_PATH=$INSTALL_PATH/ODTONE
BOOST_PATH=$INSTALL_PATH/boost_1_49_0
SPECTRA_SRC_PATH=$INSTALL_PATH/spectra_demo_src
NODE_TYPE=NONE
INSTALL_TYPE=NONE
########################################################################################### UTILS
function util_echo {
# return value passed in $1 (usually $?)
# return value = 0 - OK - Light green
if [ $1 -eq 0 ] ; then
echo -e "\e[92m\e[1m[$OWN_TAG]\e[0m $2"
# return value != 0 - ERROR
else
# return value -gt 255 - WARNING - Light Yellow
if [ $1 -gt 255 ] ; then
echo -e "\e[93m\e[1m[$OWN_TAG]\e[0m $2"
else
# return value 1 to 255 - ERROR - Light RED
echo -e "\e[91m\e[1m[$OWN_TAG]\e[0m $2"
exit
fi
fi
}
########################################################################################### BOOST C++
function fetch_boost {
cd $INSTALL_PATH
util_echo $? "-------------------------------------------------"
util_echo $? "BOOST C++ Library ..."
# Although new versions of boost exist, when compiling ODTONE he asks for v1.49.0
# (we humour it so to not have linkage problems later)
wget --trust-server-names "http://downloads.sourceforge.net/project/boost/boost/1.49.0/boost_1_49_0.tar.gz?r=&ts=1412338583&use_mirror=optimate"
util_echo $? "Fetched BOOST C++ Library ..."
sleep 2
tar -xzf boost_1_49_0.tar.gz
util_echo $? "Extracted BOOST C++ Library ..."
}
function build_boost {
cd $BOOST_PATH
util_echo $? "-------------------------------------------------"
util_echo $? "BOOST C++ Library ..."
sleep 2
# Configuring Boost
./bootstrap.sh
util_echo $? "Bootstrapped BOOST C++ Library ..."
sleep 2
# Compiling Boost (pthread link flag is vital)
./b2 --with-date_time --with-thread linkflags=-lpthread
util_echo $? "Built BOOST C++ Library ..."
}
########################################################################################### ODTONE
function fetch_odtone {
cd $INSTALL_PATH
util_echo $? "-------------------------------------------------"
util_echo $? "ODTONE ..."
sleep 2
# Getting newest version of Odtone
git clone https://github.com/ATNoG/ODTONE.git
util_echo $? "Checked Out ODTONE from ITAveiro GIT..."
cd $ODTONE_PATH
git submodule update --init
util_echo $? "Updated ODTONE submodules..."
}
function build_odtone {
cd $ODTONE_PATH
util_echo $? "-------------------------------------------------"
util_echo $? "ODTONE ..."
# /***** REPLACED WITH Git spectra PATCH
#
# Establishing the pointer to a local compilation of boost instead of the usual in /usr/local/src/
#touch boost-build.jam
#echo "boost-build $BOOST_PATH/tools/build/v2 ;" > boost-build.jam
# Copying our new MIH Users
#cp -r $SPECTRA_SRC_PATH/mih_users/* $ODTONE_PATH/app/
# we MUST patch these files! ODTONE by default has no knowledge of LTE links
# this overwrite of files ensures that full LTE link parameters exist.
# A better way of paching the files should be implemented later!!
#cp -r $SPECTRA_SRC_PATH/mihf/link.hpp $ODTONE_PATH/inc/odtone/mih/types/
#cp -r $SPECTRA_SRC_PATH/mihf/archive.hpp $ODTONE_PATH/inc/odtone/mih/detail/
#cp -r $SPECTRA_SRC_PATH/mihf/address.hpp $ODTONE_PATH/inc/odtone/mih/types/
#cp -r $SPECTRA_SRC_PATH/mihf/bin_query.hpp $ODTONE_PATH/inc/odtone/mih/types/
#cp -r $SPECTRA_SRC_PATH/mihf/CMakeLists.txt $ODTONE_PATH/lib/odtone/
#cp -r $SPECTRA_SRC_PATH/mihf/conf.cpp $ODTONE_PATH/lib/odtone/
#cp -r $SPECTRA_SRC_PATH/mihf/conf.hpp $ODTONE_PATH/inc/odtone/
#cp -r $SPECTRA_SRC_PATH/mihf/Jamfile $ODTONE_PATH/lib/odtone/
#cp -r $SPECTRA_SRC_PATH/mihf/command_service.cpp $ODTONE_PATH/src/mihf/
#cp -r $SPECTRA_SRC_PATH/mihf/dst_transaction.cpp $ODTONE_PATH/src/mihf/
#cp -r $SPECTRA_SRC_PATH/mihf/event_service.cpp $ODTONE_PATH/src/mihf/
#cp -r $SPECTRA_SRC_PATH/mihf/link_book.cpp $ODTONE_PATH/src/mihf/
#cp -r $SPECTRA_SRC_PATH/mihf/main.cpp $ODTONE_PATH/src/mihf/
#cp -r $SPECTRA_SRC_PATH/mihf/service_access_controller.cpp $ODTONE_PATH/src/mihf/
#cp -r $SPECTRA_SRC_PATH/mihf/service_management.cpp $ODTONE_PATH/src/mihf/
#cp -r $SPECTRA_SRC_PATH/mihf/src_transaction.cpp $ODTONE_PATH/src/mihf/
#cp -r $SPECTRA_SRC_PATH/mihf/transaction_pool.cpp $ODTONE_PATH/src/mihf/
#
# *****/
# Applying SPECTRA patch to ODTONE source code
git apply --check --stat $SPECTRA_SRC_PATH/common/mihf_src/0001-SPECTRA-patch-for-ODTONE-v0.1.patch
util_echo $? "Checking if SPECTRA patch can be aplied..."
git apply $SPECTRA_SRC_PATH/common/mihf_src/0001-SPECTRA-patch-for-ODTONE-v0.1.patch
util_echo $? "Applying SPECTRA patch to ODTONE..."
# Changing hostname on the boost build
sed -i "s%nikaia%$USER%g" $ODTONE_PATH/boost-build.jam
util_echo $? "Modifying boost-build.jam..."
# Compiling Odtone core
$BOOST_PATH/b2 linkflags=-lpthread
util_echo $? "Compiled ODTONE..."
# Copying lte_test_user for this node
rm -rf $ODTONE_PATH/app/lte_test_user
cp -r $SPECTRA_SRC_PATH/$NODE_TYPE/mih_user/* $ODTONE_PATH/app/
util_echo $? "Installed ODTONE mih user for: $NODE_TYPE..."
# Compiling lte_test_user
$BOOST_PATH/b2 app/lte_test_user/ linkflags=-lpthread linkflags=-lrt
util_echo $? "Compiled ODTONE apps..."
# Copying odtone confs
cp $SPECTRA_SRC_PATH/$NODE_TYPE/mih_conf/*.conf $ODTONE_PATH/dist/
util_echo $? "Installed ODTONE configuration files for: $NODE_TYPE..."
}
########################################################################################### OPENAIR
function fetch_openair {
mkdir $OPENAIR_PATH
cd $INSTALL_PATH
util_echo $? "-------------------------------------------------"
util_echo $? "OPENAIR EURECOM ..."
sleep 2
svn co http://svn.eurecom.fr/openair/openair4G/trunk $OPENAIR_PATH
util_echo $? "Checked Out openair4G/trunk from EURECOM SVN..."
}
function build_openair {
cd $OPENAIR_PATH
util_echo $? "-------------------------------------------------"
util_echo $? "OPENAIR ..."
sleep 2
# Putting in place pre-made scripts for the build of openair
cp $SPECTRA_SRC_PATH/common/openair_scripts/* $OPENAIR_PATH/targets/PROJECTS/SPECTRA/
util_echo $? "Installed OpenAir common build scripts ..."
# Putting in place pre-made scripts for the conf of openair
cp $SPECTRA_SRC_PATH/$NODE_TYPE/oai_conf/* $OPENAIR_PATH/targets/PROJECTS/SPECTRA/
util_echo $? "Installed OpenAir startup scripts and conf for $NODE_TYPE..."
cd $OPENAIR_PATH/targets/PROJECTS/SPECTRA/
# Updating the path location of ODTONE and BOOST on the script, according to the local machine.
sed -i "s%path_to_boost_folder%$BOOST_PATH%g" env_802dot21.bash
util_echo $? " Fixed BOOST path in env_802dot21.bash... $BOOST_PATH"
sed -i "s%path_to_odtone_folder%$ODTONE_PATH%g" env_802dot21.bash
util_echo $? " Fixed ODTONE path in env_802dot21.bash... $ODTONE_PATH"
if [ $NODE_TYPE == "enb2" ] ; then
sed -i "s%enb_lte_user%enb2_lte_user%g" env_802dot21.bash
util_echo $? " Fixed exec name (enb2_lte_user) for $NODE_TYPE..."
# sed -i "s%ENB_MIH_USER_CONF_FILE=enb_lte_user.conf%ENB_MIH_USER_CONF_FILE=enb2_lte_user.conf%g" env_802dot21.bash
util_echo $? " Fixed conf name (enb2_lte_user.conf) for path $NODE_TYPE..."
fi
if [ $NODE_TYPE == "ue2" ] ; then
sed -i "s%ue_lte_user%ue2_user%g" env_802dot21.bash
util_echo $? " Fixed exec name (enb2_lte_user) for $NODE_TYPE..."
util_echo $? " Fixed conf name (enb2_lte_user.conf) for path $NODE_TYPE..."
fi
# executing the (re)build of all components
# superuser necessary for installing the ITTY tool of openair
./build_all.bash
util_echo $? "Finished OpenAir build..."
}
########################################################################################### PRINT_HELP
function print_help {
util_echo 333 " -------------------------------------------------"
util_echo 333 " USAGE: "
util_echo 333 " $ $OWN_TAG <install_type> <node_type>"
util_echo 333 " "
util_echo 333 " <install_type>"
util_echo 333 " -full If you start from scratch"
util_echo 333 " -oai_svn If you got this script after"
util_echo 333 " checking out the Openair SVN"
util_echo 333 " <node_type>"
util_echo 333 " -ue1 For installing ue1 files"
util_echo 333 " -ue2 For installing ue2 files"
util_echo 333 " -enb1 For installing eNB1 files"
util_echo 333 " -enb2 For installing eNB2 files"
util_echo 333 " "
util_echo 333 " -------------------------------------------------"
util_echo 333 " "
exit
}
########################################################################################### MAIN
clear
# Testing Args
if [ $# -ne 2 ]; then
util_echo 333 " Incorrect Number of Arguments!!"
print_help
fi
if [ $1 == "-full" ]; then
INSTALL_TYPE=FULL
fi
if [ $1 == "-oai_svn" ]; then
INSTALL_TYPE=OAISVN
fi
if [ $2 == "-ue1" ]; then
NODE_TYPE=ue1
fi
if [ $2 == "-ue2" ]; then
NODE_TYPE=ue2
fi
if [ $2 == "-enb1" ]; then
NODE_TYPE=enb1
fi
if [ $2 == "-enb2" ]; then
NODE_TYPE=enb2
fi
if [ $INSTALL_TYPE == "NONE" ]; then
util_echo 333 " Incorrect Arguments (type of installation) !!"
print_help
fi
if [ $NODE_TYPE == "NONE" ]; then
util_echo 333 " Incorrect Arguments (type of node) !!"
print_help
fi
# Starting...
util_echo $? " -------------------------------------------------"
util_echo $? " SPECTRA DEMO "
util_echo $? " Installation Script"
util_echo $? " "
util_echo $? " $SCRIPT_VERSION $DATE"
util_echo $? " "
util_echo $? " Author: $AUTHOR <$EMAIL> "
util_echo $? " -------------------------------------------------"
util_echo 333 " Performing installation type: $INSTALL_TYPE for $NODE_TYPE"
sleep 3
util_echo $? " -------------------------------------------------"
util_echo $? " >> Fetching sources"
util_echo $? " -------------------------------------------------"
if [ $INSTALL_TYPE == "OAISVN" ]; then
INSTALL_PATH=$PWD/../../../../
OPENAIR_PATH=$PWD/../../../
ODTONE_PATH=$INSTALL_PATH/ODTONE
BOOST_PATH=$INSTALL_PATH/boost_1_49_0
SPECTRA_SRC_PATH=$PWD/spectra_demo_src
else
fetch_openair
fi
fetch_odtone
fetch_boost
sleep 1
util_echo $? " -------------------------------------------------"
util_echo $? " >> Building"
util_echo $? " -------------------------------------------------"
sleep 2
build_boost
build_odtone
build_openair
util_echo 333 " Open Air Configuration files at:"
util_echo 333 " $OPENAIR_PATH/targets/PROJECTS/SPECTRA/"
util_echo 333 " "
util_echo 333 " ODTONE Configuration files at:"
util_echo 333 " $ODTONE_PATH/dist/"
util_echo $? " "
util_echo $? " "
util_echo $? " -------------------------------------------------"
util_echo $? " SPECTRA DEMO preparation script ... finished!"
util_echo $? " -------------------------------------------------"
cd $INSTALL_PATH
exit 0
########################################################################################### EOF
@@ -1,80 +0,0 @@
#!/bin/bash
########################################
#
# SPECTRA DEMO PREPARATION
#
#
#
SCRIPT_VERSION="v1.12"
DATE="13 Oct 2014"
AUTHOR="Rui Costa"
EMAIL="ferreira@eurecom.fr"
########################################
OWN_TAG=$0
INSTALL_PATH=$PWD
OPENAIR_PATH=$INSTALL_PATH/openair4G
ODTONE_PATH=$INSTALL_PATH/ODTONE
BOOST_PATH=$INSTALL_PATH/boost_1_49_0
SPECTRA_SRC_PATH=$INSTALL_PATH/spectra_demo_src
SPECTRA_OAI_PATH=$OPENAIR_PATH/targets/PROJECTS/SPECTRA/
########################################################################################### UTILS
function util_echo {
# return value passed in $1 (usually $?)
# return value = 0 - OK - Light green
if [ $1 -eq 0 ] ; then
echo -e "\e[92m\e[1m[$OWN_TAG]\e[0m $2"
# return value != 0 - ERROR
else
# return value -gt 255 - WARNING - Light Yellow
if [ $1 -gt 255 ] ; then
echo -e "\e[93m\e[1m[$OWN_TAG]\e[0m $2"
else
# return value 1 to 255 - ERROR - Light RED
echo -e "\e[91m\e[1m[$OWN_TAG]\e[0m $2"
exit
fi
fi
}
########################################################################################### OPENAIR
function fetch_openair {
mkdir $OPENAIR_PATH
cd $INSTALL_PATH
util_echo $? "-------------------------------------------------"
util_echo $? "OPENAIR EURECOM ..."
sleep 2
svn co http://svn.eurecom.fr/openair/openair4G/trunk $OPENAIR_PATH
util_echo $? "Checked Out openair4G/trunk from EURECOM SVN..."
}
########################################################################################### MAIN
clear
# Starting...
util_echo $? " -------------------------------------------------"
util_echo $? " SPECTRA DEMO "
util_echo $? " Prepararation Script"
util_echo $? " "
util_echo $? " $SCRIPT_VERSION $DATE"
util_echo $? " "
util_echo $? " Author: $AUTHOR <$EMAIL> "
util_echo $? " -------------------------------------------------"
util_echo $? " "
sleep 3
util_echo $? " -------------------------------------------------"
util_echo $? " >> Fetching sources"
util_echo $? " -------------------------------------------------"
fetch_openair
cd $SPECTRA_OAI_PATH/
util_echo $? " >> Finished Prepare Script!!"
util_echo $? " >> Entering Install Script!!"
./spectra_demo_install.sh -oai_svn $1
########################################################################################### EOF
@@ -1,249 +0,0 @@
#include <cpprest/http_client.h>
#include <cpprest/json.h>
#include <iostream>
#include <ostream>
#include <sstream>
#include <fstream>
#include "cpprest/basic_types.h"
#include "cpprest/asyncrt_utils.h"
#include "cpprest/uri.h"
#include <string>
#include "CRMClient.hpp"
using namespace std;
using namespace web;
using namespace web::http;
using namespace web::http::client;
using namespace utility;
// namespace odtone {
CRMClient::CRMClient(char* url)
{
m_url = (char*) (malloc (200* sizeof (char)));
m_url = url;
}
CRMClient::CRMClient()
{
}
CRMClient::~CRMClient()
{
}
void CRMClient::SetUrl(char* url)
{
m_url = url;
}
// Retrieves a JSON value from an HTTP request.
pplx::task<void> CRMClient::RequestJSONValueAsync()
{
http_client client (U(m_url));
return client.request(methods::GET).then([](http_response response) -> pplx::task<json::value>
{
if(response.status_code() == status_codes::OK)
{
return response.extract_json();
}
return pplx::task_from_result(json::value());
})
.then([](pplx::task<json::value> previousTask)
{
try
{
ofstream myfile;
myfile.open ("outputGET.txt");
const json::value& v = previousTask.get();
string_t jsonString = v.to_string();
cout << U("Response...") << jsonString <<endl;
//Parsing Begin
cout << U("Start Parsing...") << endl;
for(auto iterArray = v.cbegin(); iterArray != v.cend(); ++iterArray)
{
const json::value &arrayValue = iterArray->second;
for(auto iterInner = arrayValue.cbegin(); iterInner != arrayValue.cend(); ++iterInner)
{
const json::value &propertyValue = iterInner->second;
for(auto iterlast = propertyValue.cbegin(); iterlast != propertyValue.cend(); ++iterlast)
{
const json::value &Name = iterlast->first;
const json::value &Value = iterlast->second;
cout<< U("Parameter: ") << Name.to_string()<<endl;
cout<< U("Value: ") << Value.to_string()<< std::endl;
}
}
cout << std::endl;
}
//parsing End
myfile << jsonString.c_str();
myfile.close();
}
catch (const http_exception& e)
{
wostringstream ss;
ss << e.what() << endl;
wcout << ss.str();
}
});
}
// Stores a JSON value (a Policy) from an HTTP request.
pplx::task<void> CRMClient::StoreJSONValuePolicies(char * param1, char * param2, char * param3, char * param4)
{
http_client client (U(m_url));
json::value::field_map putvalue;
putvalue.push_back(make_pair(json::value("pid"), json::value(param1)));
putvalue.push_back(make_pair(json::value("name"), json::value(param2)));
putvalue.push_back(make_pair(json::value("description"), json::value(param3)));
putvalue.push_back(make_pair(json::value("value"), json::value(param4)));
const string_t& s = "/";
json::value object = json::value::object(putvalue);
return client.request(methods::PUT, s, object).then([](http_response response)-> pplx::task<json::value>
{
if(response.status_code() == status_codes::OK)
{
return response.extract_json();
}
return pplx::task_from_result(json::value());
})
.then([](pplx::task<json::value> previousTask)
{
try
{
const json::value& v = previousTask.get();
string_t jsonString = v.to_string();
cout << U("Response...") << jsonString <<endl;
}
catch (const http_exception& e)
{
wostringstream ss;
ss << e.what() << endl;
wcout << ss.str();
}
});
}
// Stores a JSON value (a Measurement) from an HTTP request.
pplx::task<void> CRMClient::StoreJSONValuemeasurements(char * param1, char * param2, char * param3, char * param4, char * param5, char * param6)
{
http_client client (U(m_url));
json::value::field_map putvalue;
putvalue.push_back(make_pair(json::value("key"), json::value(param1)));
putvalue.push_back(make_pair(json::value("name"), json::value(param2)));
putvalue.push_back(make_pair(json::value("type"), json::value(param3)));
putvalue.push_back(make_pair(json::value("unit"), json::value(param4)));
putvalue.push_back(make_pair(json::value("value"), json::value(param5)));
putvalue.push_back(make_pair(json::value("time"), json::value(param6)));
const string_t& s = "/";
json::value object = json::value::object(putvalue);
return client.request(methods::PUT, s, object).then([](http_response response)-> pplx::task<json::value>
{
if(response.status_code() == status_codes::OK)
{
return response.extract_json();
}
return pplx::task_from_result(json::value());
})
.then([](pplx::task<json::value> previousTask)
{
try
{
const json::value& v = previousTask.get();
string_t jsonString = v.to_string();
cout << U("Response...") << jsonString <<endl;
}
catch (const http_exception& e)
{
wostringstream ss;
ss << e.what() << endl;
wcout << ss.str();
}
});
}
// Stores a JSON value (a Decision) from an HTTP request.
pplx::task<void> CRMClient::StoreJSONValuedecisions(char * param1, char * param2, char * param3, char * param4, char * param5)
{
http_client client (U(m_url));
json::value::field_map putvalue;
putvalue.push_back(make_pair(json::value("did"), json::value(param1)));
putvalue.push_back(make_pair(json::value("name"), json::value(param2)));
putvalue.push_back(make_pair(json::value("description"), json::value(param3)));
putvalue.push_back(make_pair(json::value("value"), json::value(param4)));
putvalue.push_back(make_pair(json::value("time"), json::value(param5)));
const string_t& s = "/";
json::value object = json::value::object(putvalue);
return client.request(methods::PUT, s, object).then([](http_response response)-> pplx::task<json::value>
{
if(response.status_code() == status_codes::OK)
{
return response.extract_json();
}
return pplx::task_from_result(json::value());
})
.then([](pplx::task<json::value> previousTask)
{
try
{
const json::value& v = previousTask.get();
string_t jsonString = v.to_string();
cout << U("Response...") << jsonString <<endl;
}
catch (const http_exception& e)
{
wostringstream ss;
ss << e.what() << endl;
wcout << ss.str();
}
});
}
pplx::task<void> CRMClient::Delete()
{
char* url = m_url;
return pplx::create_task([url]
// return pplx::create_task([m_url]
{
http_client client (U(url));
return client.request(methods::DEL);
}).then([](http_response response)
{
if(response.status_code() == status_codes::OK)
{
auto body = response.extract_string();
std::wcout << L"Deleted: " << body.get().c_str() << std::endl;
}
});
}
// }
@@ -1,56 +0,0 @@
//==============================================================================
// Brief : MIH-User
// Authors : FATMA HRIZI <hrizi@eurecom.fr>
//------------------------------------------------------------------------------
// ODTONE - Open Dot Twenty One
//
// Copyright (C) 2009-2012 Universidade Aveiro
// Copyright (C) 2009-2012 Instituto de Telecomunicações - Pólo Aveiro
//
// This software is distributed under a license. The full license
// agreement can be found in the file LICENSE in this distribution.
// This software may not be copied, modified, sold or distributed
// other than expressed in the named license agreement.
//
// This software is distributed without any warranty.
//==============================================================================
#ifndef ODTONE_CRM_CLIENT_HPP
#define ODTONE_CRM_CLIENT_HPP
#include <cpprest/http_client.h>
#include <cpprest/json.h>
#include <iostream>
#include <ostream>
#include <sstream>
#include "cpprest/basic_types.h"
#include "cpprest/asyncrt_utils.h"
#include "cpprest/uri.h"
#include <string>
// namespace odtone {
class CRMClient {
public:
CRMClient();
~CRMClient();
CRMClient(char* url);
void SetUrl(char* url);
pplx::task<void> RequestJSONValueAsync();
pplx::task<void> StoreJSONValuePolicies(char * param1, char * param2, char * param3, char * param4);
pplx::task<void> StoreJSONValuemeasurements(char * param1, char * param2, char * param3, char * param4, char * param5, char * param6);
pplx::task<void> StoreJSONValuedecisions(char * param1, char * param2, char * param3, char * param4, char * param5);
pplx::task<void> Delete();
private:
char * m_url;
};
// }
#endif
@@ -1,26 +0,0 @@
# CRMClient.o: CRMClient.cpp CRMClient.hpp
# g++-4.8 CRMClient.cpp -I /opt/casablanca/Release/include/ -L/usr/local/lib -L/opt/casablanca/Binaries/Release32/ -std=c++11 -lpthread -lboost_system -lboost_thread -lcasablanca -lboost_filesystem
#
#
# install: main.cpp
# g++-4.8 -Wall main.cpp -I /opt/casablanca/Release/include/ -L/usr/local/lib -L/opt/casablanca/Binaries/Release32/ -L. -std=c++11 -lcrmclient -lpthread -lboost_system -lboost_thread -lcasablanca -lboost_filesystem -o CRMClientmain
main: main.cpp
g++-4.8 -Wall main.cpp -I /opt/casablanca/Release/include/ -L/usr/local/lib -L/opt/casablanca/Binaries/Release32/ -L. -std=c++11 -lcrmclient -lpthread -lboost_system -lboost_thread -lcasablanca -lboost_filesystem -o CRMClientmain
lib: CRMClient.cpp CRMClient.hpp
# 64 bits compilation
# g++-4.8 -Wall -fPIC -c CRMClient.cpp -I /opt/casablanca/Release/include/ -L/usr/local/lib -L/opt/casablanca/Binaries/Release32/ -std=c++11 -m64 -lpthread -lboost_system -lboost_thread -lcasablanca -lboost_filesystem
# g++-4.8 -shared -m64 -Wl,-soname,libcrmclient.so.1 -o libcrmclient.so.1.0 CRMClient.o
# ln -sf libcrmclient.so.1.0 libcrmclient.so
# ln -sf libcrmclient.so.1.0 libcrmclient.so.1
# 32 bits compilation
g++-4.8 -Wall -fPIC -c CRMClient.cpp -I /opt/casablanca/Release/include/ -L/usr/local/lib -L/opt/casablanca/Binaries/Release32/ -std=c++11 -lpthread -lboost_system -lboost_thread -lcasablanca -lboost_filesystem
g++-4.8 -shared -Wl,-soname,libcrmclient.so.1 -o libcrmclient.so.1.0 CRMClient.o
ln -sf libcrmclient.so.1.0 libcrmclient.so
ln -sf libcrmclient.so.1.0 libcrmclient.so.1
clean:
rm *.o *.so*
@@ -1,21 +0,0 @@
#include "CRMClient.hpp"
int main(int argc,char *argv[])
{
char * policiesurl = (char*) malloc( 100 * sizeof(char) );
strcpy(policiesurl,"http://1.gae-spectra.appspot.com/policies");
// strcpy(policiesurl,"http://localhost:8888/policies");
char * measurementsurl = (char*) malloc( 100* sizeof(char) );
strcpy(measurementsurl,"http://1.gae-spectra.appspot.com/measurements");
// strcpy(measurementsurl,"http://localhost:8888/measurements");
char * decisionsurl = (char*) malloc( 100 * sizeof(char));
strcpy(decisionsurl,"http://1.gae-spectra.appspot.com/decisions");
int c;
CRMClient client (policiesurl);
client.RequestJSONValueAsync().wait();
return 0;
}
@@ -1,19 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<classpath>
<classpathentry kind="src" path="src"/>
<classpathentry exported="true" kind="con" path="com.google.appengine.eclipse.core.GAE_CONTAINER"/>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
<classpathentry kind="lib" path="lib/org.restlet.jar"/>
<classpathentry kind="lib" path="lib/org.restlet.ext.servlet.jar"/>
<classpathentry kind="lib" path="lib/org.restlet.ext.wadl.jar"/>
<classpathentry kind="lib" path="lib/org.restlet.ext.xml.jar"/>
<classpathentry kind="lib" path="lib/org.restlet.ext.json.jar"/>
<classpathentry kind="lib" path="lib/org.json.jar"/>
<classpathentry kind="lib" path="lib/org.springframework.context-3.1.1.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/org.springframework.web-3.1.1.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/org.springframework.web.servlet-3.1.1.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/org.springframework.beans-3.1.1.RELEASE.jar"/>
<classpathentry kind="lib" path="lib/json_simple-1.1.jar"/>
<classpathentry kind="lib" path="lib/gcm-server.jar"/>
<classpathentry kind="output" path="war/WEB-INF/classes"/>
</classpath>
@@ -1,43 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<projectDescription>
<name>rest-gae-server</name>
<comment></comment>
<projects>
</projects>
<buildSpec>
<buildCommand>
<name>org.eclipse.wst.common.project.facet.core.builder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>org.eclipse.jdt.core.javabuilder</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.gdt.eclipse.core.webAppProjectValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.appengine.eclipse.core.gaeProjectChangeNotifier</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.appengine.eclipse.core.projectValidator</name>
<arguments>
</arguments>
</buildCommand>
<buildCommand>
<name>com.google.appengine.eclipse.core.enhancerbuilder</name>
<arguments></arguments>
</buildCommand>
</buildSpec>
<natures>
<nature>org.eclipse.jdt.core.javanature</nature>
<nature>com.google.appengine.eclipse.core.gaeNature</nature>
<nature>org.eclipse.wst.common.project.facet.core.nature</nature>
</natures>
</projectDescription>
@@ -1,9 +0,0 @@
#Thu Sep 19 14:41:16 CEST 2013
eclipse.preferences.version=1
filesCopiedToWebInfLib=appengine-api-1.0-sdk-1.7.4.jar|appengine-api-labs.jar|appengine-endpoints.jar|appengine-jsr107cache-1.7.4.jar|asm-4.0.jar|datanucleus-api-jdo-3.1.1.jar|datanucleus-api-jpa-3.1.1.jar|datanucleus-appengine-2.1.1.jar|datanucleus-core-3.1.1.jar|geronimo-jpa_2.0_spec-1.0.jar|jdo-api-3.0.1.jar|jsr107cache-1.1.jar|jta-1.1.jar
gaeDatanucleusVersion=v2
gaeDeployDialogSettings=true
gaeIsEclipseDefaultInstPath=true
googleCloudSqlEnabled=false
localDevMySqlEnabled=true
ormEnhancementInclusions=src/
@@ -1,5 +0,0 @@
#Wed Dec 12 09:47:01 CET 2012
eclipse.preferences.version=1
jarsExcludedFromWebInfLib=
warSrcDir=war
warSrcDirIsOutput=true
@@ -1,13 +0,0 @@
<?xml version="1.0" encoding="utf-8" standalone="no"?>
<jdoconfig xmlns="http://java.sun.com/xml/ns/jdo/jdoconfig" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="http://java.sun.com/xml/ns/jdo/jdoconfig">
<persistence-manager-factory name="transactions-optional">
<property name="javax.jdo.PersistenceManagerFactoryClass" value="org.datanucleus.api.jdo.JDOPersistenceManagerFactory"/>
<property name="javax.jdo.option.ConnectionURL" value="appengine"/>
<property name="javax.jdo.option.NontransactionalRead" value="true"/>
<property name="javax.jdo.option.NontransactionalWrite" value="true"/>
<property name="javax.jdo.option.RetainValues" value="true"/>
<property name="datanucleus.appengine.autoCreateDatastoreTxns" value="true"/>
<property name="datanucleus.appengine.singletonPMFForName" value="true"/>
</persistence-manager-factory>
</jdoconfig>
@@ -1,12 +0,0 @@
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="1.0" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="transactions-optional">
<provider>org.datanucleus.api.jpa.PersistenceProviderImpl</provider>
<properties>
<property name="datanucleus.NontransactionalRead" value="true"/>
<property name="datanucleus.NontransactionalWrite" value="true"/>
<property name="datanucleus.ConnectionURL" value="appengine"/>
</properties>
</persistence-unit>
</persistence>
@@ -1,181 +0,0 @@
package fr.eurecom.pushing;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.mortbay.log.Log;
import org.restlet.resource.Get;
import fr.eurecom.senml.entity.RegisteredDeviceType;
import fr.eurecom.senml.persistence.JDOStorage;
/**
* Exposes the following URLs:
* - /pushing/register, POST, to register a device
* - /pushing/unregister, POST, to unregister a device
* - /pushing/list, GET, to retrieve the list of registered devices
* - /pushing/test, GET, test a notification to the registered devices
*
*/
public class DeviceManager extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final Logger log = Logger.getLogger("DeviceManager");
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
System.out.println("OK doPost");
System.out.println(request.getParameter("reqType") + " " + request.getParameter("deviceType"));
try {
if (request.getParameter("reqType").equals("reg")) {
// Registration of a device. Android or iOS?
if (request.getParameter("deviceType").equals("android")) {
registerAndroidDevice(request, response);
} else if (request.getParameter("deviceType").equals("ios")) {
registerAppleDevice(request, response);
}
} else if (request.getParameter("reqType").equals("unreg")) {
System.out.println("OK UNREGISTERING!");
if (request.getParameter("deviceType").equals("android")) {
System.out.println("UNREGISTERING ANDROID!");
unregisterAndroidDevice(request, response);
} else if (request.getParameter("deviceType").equals("ios")) {
unregisterAppleDevice(request, response);
}
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
response.setStatus(500);
}
}
private void unregisterAppleDevice(HttpServletRequest request,
HttpServletResponse response) {
// TODO Auto-generated method stub
response.setStatus(403);
}
private void unregisterAndroidDevice(HttpServletRequest request,
HttpServletResponse response) {
String key = request.getParameter("registrationID");
// TODO Auto-generated method stub
List<RegisteredDeviceType> devices = JDOStorage.getInstance().getAll(RegisteredDeviceType.class);
Iterator<RegisteredDeviceType> iter = devices.iterator();
while (iter.hasNext()) {
RegisteredDeviceType device = iter.next();
System.out.print("Analyzing " + device.getDeviceRegistrationKey());
if (device.getDeviceRegistrationKey().equals(key)) {
JDOStorage.getInstance().delete(device);
System.out.println("OK");
return;
} else {
System.out.println("NO!");
}
}
}
private void registerAppleDevice(HttpServletRequest request, HttpServletResponse response) {
// TODO Auto-generated method stub
response.setStatus(403);
}
private void registerAndroidDevice(HttpServletRequest request, HttpServletResponse response) throws JSONException, IOException {
Date n = new Date();
boolean isadmin = (request.getParameter("isadmin") != null);
RegisteredDeviceType device = new RegisteredDeviceType(
UUID.randomUUID().toString(),
request.getParameter("deviceType") + ": " + request.getParameter("deviceDet"),
request.getParameter("devicekey"), n.getTime());
if (isadmin) {
System.out.println("ADMIN");
device.setIsadmin(isadmin);
}
JDOStorage.getInstance().write(device);
response.setContentType("text/html");
PrintWriter writer = response.getWriter();
response.setStatus(200);
writer.write("Registered");
}
/**
* Handle HTTP GET method / Json
*
* @return a JSON Zone Representation
*/
@Get
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
PrintWriter writer = response.getWriter();
if (request.getPathInfo().equals("/test")) {
GCMPushingServer GCM = GCMPushingServer.getInstance();
try {
GCM.sendNotification("notification test ");
writer.write("Sent a notification test to the following devices:");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else if (request.getPathInfo().equals("/alarm")) {
GCMPushingServer GCM = GCMPushingServer.getInstance();
try {
GCM.sendNotification("ALARM for sensor: " + request.getParameter("sensor"));
writer.write("OK");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
writer.write("NO");
}
return;
}
List<RegisteredDeviceType> devices = JDOStorage.getInstance().getAll(RegisteredDeviceType.class);
if (devices.isEmpty()) {
// No devices registered
response.setStatus(200);
writer.write("The list of devices is empty.");
return;
}
response.setContentType("text/html");
JSONArray jsonDevices = new JSONArray();
Iterator<RegisteredDeviceType> iter = devices.iterator();
writer.write("<table border=1><tr style=\"font-weight: bold;\"><th>Device Logo</th><th>Device Type</th><th>registered on</th><th>Registration Key</th></tr>");
// Get the list of devices and build the json
try {
while (iter.hasNext()) {
RegisteredDeviceType current = iter.next();
JSONObject obj = new JSONObject(current);
jsonDevices.put(obj);
String deviceLogo = obj.getString("deviceType").split(":")[0].toLowerCase();
writer.write("<tr><td><img src=\"/images/" + deviceLogo + ".jpg\"/></td><td>"
+ obj.getString("deviceType") + "</td><td>"
+ obj.getString("time") + "</td><td>"
+ obj.getString("deviceRegistrationKey") + "</td></tr>");
}
writer.write("</table>");
} catch (Exception e) {
response.setStatus(500);
log.log(Level.WARNING, "", e);
}
}
}
@@ -1,206 +0,0 @@
package fr.eurecom.pushing;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import com.google.android.gcm.server.Message;
import com.google.android.gcm.server.MulticastResult;
import com.google.android.gcm.server.Sender;
import fr.eurecom.senml.entity.RegisteredDeviceType;
import fr.eurecom.senml.entity.SensorAdmin;
import fr.eurecom.senml.persistence.JDOStorage;
public class GCMPushingServer implements IPushingServer {
private List<String> REG_IDS, ADMIN_REG_IDS;
// HARD-CODED, move on a different configuration file!
private String API_KEY = "AIzaSyDO3RS9FZPTp0d2BNn-0zKUuiiOI45-ED8";
private boolean initialized = false;
private static final GCMPushingServer instance = new GCMPushingServer();
protected GCMPushingServer() {
}
public static GCMPushingServer getInstance() {
if (!instance.isInitialized()) {
instance.initialize();
}
return instance;
}
public boolean isInitialized() {
return initialized;
}
public void initialize() {
REG_IDS = ADMIN_REG_IDS = new ArrayList<String>();
initialized = true;
}
public void refreshDevicesList() {
REG_IDS = new ArrayList<String>();
List<RegisteredDeviceType> list = JDOStorage.getInstance().getAll(
RegisteredDeviceType.class);
Iterator<RegisteredDeviceType> iter = list.iterator();
while (iter.hasNext()) {
RegisteredDeviceType current = iter.next();
if (isAndroidDevice(current)) {
if (current.isIsadmin()) {
if (ADMIN_REG_IDS.indexOf(current) == -1) {
System.out.println("Refreshing the list of admins...adding "
+ current.getDeviceRegistrationKey());
ADMIN_REG_IDS.add(current.getDeviceRegistrationKey());
}
} else {
if (REG_IDS.indexOf(current) == -1) {
System.out.println("Refreshing the list...adding "
+ current.getDeviceRegistrationKey());
REG_IDS.add(current.getDeviceRegistrationKey());
}
}
}
}
}
/**
* Return true if the device is of type Android
*
* @param device
* @return
*/
private boolean isAndroidDevice(RegisteredDeviceType device) {
System.out.print("isAndroidDevice? ");
if (device.getDeviceType().toLowerCase().indexOf("android") > -1) {
System.out.println("Yes");
} else {
System.out.println("No");
}
return (device.getDeviceType().toLowerCase().indexOf("android") > -1);
}
@Override
public void sendNotification(String data) throws JSONException {
// Refresh the devices list and put it on the JSON object
refreshDevicesList();
System.out.println("Calling gcmnotify with data = " + data);
GCMnotify(data);
// TODO: Check that is part of monitored sensors
GCMnotify(data, true);
}
private void GCMnotify(String data) {
System.out.println("Sending data: " + data);
// Instance of com.android.gcm.server.Sender, that does the
// transmission of a Message to the Google Cloud Messaging service.
Sender sender = new Sender(API_KEY);
// This Message object will h old the data that is being transmitted
// to the Android client devices. For this demo, it is a simple text
// string, but could certainly be a JSON object.
Message message = new Message.Builder()
// If multiple messages are sent using the same .collapseKey()
// the android target device, if it was offline during earlier
// message
// transmissions, will only receive the latest message for that
// key when
// it goes back on-line.
// .collapseKey(collapseKey)
.timeToLive(30).delayWhileIdle(true)
.addData("type", "zoneupdated")
.addData("notificationmessage", "WL-BOX, zone updated: " + data.replace("ZoneUpdated", ""))
.addData("alertstatus", "info")
.addData("message", data).build();
if (REG_IDS.size() == 0) {
// Noone to notify
return;
}
try {
// use this for multicast messages. The second parameter
// of sender.send() will need to be an array of register ids.
MulticastResult result = sender.send(message, REG_IDS, 1);
if (result.getResults() != null) {
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// TODO: Only one constructor, most of the code is the same...
private void GCMnotify(String data, boolean isadmin) {
System.out.println("ADMIN! Sending data: " + data);
// Instance of com.android.gcm.server.Sender, that does the
// transmission of a Message to the Google Cloud Messaging service.
Sender sender = new Sender(API_KEY);
// This Message object will h old the data that is being transmitted
// to the Android client devices. For this demo, it is a simple text
// string, but could certainly be a JSON object.
Message message = new Message.Builder()
// If multiple messages are sent using the same .collapseKey()
// the android target device, if it was offline during earlier
// message
// transmissions, will only receive the latest message for that
// key when
// it goes back on-line.
// .collapseKey(collapseKey)
.timeToLive(30).delayWhileIdle(true)
.addData("type", "alert")
.addData("notificationmessage", "WL-BOX admin, SENSOR ALERT!")
.addData("alertstatus", "alert")
.addData("message", data).build();
if (ADMIN_REG_IDS.size() == 0) {
// Noone to notify
System.out.println("Admin IDS empty");
return;
}
try {
// use this for multicast messages. The second parameter
// of sender.send() will need to be an array of register ids.
MulticastResult result = sender.send(message, ADMIN_REG_IDS, 1);
if (result.getResults() != null) {
System.out.println("!) null");
int canonicalRegId = result.getCanonicalIds();
if (canonicalRegId != 0) {
}
} else {
int error = result.getFailure();
System.out.println("Broadcast failure: " + error);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@@ -1,7 +0,0 @@
package fr.eurecom.pushing;
import org.json.JSONException;
public interface IPushingServer {
public void sendNotification(String data) throws JSONException;
}
@@ -1,146 +0,0 @@
package fr.eurecom.restlet.resources.common;
/**
* This class implements the Contact entity.
*
*/
public class Contact {
// private static final long serialVersionUID = 7390103290165670089L;
/**
* Contact's identifier.
*/
private final int id;
/**
* Contact's first name
*/
private String firstName = "N/A";
/**
* Contact's last name
*/
private String lastName = "N/A";
/**
* Contact's email address
*/
private String mail = "N/A";
/**
* Contact's phone number
*/
private String phone = "N/A";
/**
* Constructs a contact with the specified id.
*
* @param id
*/
public Contact(int id) {
this.id = id;
}
/**
* Constructs a contact with the specified values.
*
* @param id
* Contact's identifier.
* @param firstname
* Contact's first name.
* @param lastname
* Contact's last name.
* @param mail
* Contact's email address.
* @param phone
* Contact's Phone number.
*/
public Contact(int id, String firstname, String lastname, String mail,
String phone) {
this.id = id;
this.firstName = firstname;
this.lastName = lastname;
this.mail = mail;
this.phone = phone;
}
/**
*
* @return the contact id.
*/
public int getId() {
return id;
}
/**
* Set an email address
*
* @param mail
* email address.
*/
public void setMail(String mail) {
this.mail = mail;
}
/**
* Retrieve the email address.
*
* @return the mail address if set, "N/A" otherwise.
*/
public String getMail() {
return mail;
}
/**
* Retrieve the first name.
*
* @return the first name if set, "N/A" otherwise.
*/
public String getFirstName() {
return firstName;
}
/**
* Set a first name.
*
* @param firstname
* to set.
*/
public void setFirstName(String firstname) {
this.firstName = firstname;
}
/**
* Retrieve the last name.
*
* @return the last name set, "N/A" otherwise.
*/
public String getLastName() {
return lastName;
}
/**
* Set a last name.
*
* @param lastname
* to set, "N/A" otherwise.
*/
public void setLastName(String lastname) {
this.lastName = lastname;
}
/**
* Retrieve the phone number.
*
* @return the phone set, "N/A" otherwise.
*/
public String getPhone() {
return phone;
}
/**
* Set the phone number.
*
* @param phone
* number to set.
*/
public void setPhone(String phone) {
this.phone = phone;
}
}
@@ -1,173 +0,0 @@
package fr.eurecom.restlet.resources.common;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.restlet.data.Status;
import org.restlet.ext.wadl.WadlServerResource;
import com.google.appengine.api.channel.ChannelMessage;
import com.google.appengine.api.channel.ChannelService;
import com.google.appengine.api.channel.ChannelServiceFactory;
import fr.eurecom.restlet.resources.persistence.Storage;
public abstract class ContactBaseResource extends WadlServerResource {
private final static String CONTACTS_UPDATED = "contactsupdated";
private static final Logger log = Logger.getLogger("ContactBaseResource");
public enum MEMBERS {
CONTACT, ID, FIRSTNAME, LASTNAME, PHONE, MAIL
}
protected static final String CONTACTS = "contacts";
protected static final String CONTACT = "contact";
protected static final String ID = "id";
protected static final String FIRST_NAME = "firstname";
protected static final String LAST_NAME = "lastname";
protected static final String PHONE = "phone";
protected static final String MAIL = "mail";
protected static final String URL = "url";
protected static final String REQUEST_QUERY_SORT = "sort";
// HACK, this class is also used to support subscribers for senml objects. Move the subscribers channel API Stuffs to a common place.
protected static final Map<String, Token> subscribers = new HashMap<String, Token>();
final static class Token {
public String token;
public long timestamp;
public Token(String token) {
this.token = token;
this.timestamp = System.currentTimeMillis();
}
}
/**
* Retrieve the contacts from the persistence layer.
*
* @return the contact's list.
*/
protected List<Contact> getContacts() {
// Dispatcher d = (Dispatcher)getApplication();
return Storage.getInstance().getContacts(MEMBERS.ID, 0, 999);
}
/**
* Retrieve the contacts sorted by Last name from the persistence layer.
*
* @return a sorted contacts list.
*/
@SuppressWarnings("unchecked")
protected List<Contact> getSortedContacts(String sort) {
try {
MEMBERS mSorted = sort == null || sort.trim().isEmpty() ? MEMBERS.LASTNAME
: MEMBERS.valueOf(sort.trim().toUpperCase());
return Storage.getInstance().getContacts(mSorted, 0, 999);
} catch (Exception e) {
e.printStackTrace();
return Collections.EMPTY_LIST;
}
}
/**
* Retrieve the contact which matches this id from the persistence layer.
*
* @param id
* @return contact or null.
*/
protected Contact getContact(int id) {
return Storage.getInstance().getContact(id);
}
/**
* Delete a contact from the persistence layer.
*
* @param id
* @return Status.SUCCESS_NO_CONTENT if deleted,
* Status.CLIENT_ERROR_NOT_FOUND otherwise.
*/
protected Status removeContact(int id) {
if (Storage.getInstance().removeContact(id)) {
sendUpdateSubscribers(CONTACTS_UPDATED);
return Status.SUCCESS_NO_CONTENT;
}
else {
return Status.CLIENT_ERROR_NOT_FOUND;
}
}
/**
* Save a new contact to the persistence layer. (restricted to 50 contacts
* currently).
*
* @param contact
* @return Status.SUCCESS_CREATED if saved,
* Status.SERVER_ERROR_INSUFFICIENT_STORAGE otherwise.
*/
protected Status addContact(Contact contact) {
if (Storage.getInstance().saveContact(contact)) {
sendUpdateSubscribers(CONTACTS_UPDATED);
return Status.SUCCESS_CREATED;
}
return Status.SERVER_ERROR_INSUFFICIENT_STORAGE;
}
/**
* Update a contact to the persistence layer.
*
* @param contact
* @return Status.SUCCESS_OK if updated, Status.CLIENT_ERROR_NOT_FOUND
* otherwise.
*/
protected Status updateContact(Contact contact) {
if (Storage.getInstance().saveContact(contact)) {
sendUpdateSubscribers(CONTACTS_UPDATED);
return Status.SUCCESS_NO_CONTENT;
} else {
return Status.CLIENT_ERROR_NOT_FOUND;
}
}
public static void addSubscriber(String clientID, String token) {
subscribers.put(clientID, new Token(token));
}
public static void deleteSubscriber(String clientID) {
subscribers.remove(clientID);
}
public static String getToken(String clientID) {
Token t = subscribers.get(clientID);
if (t != null && (System.currentTimeMillis() - t.timestamp) < 7200000) {
return t.token;
}
else {
return null;
}
}
public static void sendUpdateSubscribers(String message) {
ChannelService service = ChannelServiceFactory.getChannelService();
try {
service.sendMessage(new ChannelMessage("I235", message));
log.info("Notified I235" + message);
}
catch (Exception e) {
log.log(Level.WARNING, "Error Notifying client I235", e);
System.out.println("Error notifying client I235");
}
/* for (String clientID : subscribers.keySet()) {
System.out.println("Will notify " + clientID + " " + message);
service.sendMessage(new ChannelMessage(clientID, message));
}
*/
}
}
@@ -1,242 +0,0 @@
package fr.eurecom.restlet.resources.common;
import java.util.Map;
import org.json.JSONObject;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.wadl.MethodInfo;
import org.restlet.ext.wadl.ParameterInfo;
import org.restlet.ext.wadl.ParameterStyle;
import org.restlet.ext.wadl.RepresentationInfo;
import org.restlet.ext.wadl.RequestInfo;
import org.restlet.ext.wadl.ResponseInfo;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Delete;
import org.restlet.resource.Get;
import org.restlet.resource.Put;
import org.restlet.resource.ResourceException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
*
* This class represents the Contact resource
*/
public class ContactResource extends ContactBaseResource {
/**
* underlying contact.
*/
private Contact contact = null;
/**
* Resource contact identifier.
*/
private int identifier = -1;
@Override
public Representation describe() {
System.out.println("describe");
setName("Contact Resource");
setDescription("Manage the current Contact");
return super.describe();
}
@Override
public void describeDelete(MethodInfo mInfo) {
mInfo.setIdentifier("ContactDelete");
mInfo.setDocumentation("To Delete the current contact.");
ResponseInfo response = new ResponseInfo(
"Contact deleted. No contents returned.");
response.getStatuses().add(Status.SUCCESS_NO_CONTENT);
mInfo.getResponses().add(response);
response = new ResponseInfo("Contact not found");
response.getStatuses().add(Status.CLIENT_ERROR_NOT_FOUND);
mInfo.getResponses().add(response);
}
@Override
public void describeGet(MethodInfo mInfo) {
mInfo.setIdentifier("ContactDetail");
mInfo.setDocumentation("To retrieve details of the current contact.");
ResponseInfo response = new ResponseInfo("Current contact details");
response.getStatuses().add(Status.SUCCESS_OK);
RepresentationInfo repInfo = new RepresentationInfo(
MediaType.APPLICATION_XML);
repInfo.setXmlElement(CONTACT);
repInfo.setDocumentation("XML representation of the current contact.");
response.getRepresentations().add(repInfo);
repInfo = new RepresentationInfo(MediaType.APPLICATION_JSON);
repInfo.setDocumentation("JSON representation of the current contact");
repInfo.setXmlElement(CONTACT);
response.getRepresentations().add(repInfo);
mInfo.getResponses().add(response);
response = new ResponseInfo("Contact not found");
repInfo = new RepresentationInfo(MediaType.TEXT_HTML);
repInfo.setIdentifier("contactError");
response.getStatuses().add(Status.CLIENT_ERROR_NOT_FOUND);
response.getRepresentations().add(repInfo);
mInfo.getResponses().add(response);
}
@Override
public void describePut(MethodInfo mInfo) {
mInfo.setIdentifier("ContactUpdate");
mInfo.setDocumentation("To update details of the current contact");
RequestInfo requestInfo = new RequestInfo();
// requestInfo.getParameters().add(
// new ParameterInfo(ID, true, "Number", ParameterStyle.QUERY,
// "Contact identifier"));
requestInfo.getParameters().add(
new ParameterInfo(FIRST_NAME, false, "String",
ParameterStyle.QUERY, "Contact First Name"));
requestInfo.getParameters().add(
new ParameterInfo(LAST_NAME, false, "String",
ParameterStyle.QUERY, "Contact Last Name"));
requestInfo.getParameters().add(
new ParameterInfo(PHONE, false, "String", ParameterStyle.QUERY,
"Contact Phone number"));
requestInfo.getParameters().add(
new ParameterInfo(MAIL, false, "String", ParameterStyle.QUERY,
"Contact email address"));
mInfo.setRequest(requestInfo);
ResponseInfo responseInfo = new ResponseInfo("Contact not Found");
responseInfo.getStatuses().add(Status.CLIENT_ERROR_NOT_FOUND);
mInfo.getResponses().add(responseInfo);
responseInfo = new ResponseInfo(
"Contact updated, no contents returned.");
responseInfo.getStatuses().add(Status.SUCCESS_NO_CONTENT);
mInfo.getResponses().add(responseInfo);
}
@Override
protected void doInit() throws ResourceException {
String sIdentifier = (String) getRequest().getAttributes().get("id");
if (sIdentifier != null) {
identifier = Integer.parseInt(sIdentifier);
contact = getContact(identifier);
}
setExisting(contact != null);
}
/**
* Handle HTTP GET method / xml
*
* @return a xml resource representation
*/
@Get("xml")
public Representation toXML() {
try {
DomRepresentation representation = new DomRepresentation(
MediaType.TEXT_XML);
Document d = representation.getDocument();
Element eltItem = d.createElement(CONTACT);
d.appendChild(eltItem);
Element el = d.createElement(ID);
el.appendChild(d.createTextNode("" + contact.getId()));
eltItem.appendChild(el);
el = d.createElement(FIRST_NAME);
el.appendChild(d.createTextNode(contact.getFirstName()));
eltItem.appendChild(el);
el = d.createElement(LAST_NAME);
el.appendChild(d.createTextNode(contact.getLastName()));
eltItem.appendChild(el);
el = d.createElement(PHONE);
el.appendChild(d.createTextNode(contact.getPhone()));
eltItem.appendChild(el);
el = d.createElement(MAIL);
el.appendChild(d.createTextNode(contact.getMail()));
eltItem.appendChild(el);
d.normalizeDocument();
return representation;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* Handle HTTP GET method / json
*
* @return a json resource representation.
*/
@Get("json")
public Representation toJSON() {
JSONObject jObject = new JSONObject();
try {
jObject.put(ID, "" + contact.getId());
jObject.put(FIRST_NAME, contact.getFirstName());
jObject.put(LAST_NAME, contact.getLastName());
jObject.put(PHONE, contact.getPhone());
jObject.put(MAIL, contact.getMail());
return new JsonRepresentation(jObject);
} catch (Exception e) {
return null;
}
}
/**
* Handle HTTP PUT method. Update an existing contact.
*
* @param entity
*/
@Put
public void updateContact(Representation entity) {
Map<String, String> map = new Form(entity).getValuesMap();
for (String k : map.keySet()) {
MEMBERS m = MEMBERS.valueOf(k.toUpperCase());
switch (m) {
case FIRSTNAME:
contact.setFirstName(map.get(k));
break;
case LASTNAME:
contact.setLastName(map.get(k));
break;
case PHONE:
contact.setPhone(map.get(k));
break;
case MAIL:
contact.setMail(map.get(k));
break;
}
}
Status updateStatus = super.updateContact(contact);
setStatus(updateStatus);
}
/**
* Handle HTTP DELETE method. Delete an existing contact.
*/
@Delete
public void deleteContact() {
Status deleteStatus = super.removeContact(identifier);
setStatus(deleteStatus);
}
}
@@ -1,335 +0,0 @@
package fr.eurecom.restlet.resources.common;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.Form;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.wadl.MethodInfo;
import org.restlet.ext.wadl.OptionInfo;
import org.restlet.ext.wadl.ParameterInfo;
import org.restlet.ext.wadl.ParameterStyle;
import org.restlet.ext.wadl.RepresentationInfo;
import org.restlet.ext.wadl.RequestInfo;
import org.restlet.ext.wadl.ResponseInfo;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
public class ContactsResource extends ContactBaseResource {
/**
* {@inheritDoc}
*/
@Override
public Representation describe() {
setName("Contacts Resource");
setDescription("Retrieve contacts list");
return super.describe();
}
/**
* {@inheritDoc}
*/
@Override
public void describeGet(MethodInfo mInfo) {
mInfo.setIdentifier("ContactsList");
mInfo.setDocumentation("To Retrieve a sorted list of contacts");
RequestInfo requestInfo = new RequestInfo();
ParameterInfo pInfo = createCommonParameter(REQUEST_QUERY_SORT,
"Sort query", LAST_NAME);
pInfo.getOptions().add(
createOptionInfo(FIRST_NAME, "Sort by first name"));
pInfo.getOptions()
.add(createOptionInfo(LAST_NAME, "Sort by last name"));
pInfo.getOptions().add(createOptionInfo(MAIL, "Sort by Email"));
pInfo.getOptions().add(createOptionInfo(PHONE, "Sort by Phone"));
requestInfo.getParameters().add(pInfo);
mInfo.setRequest(requestInfo);
ResponseInfo response = new ResponseInfo("Current list of contacts");
response.getStatuses().add(Status.SUCCESS_OK);
RepresentationInfo repInfo = new RepresentationInfo(
MediaType.APPLICATION_XML);
repInfo.setXmlElement(CONTACTS);
repInfo.setDocumentation("XML List of contacts");
response.getRepresentations().add(repInfo);
repInfo = new RepresentationInfo(MediaType.APPLICATION_JSON);
repInfo.setXmlElement(CONTACTS);
repInfo.setDocumentation("JSON List of contacts");
response.getRepresentations().add(repInfo);
mInfo.getResponses().add(response);
}
/**
* {@inheritDoc}
*/
@Override
public void describePost(MethodInfo mInfo) {
mInfo.setIdentifier("ContactsAdd");
mInfo.setIdentifier("To add a new contact to the list");
RequestInfo requestInfo = new RequestInfo();
requestInfo.getParameters().add(
new ParameterInfo(ID, true, "Number", ParameterStyle.QUERY,
"Contact identifier"));
requestInfo.getParameters().add(
createCommonParameter(FIRST_NAME, "Contact First Name"));
requestInfo.getParameters().add(
createCommonParameter(LAST_NAME, "Contact Last Name"));
requestInfo.getParameters().add(
createCommonParameter(PHONE, "Contact Phone Number"));
requestInfo.getParameters().add(
createCommonParameter(MAIL, "Contact Email address"));
mInfo.setRequest(requestInfo);
ResponseInfo response = new ResponseInfo("Contact saved");
response.getStatuses().add(Status.SUCCESS_CREATED);
response.getParameters().add(
new ParameterInfo("Content-Location", ParameterStyle.HEADER,
"URI contact saved"));
mInfo.getResponses().add(response);
response = new ResponseInfo("Contact not saved. (restricted to 50)");
response.getStatuses().add(Status.SERVER_ERROR_INSUFFICIENT_STORAGE);
mInfo.getResponses().add(response);
}
// HACK: Version Restlet-gae 2.1-rc5.
// There is an error routing the GET request when
// the Request Header Content-Type = application/x-www-form-urlencoded and
// Header Accept = "application/json" and
// URI have a query : http://localhost:8888/contacts?sort=firstname.
// In this case the router ignores the Accept header and route the request
// to @Get("xml") systematically because the query is badly interpreted.
// To workaround this problem, at the init we reformat the Entity with an
// empty Representation.
@Override
public void init(Context context, Request request, Response response) {
// System.out.println("init" + request + " " + response);
// System.out.println("Content-Type: " +
// request.getEntity().getMediaType());
if (request.getMethod().compareTo(Method.GET) == 0) {
Representation entity = request.getEntity();
System.out.println("Entity " + entity + " Content-Type: "
+ request.getEntity().getMediaType());
request.setEntity(new StringRepresentation(""));
}
super.init(context, request, response);
}
/**
* Handle HTTP GET Metod / xml
*
* @return an XML list of contacts.
*/
@Get("xml")
public Representation toXML() {
// System.out.println("Request Original Ref " + getOriginalRef());
// System.out.println("Request Entity " + getRequest().getEntityAsText()
// +
// " entity mediaType " + getRequest().getEntity().getMediaType());
Reference ref = getRequest().getResourceRef();
final String baseURL = ref.getHierarchicalPart();
Form formQuery = ref.getQueryAsForm();
try {
DomRepresentation representation = new DomRepresentation(
MediaType.TEXT_XML);
Document d = representation.getDocument();
Element elContacts = d.createElement(CONTACTS);
d.appendChild(elContacts);
Iterator<Contact> it = getSortedContacts(
formQuery.getFirstValue(REQUEST_QUERY_SORT, LAST_NAME))
.iterator();
while (it.hasNext()) {
Contact contact = it.next();
Element el = d.createElement(CONTACT);
Element id = d.createElement(ID);
id.appendChild(d.createTextNode(String.format("%s",
contact.getId())));
el.appendChild(id);
Element firstname = d.createElement(FIRST_NAME);
firstname.appendChild(d.createTextNode(contact.getFirstName()));
el.appendChild(firstname);
Element lastname = d.createElement(LAST_NAME);
lastname.appendChild(d.createTextNode(contact.getLastName()));
el.appendChild(lastname);
Element url = d.createElement(URL);
url.appendChild(d.createTextNode(String.format("%s/%s",
baseURL, contact.getId())));
el.appendChild(url);
elContacts.appendChild(el);
}
d.normalizeDocument();
return representation;
} catch (Exception e) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
/**
* Handle HTTP GET method / Json
*
* @return a JSON list of contacts.
*/
@Get("json")
public Representation toJSON() {
// System.out.println("Request Original Ref " + getOriginalRef());
// System.out.println("Request Entity " + getRequest().getEntityAsText()
// +
// " entity mediaType " + getRequest().getEntity().getMediaType());
try {
JSONArray jcontacts = new JSONArray();
Reference ref = getRequest().getResourceRef();
final String baseURL = ref.getHierarchicalPart();
Form formQuery = ref.getQueryAsForm();
Iterator<Contact> it = getSortedContacts(
formQuery.getFirstValue(REQUEST_QUERY_SORT, LAST_NAME))
.iterator();
while (it.hasNext()) {
Contact contact = it.next();
JSONObject jcontact = new JSONObject();
jcontact.put(ID, String.format("%s", contact.getId()));
jcontact.put(URL, String.format("%s/%s", baseURL, contact.getId()));
jcontact.put(FIRST_NAME, contact.getFirstName());
jcontact.put(LAST_NAME, contact.getLastName());
jcontacts.put(jcontact);
}
JSONObject contacts = new JSONObject();
contacts.put(CONTACTS, jcontacts);
return new JsonRepresentation(contacts);
} catch (Exception e) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
/**
* Handle HTTP POST Method.
*
* @param entity
* contact to create.
* @return The new contact URI representation (Header Content-Location).
*/
@Post
public Representation createContact(Representation entity) {
Form form = new Form(entity);
try {
int id = Integer.parseInt(form.getFirstValue(ID, "-1"));
if (id == -1) {
System.out.println("id = -1");
setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED,
"Must provide 'id' field.");
return null;
}
Contact contact = getContact(id) == null ? new Contact(id)
: getContact(id);
contact.setFirstName(form.getFirstValue(FIRST_NAME, "N/A"));
contact.setLastName(form.getFirstValue(LAST_NAME, "N/A"));
contact.setPhone(form.getFirstValue(PHONE, "N/A"));
contact.setMail(form.getFirstValue(MAIL, "N/A"));
Status createStatus = super.addContact(contact);
setStatus(createStatus);
Representation rep = new StringRepresentation("Contact created",
MediaType.TEXT_PLAIN);
rep.setLocationRef(String.format("%s/%s", getRequest()
.getResourceRef().getIdentifier(), id));
return rep;
} catch (Exception e) {
e.printStackTrace();
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
/**
* Helper Method creating common form of ParameterInfo
*
* @param name
* ParameterInfo name
* @param description
* ParameterInfo description
* @return ParameterInfo formatted : required=false, parameterStyle=Query,
* defaultValue="N/A", type="String".
*/
private static ParameterInfo createCommonParameter(String name,
String description) {
return createCommonParameter(name, description, "N/A");
}
/**
* Helper Method creating common form of ParameterInfo
*
* @param name
* - ParameterInfo name
* @param description
* - ParameterInfo description
* @param defaultValue
* - ParameterInfo defaultValue.
* @return ParameterInfo formatted : required=false, parameterStyle=Query,
* type="String".
*/
private static ParameterInfo createCommonParameter(String name,
String description, String defaultValue) {
ParameterInfo pi = new ParameterInfo(name, false, "String",
ParameterStyle.QUERY, description);
pi.setDefaultValue(defaultValue);
return pi;
}
/**
* Helper method creating an OptionInfo
*
* @param value
* Option's value
* @param description
* - Option's description
* @return an OptionInfo with the specified values.
*/
private static OptionInfo createOptionInfo(String value, String description) {
OptionInfo oi = new OptionInfo(description);
oi.setValue(value);
return oi;
}
}
@@ -1,69 +0,0 @@
package fr.eurecom.restlet.resources.common;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONObject;
import org.restlet.data.Form;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.wadl.MethodInfo;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import com.google.appengine.api.channel.ChannelServiceFactory;
public class ContactsSubResource extends ContactBaseResource {
private static final Logger log = Logger.getLogger("ContactSubResource");
/**
* {@inheritDoc}
*/
@Override
public void describePost(MethodInfo mInfo) {
}
/**
* Handle HTTP GET Subscribe method
*
* @param entity - must contains the client id channel.
* @return a JSON Representation of the token.
*/
@Get
public Representation subscribe(Representation entity) {
Reference ref = getRequest().getResourceRef();
Form formQuery = ref.getQueryAsForm();
JSONObject json = new JSONObject();
try {
String clientID = formQuery.getFirstValue("clientID", "").trim();
if (clientID.isEmpty()) {
log.warning("client ID not found");
setStatus(Status.CLIENT_ERROR_EXPECTATION_FAILED,
"Must provide a clientID field.");
return null;
}
String token = getToken(clientID);
if (token == null) {
token = ChannelServiceFactory.getChannelService().createChannel(clientID);
log.info("Create a new token [" + token + "]");
addSubscriber(clientID, token);
}
else {
log.info("Token already existing for client " + clientID);
}
json.append("token", token);
return new JsonRepresentation(json);
} catch (Exception e) {
e.printStackTrace();
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
}
@@ -1,149 +0,0 @@
package fr.eurecom.restlet.resources.common;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.wadl.MethodInfo;
import org.restlet.ext.wadl.RepresentationInfo;
import org.restlet.ext.wadl.ResponseInfo;
import org.restlet.ext.wadl.WadlServerResource;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Delete;
import org.restlet.resource.Put;
import org.restlet.resource.Post;
import fr.eurecom.senml.entity.*;
import fr.eurecom.senml.persistence.JDOStorage;
public class SensorInResource extends WadlServerResource {
private static final Logger log = Logger.getLogger("SensorInResource");
private static final MediaType SENML_JSON = MediaType.valueOf("application/senml+json");
/**
* {@inheritDoc}
*/
@Override
public Representation describe() {
setName("Sensor-In Resource");
setDescription("Acquisition sensors receiver");
return super.describe();
}
@Post
@Put
public void updateSensor(Representation entity) {
JSONObject jObject = null;
String text = null;
try {
MediaType mt = entity.getMediaType();
text = entity.getText();
if (mt.isCompatible(MediaType.APPLICATION_JSON) || mt.isCompatible(SENML_JSON) ) {
jObject = new JSONObject(text);
}
else {
setStatus(Status.CLIENT_ERROR_NOT_ACCEPTABLE, "Content is not JSON compatible");
log.info("This entry cause a 406 response / reason not json");
return;
}
String bn = jObject.has(ISensor.BASE_NAME) ? jObject.getString(ISensor.BASE_NAME) : null;
long bt = jObject.has(ISensor.BASE_TIME) ? jObject.getLong(ISensor.BASE_TIME) : Long.MIN_VALUE;
String bu = jObject.has(ISensor.BASE_UNIT) ? jObject.getString(ISensor.BASE_UNIT) : null;
if (! jObject.has(ISensor.MEASUREMENT) || bn == null) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, "Parameter Base Name[bn] or measure[e] missing.");
log.info("This entry cause a 400 response. reason bn - e missing ||" + text + "||");
return;
}
JSONArray measures = jObject.getJSONArray(ISensor.MEASUREMENT);
// TODO: Remove this hack: zone key is static. For first tests with IQSIM and demo.
IZone zone = JDOStorage.getInstance().getById("Aix", ZoneAdmin.class);
SensorAdmin sa = new SensorAdmin(bn, "Generic Sensor", zone);
boolean parsingOK = true;
String reasonPhrase = null;
for (int i = 0; i < measures.length(); i++) {
JSONObject m = measures.getJSONObject(i);
Measure.ParamTypeValue tv = getUnitType(m);
if (tv == null) {
parsingOK = false;
reasonPhrase = "Measure miss type value [v|sv|bv]";
break;
}
Units unit = getUnit(m, bu);
if (unit == null) {
parsingOK = false;
reasonPhrase = "parameter unit [bu|u] invalid (missing or unknown)";
break;
}
String name = m.has(Measure.PARAM_NAME) ? m.getString(Measure.PARAM_NAME) : null;
if ( name == null || name.trim().isEmpty()) {
parsingOK = false;
reasonPhrase = "parameter name [n] missing or empty. Not supported";
break;
}
String type = m.has(Measure.PARAM_TYPE) ? m.getString(Measure.PARAM_TYPE) : null;
if ( type == null || type.trim().isEmpty()) {
parsingOK = false;
reasonPhrase = "parameter type [n] missing or empty. Not supported";
break;
}
sa.addMeasure(name.trim(), unit, tv,
m.getString(tv.getSenML()),
m.has(Measure.PARAM_TIME) ? m.getLong(Measure.PARAM_TIME) :
bt == Long.MIN_VALUE ? 0 : bt, type.trim());
}
if (!parsingOK) {
setStatus(Status.CLIENT_ERROR_BAD_REQUEST, reasonPhrase);
log.info("This entry cause a 400 response / reason " + reasonPhrase + " ||" + text + "||");
}
else {
setStatus(Status.SUCCESS_CREATED);
}
}
catch (Exception e) {
log.warning("Unexpected error receiving this entry : ||" + text + "||");
log.log(Level.WARNING, "Unexpected Error", e);
setStatus(Status.SERVER_ERROR_INTERNAL, "Unexpected Error");
}
return;
}
private static Measure.ParamTypeValue getUnitType(JSONObject m) {
if (m.has(Measure.PARAM_VALUE)) {
return Measure.ParamTypeValue.FLOAT;
}
else if (m.has(Measure.PARAM_BOOLEAN_VALUE)) {
return Measure.ParamTypeValue.BOOL;
}
else if (m.has(Measure.PARAM_STRING_VALUE)) {
return Measure.ParamTypeValue.STRING;
}
else if (m.has(Measure.PARAM_SUM_VALUE)) {
return Measure.ParamTypeValue.SUM;
}
return null;
}
private static Units getUnit(JSONObject m, String bu) throws JSONException {
String u = m.has(Measure.PARAM_UNIT) ? m.getString(Measure.PARAM_UNIT) : bu != null ? bu : null;
return u == null ? null : Units.getUnit(u);
}
}
@@ -1,278 +0,0 @@
package fr.eurecom.restlet.resources.common;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.data.Tag;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.wadl.MethodInfo;
import org.restlet.ext.wadl.RepresentationInfo;
import org.restlet.ext.wadl.ResponseInfo;
import org.restlet.ext.wadl.WadlServerResource;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.restlet.resource.Post;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import fr.eurecom.restlet.resources.common.ZonesResource.ZoneFormat;
import fr.eurecom.senml.entity.ISensor;
import fr.eurecom.senml.entity.IZone;
import fr.eurecom.senml.entity.PostValAdmin;
import fr.eurecom.senml.entity.ZoneAdmin;
import fr.eurecom.senml.persistence.JDOStorage;
public class SensorPost extends WadlServerResource {
private static final Logger log = Logger.getLogger("SensorPost");
/**
* {@inheritDoc}
*/
@Override
public Representation describe() {
setName("Sensor Post");
setDescription("Post Something, is a test!");
return super.describe();
}
@Post("json")
public Representation doPost(String entity) {
String senmlValue = (String) getRequest().getAttributes().get("senml");
//IZone zone = JDOStorage.getInstance().getById(id, ZoneAdmin.class);
JSONObject jzone = new JSONObject();
try {
jzone.put("senml", senmlValue);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Date n = new Date();
PostValAdmin sa = new PostValAdmin();
sa.addPost("testing post " + String.valueOf(n),
entity,
"NOW".equals(n) ? 0 : System.currentTimeMillis());
Representation out = new JsonRepresentation(jzone);
return out;
}
/**
* {@inheritDoc}
*/
@Override
public void describeGet(MethodInfo mInfo) {
mInfo.setIdentifier("Sensor Posting");
mInfo.setDocumentation("To Retrieve a zone description");
ResponseInfo response = new ResponseInfo("Current list of zones");
response.getStatuses().add(Status.SUCCESS_OK);
RepresentationInfo repInfo = new RepresentationInfo(
MediaType.APPLICATION_JSON);
repInfo.setDocumentation("JSON array of of the current list zone");
response.getRepresentations().add(repInfo);
mInfo.getResponses().add(response);
}
/**
* Handle HTTP GET method / Json
*
* @return a JSON Zone Representation
*/
@Get("json")
public Representation toJSON() {
final String baseURL = buildBaseURL(getRequest().getResourceRef());
String id = (String) getRequest().getAttributes().get("id");
IZone zone = JDOStorage.getInstance().getById(id, ZoneAdmin.class);
JSONObject jzone = new JSONObject();
try {
jzone.put(ZoneFormat.NAME.getRestAtr(), zone.getName());
JSONArray subZones = new JSONArray();
for (IZone sub : zone.getSubZones()) {
JSONObject z = new JSONObject();
z.put(ZoneFormat.URI.getRestAtr(),
String.format("%s/%s", baseURL, sub.getKey()));
z.put(ZoneFormat.NAME.getRestAtr(), sub.getName());
z.put(ZoneFormat.HAS_SENSORS.getRestAtr(), sub.getSensors()
.size() > 0);
z.put(ZoneFormat.HAS_SUBZONES.getRestAtr(), sub.getSubZones()
.size() > 0);
subZones.put(z);
}
if (subZones.length() > 0) {
jzone.put(ZoneFormat.SUBZONE.getRestAtr(), subZones);
}
JSONArray sensors = new JSONArray();
for (ISensor sensor : zone.getSensors()) {
sensors.put(sensor.toJSONSenML());
}
if (sensors.length() > 0) {
jzone.put(ZoneFormat.SENSORS_SENML.getRestAtr(), sensors);
}
/* String md5 = md5(jzone.toString());
Tag tag = md5 == null ? null : new Tag(md5, false);
if (!isModified(tag)) {
setStatus(Status.REDIRECTION_NOT_MODIFIED);
return null;
}
*/
Representation json = new JsonRepresentation(jzone);
// json.setTag(tag);
return json;
} catch (Exception e) {
setStatus(Status.SERVER_ERROR_INTERNAL);
log.log(Level.WARNING, "", e);
return null;
}
}
/**
* HTTP GET method / xml accept
*
* @return a XML Zone Representation
*/
@Get("xml")
public Representation toXML() {
long before = System.currentTimeMillis();
String id = (String) getRequest().getAttributes().get("id");
IZone zone = JDOStorage.getInstance().getById(id, ZoneAdmin.class);
final String baseURL = buildBaseURL(getRequest().getResourceRef());
try {
DomRepresentation xml = new DomRepresentation(MediaType.TEXT_XML);
Document d = xml.getDocument();
Element currentZone = d.createElement(ZoneFormat.ZONE.getRestAtr());
currentZone.setAttribute(ZoneFormat.NAME.getRestAtr(),
zone.getName());
d.appendChild(currentZone);
for (IZone subzone : zone.getSubZones()) {
Element sub = d.createElement(ZoneFormat.SUBZONE.getRestAtr());
sub.setAttribute(ZoneFormat.NAME.getRestAtr(),
subzone.getName());
sub.setAttribute(ZoneFormat.URI.getRestAtr(),
String.format("%s/%s", baseURL, subzone.getKey()));
sub.setAttribute(ZoneFormat.HAS_SENSORS.getRestAtr(), ""
+ (subzone.getSensors().size() > 0));
sub.setAttribute(ZoneFormat.HAS_SUBZONES.getRestAtr(), ""
+ (subzone.getSubZones().size() > 0));
currentZone.appendChild(sub);
}
for (ISensor sensor : zone.getSensors()) {
Node senml = sensor.toXMLSenML(d);
currentZone.appendChild(senml);
}
/* String md5 = md5(xml.getText());
Tag tag = md5 == null ? null : new Tag(md5, false);
if (!isModified(tag)) {
setStatus(Status.REDIRECTION_NOT_MODIFIED);
return null;
}
*/
// xml.setTag(tag);
return xml;
} catch (Exception e) {
log.log(Level.WARNING, "", e);
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
/*
* Alternative method to add an header to the response. Series<Header>
* responseHeaders = (Series<Header>)
* getResponse().getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); if
* (responseHeaders == null) { responseHeaders = new
* Series<Header>(Header.class); getResponse().getAttributes().put(
* HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders);
*
* } responseHeaders.add(new Header("ETag", md5));
*/
/**
* Build a String baseURL = to current URI/Reference less the last path
* segment.
*
* @param reference
* the current reference object
* @return String base URI.
*/
private String buildBaseURL(Reference reference) {
Reference ref = new Reference(reference);
List<String> segments = ref.getSegments();
if (segments.size() > 0) {
segments.remove(segments.size() - 1);
ref.setSegments(segments);
}
return ref.getHierarchicalPart();
}
private String md5(String value) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(value.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1, digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32
// chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private boolean isModified(Tag currentTag) {
boolean modified = true;
if (currentTag == null) {
return modified;
}
if (getRequest().getConditions() != null
&& getRequest().getConditions().getNoneMatch() != null) {
for (Tag noMatch : getRequest().getConditions().getNoneMatch()) {
if (currentTag.equals(noMatch)) {
modified = false;
break;
}
}
}
return modified;
}
}
@@ -1,255 +0,0 @@
package fr.eurecom.restlet.resources.common;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.restlet.data.MediaType;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.data.Tag;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.wadl.MethodInfo;
import org.restlet.ext.wadl.RepresentationInfo;
import org.restlet.ext.wadl.ResponseInfo;
import org.restlet.ext.wadl.WadlServerResource;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.resource.Get;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import fr.eurecom.restlet.resources.common.ZonesResource.ZoneFormat;
import fr.eurecom.senml.entity.ISensor;
import fr.eurecom.senml.entity.IZone;
import fr.eurecom.senml.entity.ZoneAdmin;
import fr.eurecom.senml.persistence.JDOStorage;
public class ZoneResource extends WadlServerResource {
// Map<String, Tag> etags = new HashMap<String, Tag>();
private static final Logger log = Logger.getLogger("ZoneResource");
/**
* {@inheritDoc}
*/
@Override
public Representation describe() {
setName("Zone Resource");
setDescription("Retrieve a zone description");
return super.describe();
}
/**
* {@inheritDoc}
*/
@Override
public void describeGet(MethodInfo mInfo) {
mInfo.setIdentifier("Zone description");
mInfo.setDocumentation("To Retrieve a zone description");
ResponseInfo response = new ResponseInfo("Current list of zones");
response.getStatuses().add(Status.SUCCESS_OK);
RepresentationInfo repInfo = new RepresentationInfo(
MediaType.APPLICATION_JSON);
repInfo.setDocumentation("JSON array of of the current list zone");
response.getRepresentations().add(repInfo);
mInfo.getResponses().add(response);
}
/**
* Handle HTTP GET method / Json
*
* @return a JSON Zone Representation
*/
@Get("json")
public Representation toJSON() {
final String baseURL = buildBaseURL(getRequest().getResourceRef());
String id = (String) getRequest().getAttributes().get("id");
IZone zone = JDOStorage.getInstance().getById(id, ZoneAdmin.class);
JSONObject jzone = new JSONObject();
try {
jzone.put(ZoneFormat.NAME.getRestAtr(), zone.getName());
JSONArray subZones = new JSONArray();
for (IZone sub : zone.getSubZones()) {
JSONObject z = new JSONObject();
z.put(ZoneFormat.URI.getRestAtr(),
String.format("%s/%s", baseURL, sub.getKey()));
z.put(ZoneFormat.NAME.getRestAtr(), sub.getName());
z.put(ZoneFormat.ZONE_TYPE.getRestAtr(), sub.getType());
z.put(ZoneFormat.HAS_SENSORS.getRestAtr(), sub.getSensors()
.size() > 0);
z.put(ZoneFormat.HAS_SUBZONES.getRestAtr(), sub.getSubZones()
.size() > 0);
subZones.put(z);
}
if (subZones.length() > 0) {
jzone.put(ZoneFormat.SUBZONE.getRestAtr(), subZones);
}
JSONArray sensors = new JSONArray();
for (ISensor sensor : zone.getSensors()) {
sensors.put(sensor.toJSONSenML());
}
if (sensors.length() > 0) {
jzone.put(ZoneFormat.SENSORS_SENML.getRestAtr(), sensors);
}
/* String md5 = md5(jzone.toString());
Tag tag = md5 == null ? null : new Tag(md5, false);
if (!isModified(tag)) {
setStatus(Status.REDIRECTION_NOT_MODIFIED);
return null;
}
*/
Representation json = new JsonRepresentation(jzone);
// json.setTag(tag);
return json;
} catch (Exception e) {
setStatus(Status.SERVER_ERROR_INTERNAL);
log.log(Level.WARNING, "", e);
return null;
}
}
/**
* HTTP GET method / xml accept
*
* @return a XML Zone Representation
*/
@Get("xml")
public Representation toXML() {
long before = System.currentTimeMillis();
String id = (String) getRequest().getAttributes().get("id");
IZone zone = JDOStorage.getInstance().getById(id, ZoneAdmin.class);
final String baseURL = buildBaseURL(getRequest().getResourceRef());
try {
DomRepresentation xml = new DomRepresentation(MediaType.TEXT_XML);
Document d = xml.getDocument();
Element currentZone = d.createElement(ZoneFormat.ZONE.getRestAtr());
currentZone.setAttribute(ZoneFormat.NAME.getRestAtr(),
zone.getName());
currentZone.setAttribute(ZoneFormat.ZONE_TYPE.getRestAtr(), zone.getType());
d.appendChild(currentZone);
for (IZone subzone : zone.getSubZones()) {
Element sub = d.createElement(ZoneFormat.SUBZONE.getRestAtr());
sub.setAttribute(ZoneFormat.NAME.getRestAtr(),
subzone.getName());
sub.setAttribute(ZoneFormat.URI.getRestAtr(),
String.format("%s/%s", baseURL, subzone.getKey()));
sub.setAttribute(ZoneFormat.HAS_SENSORS.getRestAtr(), ""
+ (subzone.getSensors().size() > 0));
sub.setAttribute(ZoneFormat.HAS_SUBZONES.getRestAtr(), ""
+ (subzone.getSubZones().size() > 0));
currentZone.appendChild(sub);
}
for (ISensor sensor : zone.getSensors()) {
Node senml = sensor.toXMLSenML(d);
currentZone.appendChild(senml);
}
/* String md5 = md5(xml.getText());
Tag tag = md5 == null ? null : new Tag(md5, false);
if (!isModified(tag)) {
setStatus(Status.REDIRECTION_NOT_MODIFIED);
return null;
}
*/
// xml.setTag(tag);
return xml;
} catch (Exception e) {
log.log(Level.WARNING, "", e);
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
/*
* Alternative method to add an header to the response. Series<Header>
* responseHeaders = (Series<Header>)
* getResponse().getAttributes().get(HeaderConstants.ATTRIBUTE_HEADERS); if
* (responseHeaders == null) { responseHeaders = new
* Series<Header>(Header.class); getResponse().getAttributes().put(
* HeaderConstants.ATTRIBUTE_HEADERS, responseHeaders);
*
* } responseHeaders.add(new Header("ETag", md5));
*/
/**
* Build a String baseURL = to current URI/Reference less the last path
* segment.
*
* @param reference
* the current reference object
* @return String base URI.
*/
private String buildBaseURL(Reference reference) {
Reference ref = new Reference(reference);
List<String> segments = ref.getSegments();
if (segments.size() > 0) {
segments.remove(segments.size() - 1);
ref.setSegments(segments);
}
return ref.getHierarchicalPart();
}
private String md5(String value) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(value.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1, digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32
// chars.
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private boolean isModified(Tag currentTag) {
boolean modified = true;
if (currentTag == null) {
return modified;
}
if (getRequest().getConditions() != null
&& getRequest().getConditions().getNoneMatch() != null) {
for (Tag noMatch : getRequest().getConditions().getNoneMatch()) {
if (currentTag.equals(noMatch)) {
modified = false;
break;
}
}
}
return modified;
}
}
@@ -1,200 +0,0 @@
package fr.eurecom.restlet.resources.common;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONObject;
import org.mortbay.log.Log;
import org.restlet.Context;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.data.MediaType;
import org.restlet.data.Method;
import org.restlet.data.Reference;
import org.restlet.data.Status;
import org.restlet.ext.json.JsonRepresentation;
import org.restlet.ext.wadl.MethodInfo;
import org.restlet.ext.wadl.RepresentationInfo;
import org.restlet.ext.wadl.ResponseInfo;
import org.restlet.ext.wadl.WadlServerResource;
import org.restlet.ext.xml.DomRepresentation;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.Get;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import fr.eurecom.senml.entity.IZone;
import fr.eurecom.senml.entity.ZoneAdmin;
import fr.eurecom.senml.persistence.JDOStorage;
public class ZonesResource extends WadlServerResource {
public static enum ZoneFormat {
ID("id", "zone identifier"), NAME("name", "zone name"), SUBZONE(
"subzone", "subzone description"),
// SENSORS("sensors","sensors lsit uri"),
PARENT_ZONE("parent", "name zone parent"), ZONE("zone", "Zone"), URI(
"uri", "URI"), HAS_SUBZONES("has_subzones", "Has subzones"), HAS_SENSORS(
"has_sensors", "Has_sensors"), SENSORS_SENML("senml",
"sensors over senml"),ZONE_TYPE("type", "type of the zone");
private final String restAttr;
private final String desc;
ZoneFormat(String restAttr, String desc) {
this.restAttr = restAttr;
this.desc = desc;
}
public String getRestAtr() {
return restAttr;
}
public String getDescription() {
return desc;
}
};
/**
* {@inheritDoc}
*/
@Override
public Representation describe() {
setName("Zones Resource");
setDescription("Retrieve zones list");
return super.describe();
}
/**
* {@inheritDoc}
*/
@Override
public void describeGet(MethodInfo mInfo) {
mInfo.setIdentifier("Zones List");
Log.info("oooooo");
mInfo.setDocumentation("To Retrieve a list of zones");
ResponseInfo response = new ResponseInfo("Current list of zones");
response.getStatuses().add(Status.SUCCESS_OK);
RepresentationInfo repInfo = new RepresentationInfo(
MediaType.APPLICATION_JSON);
repInfo.setDocumentation("JSON array of of the current list zone");
response.getRepresentations().add(repInfo);
mInfo.getResponses().add(response);
}
// HACK: Version Restlet-gae 2.1-rc5.
// There is an error routing the GET request when
// the Request Header Content-Type = application/x-www-form-urlencoded and
// Header Accept = "application/json" and
// URI have a query : http://localhost:8888/contacts?sort=firstname.
// In this case the router ignores the Accept header and route the request
// to @Get("xml") systematically because the query is badly interpreted.
// To workaround this problem, at the init we reformat the Entity with an
// empty Representation.
@Override
public void init(Context context, Request request, Response response) {
// System.out.println("init" + request + " " + response);
// System.out.println("Content-Type: " +
// request.getEntity().getMediaType());
if (request.getMethod().compareTo(Method.GET) == 0) {
Representation entity = request.getEntity();
System.out.println("Entity " + entity + " Content-Type: "
+ request.getEntity().getMediaType());
request.setEntity(new StringRepresentation(""));
}
super.init(context, request, response);
}
/**
* Handle HTTP GET method / Json
*
* @return a JSON list of root zones by default.
*/
@Get("json")
public Representation toJSON() {
// System.out.println("Request Original Ref " + getOriginalRef());
// System.out.println("Request Entity " + getRequest().getEntityAsText()
// +
// " entity mediaType " + getRequest().getEntity().getMediaType());
try {
List<IZone> zones = JDOStorage.getInstance()
.getAll(ZoneAdmin.class);
JSONArray jzones = new JSONArray();
Reference ref = getRequest().getResourceRef();
final String baseURL = ref.getHierarchicalPart();
for (IZone zone : zones) {
if (zone.getParentZone() == null) {
JSONObject jzone = new JSONObject();
jzone.put(ZoneFormat.URI.getRestAtr(),
String.format("%s/%s", baseURL, zone.getKey()));
jzone.put(ZoneFormat.NAME.getRestAtr(), zone.getName());
jzone.put(ZoneFormat.ZONE_TYPE.getRestAtr(), zone.getType());
jzone.put(ZoneFormat.HAS_SENSORS.getRestAtr(), zone
.getSensors().size() > 0);
jzone.put(ZoneFormat.HAS_SUBZONES.getRestAtr(), zone
.getSubZones().size() > 0);
jzones.put(jzone);
}
}
JSONObject zoneHead = new JSONObject();
zoneHead.put(ZoneFormat.SUBZONE.getRestAtr(), jzones);
return new JsonRepresentation(zoneHead);
} catch (Exception e) {
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
@Get("xml")
public Representation toXML() {
try {
List<IZone> zones = JDOStorage.getInstance()
.getAll(ZoneAdmin.class);
Reference ref = getRequest().getResourceRef();
final String baseURL = ref.getHierarchicalPart();
DomRepresentation xml = new DomRepresentation(MediaType.TEXT_XML);
Document d = xml.getDocument();
Element root = d.createElement(ZoneFormat.ZONE.getRestAtr());
d.appendChild(root);
for (IZone zone : zones) {
if (zone.getParentZone() == null) {
Element subzone = d.createElement(ZoneFormat.SUBZONE
.getRestAtr());
subzone.setAttribute(ZoneFormat.NAME.getRestAtr(),
zone.getName());
subzone.setAttribute(ZoneFormat.URI.getRestAtr(),
String.format("%s/%s", baseURL, zone.getKey()));
subzone.setAttribute(ZoneFormat.HAS_SENSORS.getRestAtr(),
"" + (zone.getSensors().size() > 0));
subzone.setAttribute(ZoneFormat.HAS_SUBZONES.getRestAtr(),
"" + (zone.getSubZones().size() > 0));
root.appendChild(subzone);
}
}
return xml;
} catch (Exception e) {
e.printStackTrace();
setStatus(Status.SERVER_ERROR_INTERNAL);
return null;
}
}
}
@@ -1,43 +0,0 @@
package fr.eurecom.restlet.resources.gae;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.ext.wadl.ApplicationInfo;
import org.restlet.ext.wadl.DocumentationInfo;
import org.restlet.ext.wadl.WadlApplication;
import org.restlet.resource.Directory;
import org.restlet.routing.Router;
import fr.eurecom.restlet.resources.common.ContactResource;
import fr.eurecom.restlet.resources.common.ContactsResource;
import fr.eurecom.restlet.resources.common.ContactsSubResource;
public class Dispatcher extends WadlApplication {
@Override
public Restlet createInboundRoot() {
Router router = new Router(getContext());
router.attachDefault(new Directory(getContext(), "war:///"));
// web xml mapping = /*
// router.attach("/contacts", ContactsResource.class);
// router.attach("/contacts/{id}", ContactResource.class);
// web xml mapping = /contacts/*
router.attach("", ContactsResource.class);
router.attach("/subscribe", ContactsSubResource.class);
router.attach("/{id}", ContactResource.class);
return router;
}
@Override
public ApplicationInfo getApplicationInfo(Request request, Response response) {
ApplicationInfo info = super.getApplicationInfo(request, response);
DocumentationInfo docInfo = new DocumentationInfo(
"emulator-box-services application documentation");
docInfo.setTitle("Emulator Box Services application infos.");
info.setDocumentation(docInfo);
return info;
}
}
@@ -1,48 +0,0 @@
package fr.eurecom.restlet.resources.gae;
import java.util.logging.Logger;
import org.restlet.Request;
import org.restlet.Response;
import org.restlet.Restlet;
import org.restlet.ext.wadl.ApplicationInfo;
import org.restlet.ext.wadl.DocumentationInfo;
import org.restlet.ext.wadl.WadlApplication;
import org.restlet.resource.Directory;
import org.restlet.routing.Router;
import fr.eurecom.restlet.resources.common.SensorPost;
import fr.eurecom.restlet.resources.common.ZonesResource;
import fr.eurecom.restlet.resources.common.ZoneResource;
import fr.eurecom.restlet.resources.common.SensorInResource;
public class DispatcherSenml extends WadlApplication {
private static final Logger log = Logger.getLogger("DispatcherSenml");
@Override
public Restlet createInboundRoot() {
log.info("SenML dispatcher attaches resources");
Router router = new Router(getContext());
router.attachDefault(new Directory(getContext(), "war:///"));
// web xml mapping = /*
router.attach("/zones", ZonesResource.class);
router.attach("/zones/{id}", ZoneResource.class);
router.attach("/sensorsin", SensorInResource.class);
router.attach("/posttest", SensorPost.class);
return router;
}
@Override
public ApplicationInfo getApplicationInfo(Request request, Response response) {
ApplicationInfo info = super.getApplicationInfo(request, response);
DocumentationInfo docInfo = new DocumentationInfo(
"emulator-box-services application documentation");
docInfo.setTitle("Emulator Box Services application infos.");
info.setDocumentation(docInfo);
return info;
}
}
@@ -1,24 +0,0 @@
package fr.eurecom.restlet.resources.gae;
import java.io.IOException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* This class serves for test only. Can be deleted.
* @author ouest
*
*/
@SuppressWarnings("serial")
public class ResourcesServletGAE extends HttpServlet {
@Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
@@ -1,18 +0,0 @@
package fr.eurecom.restlet.resources.persistence;
import javax.jdo.JDOHelper;
import javax.jdo.PersistenceManagerFactory;
public final class PMF {
private static final PersistenceManagerFactory pmfInstance = JDOHelper
.getPersistenceManagerFactory("transactions-optional");
private PMF() {
}
public static PersistenceManagerFactory get() {
return pmfInstance;
}
}
// PersistenceManager pm = PMF.get().getPersistenceManager();
@@ -1,252 +0,0 @@
package fr.eurecom.restlet.resources.persistence;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import fr.eurecom.restlet.resources.common.Contact;
import fr.eurecom.restlet.resources.common.ContactBaseResource.MEMBERS;
/**
* This class is a naive implementation of contact's datastore, it should be
* replaced by a NOSQL JDO storage.
*/
// TODO: Replace this class by NOSQL JDO implementation.
public class Storage {
/**
* Array of contacts. Restricted to 50 contacts.
*/
private final Contact[] backend = new Contact[50];
/**
* Storage instance.
*/
private static Storage instance = null;
private static final String TEMPLATE_SORT = "%s-%s";
/**
* Constructs a storage. Initialize a bunch of contacts.
*/
private Storage() {
backend[0] = new Contact(0, "Bonnie", "Parker", "bonnie@gangsters.org",
"+1-555-329-4589");
backend[1] = new Contact(1, "Clyde", "Barrow", "clyde@gangsters.org",
"+1-555-329-4589");
backend[2] = new Contact(2, "John", "Dillinger", "john@gangsters.org",
"+1-555-355-3232");
backend[3] = new Contact(3, "Herman", "Lamm", "herman@gangsters.org",
"+1-555-258-2365");
backend[4] = new Contact(4, "Willie", "Sutton", "will@gangsters.org",
"+1-555-258-2365");
for (int i = 5; i < 50; i++) {
backend[i] = null;
}
}
/**
* Retrieve the singleton storage.
*
* @return a Storage instance.
*/
public static Storage getInstance() {
if (instance == null) {
instance = new Storage();
}
return instance;
}
/**
* Retrieve a list of sorted contacts, starting with the given offset.
*
* @param sort
* - Sort parameter.
* @param minLimit
* - reserved for a future usage
* @param maxLimit
* - reserved for a future usage
* @return a sorted list of the contacts.
*/
@SuppressWarnings("unchecked")
public List<Contact> getContacts(MEMBERS sort, int minLimit, int maxLimit) {
switch (sort) {
case ID:
return getSortedById();
case FIRSTNAME:
return getSortedByFirstName();
case LASTNAME:
return getSortedByLastName();
case PHONE:
return getSortedByPhone();
case MAIL:
return getSortedByEmail();
}
return Collections.EMPTY_LIST;
}
/**
* Save a contact, the Contact's id must be comprise between 0 and 49.
*
* @param contact
* to save.
* @return true if correctly saved, false otherwise.
*/
public boolean saveContact(Contact contact) {
if (checkIndex(contact.getId())) {
backend[contact.getId()] = contact;
return true;
}
return false;
}
/**
* Delete a contact. Same as {@link #removeContact(int)}
* {@code
* removeContact(conctact.getId();
* }
*
* @param contact
* to delete.
* @return true if deleted, false otherwise.
*/
public boolean removeContact(Contact contact) {
return removeContact(contact.getId());
}
/**
* Delete a contact
*
* @param identifier
* - Contact's identifier
* @return true if deleted, false otherwise
* @see Storage.removeContact(Contact)
*/
public boolean removeContact(int identifier) {
if (checkIndex(identifier)) {
backend[identifier] = null;
return true;
}
return false;
}
/**
* Retrieve a contact from an identifier.
*
* @param identifier
* - Contact's identifier
* @return Contact.
*/
public Contact getContact(int identifier) {
if (checkIndex(identifier)) {
return backend[identifier];
}
return null;
}
private boolean checkIndex(int index) {
return index > -1 && index < 50;
}
/**
* Sort contacts by email field.
*
* @return a sorted list of contacts.
*/
private List<Contact> getSortedByEmail() {
Map<String, Contact> sorted = new TreeMap<String, Contact>(
String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < 50; i++) {
if (backend[i] != null) {
sorted.put(unicKey(backend[i].getMail(), i), backend[i]);
}
}
return new ArrayList<Contact>(sorted.values());
}
/**
* Sort contacts by phone number
*
* @return a sorted list of contacts.
*/
private List<Contact> getSortedByPhone() {
Map<String, Contact> sorted = new TreeMap<String, Contact>(
String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < 50; i++) {
if (backend[i] != null) {
sorted.put(unicKey(toNumeric(backend[i].getPhone()), i),
backend[i]);
}
}
return new ArrayList<Contact>(sorted.values());
}
/**
* Sort contacts by last name
*
* @return a sorted list of contacts.
*/
private List<Contact> getSortedByLastName() {
Map<String, Contact> sorted = new TreeMap<String, Contact>(
String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < 50; i++) {
if (backend[i] != null) {
sorted.put(unicKey(backend[i].getLastName(), i), backend[i]);
}
}
return new ArrayList<Contact>(sorted.values());
}
/**
* Sort contacts by first name
*
* @return a sorted list of contacts.
*/
private List<Contact> getSortedByFirstName() {
Map<String, Contact> sorted = new TreeMap<String, Contact>(
String.CASE_INSENSITIVE_ORDER);
for (int i = 0; i < 50; i++) {
if (backend[i] != null) {
sorted.put(unicKey(backend[i].getFirstName(), i), backend[i]);
}
}
return new ArrayList<Contact>(sorted.values());
}
/**
* Sort contacts by identifier.
*
* @return a sorted list of contacts.
*/
private List<Contact> getSortedById() {
return Arrays.asList(backend);
}
private static String toNumeric(String phone) {
char[] chars = phone.toCharArray();
StringBuilder builder = new StringBuilder();
for (char c : chars) {
if (Character.isDigit(c)) {
builder.append(c);
}
}
return builder.toString();
}
/**
* Format a unic key (necessary when at least 2 contacts have a same
* property value like firstname/lastname..)
*
* @param key
* @param id
* @return
*/
private static String unicKey(String key, int id) {
return String.format(TEMPLATE_SORT, key, id);
}
}
@@ -1,36 +0,0 @@
package fr.eurecom.senml.entity;
import javax.jdo.annotations.IdGeneratorStrategy;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
@PersistenceCapable
public class ContactTest {
@PrimaryKey
@Persistent(valueStrategy = IdGeneratorStrategy.IDENTITY)
private Key key;
@Persistent
private String firstName;
@Persistent
private String lastName;
@Persistent
private String email;
public ContactTest(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public String getirstName() {return firstName;}
public String getLastName() {return lastName;}
public String getEmail() {return email;}
public Key getKey() {return key;}
}
@@ -1,9 +0,0 @@
package fr.eurecom.senml.entity;
public interface IPostVal {
public final static String BASE_NAME = "bn";
public final static String STATUS = "status";
}
@@ -1,37 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.List;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
public interface ISensor {
public final static String BASE_NAME = "bn";
public final static String BASE_TIME = "bt";
public final static String BASE_UNIT = "bu";
public final static String VERSION = "ver";
public final static String MEASUREMENT = "e";
public String getUUID();
public IZone getZone();
public String getTitle();
public List <Measure> getMeasures();
// public List<String> getMeasuresKey();
// public List<String> getMeasuresPrint();
public JSONObject toJSONSenML();
public Document toXMLSenML();
public Node toXMLSenML(Document rootDocument);
public String getBaseUnit();
public String zoneType();
}
@@ -1,34 +0,0 @@
package fr.eurecom.senml.entity;
import fr.eurecom.senml.entity.Measure.ParamTypeValue;
public interface ISensorAdmin extends ISensor {
public boolean linkZone(IZone zone);
public boolean linkZone(String zoneKey);
public void unlinkZone();
public Measure addMeasure(String measureName,
Units measureUnit,
ParamTypeValue measureTypeValue,
String measureValue, long timeMeasure, String type);
public void deleteMeasure(String measureKey);
public void deleteMeasure(Measure measure);
public void setTitle(String title);
// void tag(Tag tag);
// void untag(Tag tag);
public void destroy();
public Measure addMeasure(String measureName, Units measureUnit,
ParamTypeValue measureTypeValue, String measureValue,
long timeMeasure, String type, String sum);
}
@@ -1,23 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.List;
public interface IZone extends Comparable<IZone> {
// public boolean hasSensors();
// public boolean hasSubZones();
public List<IZone> getSubZones();
public List<ISensor> getSensors();
public String getName();
public String getKey();
public IZone getParentZone();
String getType();
}
@@ -1,17 +0,0 @@
package fr.eurecom.senml.entity;
public interface IZoneAdmin extends IZone {
public boolean linkParentZone(String parentZoneKey);
public boolean linkParentZone(IZone parentZone);
public void unlinkParentZone();
// public boolean addSensor(String sensorKey);
// public boolean removeSensor(String sensorKey);
public void destroy();
}
@@ -1,301 +0,0 @@
package fr.eurecom.senml.entity;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.UUID;
import java.util.logging.Logger;
import java.util.Map;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import fr.eurecom.senml.persistence.JDOStorage;
/**
* Immutable object. Represents the SenML Measurement entry.
*
* @author dalmassi
*
*/
@PersistenceCapable(detachable = "true")
public class Measure {
public enum ParamTypeValue {
BOOL("bv"), FLOAT("v"), STRING("sv"), SUM("s");
private String encoded;
private final static Map<String, ParamTypeValue> mTypeValue = new HashMap<String, ParamTypeValue>();
ParamTypeValue(String encoded) {
this.encoded = encoded;
}
public String getSenML() {
return encoded;
}
public static ParamTypeValue getParamTypeValue(String senmlEncoded) {
if (mTypeValue == null) {
initMapValue();
}
return mTypeValue.get(senmlEncoded);
}
private static synchronized void initMapValue() {
if (mTypeValue.size() > 0) {
return;
}
for (ParamTypeValue v : values()) {
mTypeValue.put(v.encoded, v);
}
}
};
@NotPersistent
private static final DateFormat df = new SimpleDateFormat(
"yyyy.MM.dd G 'at' HH:mm:ss z");
@NotPersistent
private static final Logger log = Logger
.getLogger("sensors.entity.Measure");
@NotPersistent
public static final String PARAM_UNIT = "u";
@NotPersistent
public static final String PARAM_NAME = "n";
@NotPersistent
public static final String PARAM_TIME = "t";
@NotPersistent
public static final String PARAM_VALUE = "v";
@NotPersistent
public static final String PARAM_STRING_VALUE = "sv";
@NotPersistent
public static final String PARAM_BOOLEAN_VALUE = "bv";
@NotPersistent
public static final String PARAM_SUM_VALUE = "s";
@NotPersistent
public static final String PARAM_UPDATE_TIME = "ut";
@NotPersistent
public static final String PARAM_TYPE = "type";
@PrimaryKey
@Persistent
Key key;
@Persistent
private String name;
@Persistent
private String unitCS;
@Persistent
private String unitPrint;
@Persistent
private String unitKindOfQty;
@Persistent
private String value;
@Persistent
private String paramTypeValueEncoded;
private long time;
@Persistent
private String sensorKey;
private String baseunitCS;
private String baseunitPrint;
private String baseunitKindOfQty;
private String type;
private String sum;
public Measure(String sensorKey, String name, Units unit,
ParamTypeValue typeValue, String value, long time, String type) {
this.sensorKey = sensorKey;
this.name = name == null || name.isEmpty() ? generateName() : name;
this.unitCS = unit == null ? null : unit.getCS();
this.unitPrint = unit == null ? null : unit.getPrint();
this.unitKindOfQty = unit == null ? null : unit.getKindofQty();
this.paramTypeValueEncoded = typeValue.getSenML();
this.value = value;
this.time = time;
this.key = KeyFactory.createKey(Measure.class.getSimpleName(),
sensorKey + name);
this.type = type;
}
public Measure(String sensorKey, String name, Units unit,
ParamTypeValue typeValue, String value, long time, String type, String sum) {
this.sensorKey = sensorKey;
this.name = name == null || name.isEmpty() ? generateName() : name;
this.unitCS = unit == null ? null : unit.getCS();
this.unitPrint = unit == null ? null : unit.getPrint();
this.unitKindOfQty = unit == null ? null : unit.getKindofQty();
this.paramTypeValueEncoded = typeValue.getSenML();
this.value = value;
this.time = time;
this.sum = sum;
this.key = KeyFactory.createKey(Measure.class.getSimpleName(),
sensorKey + name);
this.type = type;
}
public void destroy() {
JDOStorage.getInstance().delete(this);
}
public String getKey() {
return key == null ? null : KeyFactory.keyToString(key);
}
public String getType() {
return type;
}
public JSONObject toJSONSenML() {
try {
JSONObject entrySenML = new JSONObject();
if (name != null) {
entrySenML.put(PARAM_NAME, name);
}
if (sum != null) {
entrySenML.put(PARAM_SUM_VALUE, sum);
}
entrySenML.put(PARAM_TYPE, type);
entrySenML.put(PARAM_TIME, time);
if (this.unitPrint != null) {
entrySenML.put(PARAM_UNIT, unitCS);
}
if (paramTypeValueEncoded != null) {
entrySenML.put(paramTypeValueEncoded, value);
}
return entrySenML;
} catch (Exception e) {
e.printStackTrace();
log.warning("Error Encoding a measure");
return null;
}
}
public Node toXMLSenML(Document d) {
Element measure = d.createElement("e");
measure.setAttribute(PARAM_NAME, name);
measure.setAttribute(PARAM_TYPE, type);
measure.setAttribute(PARAM_TIME, "" + time);
if (this.unitPrint != null) {
measure.setAttribute(PARAM_UNIT, unitCS);
}
if (this.sum != null) {
measure.setAttribute(PARAM_SUM_VALUE, sum);
}
if (paramTypeValueEncoded != null) {
measure.setAttribute(paramTypeValueEncoded, value);
}
return measure;
}
public String toString() {
StringBuilder builder = new StringBuilder();
if (this.unitCS != null) {
builder.append("key[" + getKey()).append("] name[" + name)
.append("] unitCS[" + unitCS)
.append("] unitPrint[" + unitPrint)
.append(this.sum == null ? "" : "] sum[" + sum)
.append("] unitKindOfQty[" + unitKindOfQty)
.append("] paramTypeEncoded[" + paramTypeValueEncoded)
.append("] value[" + value).append("] time[" + time)
.append("] sensorKey[" + sensorKey).append("]");
} else {
// Check if we have to initialize the base unit
baseUnitInit();
builder.append("key[" + getKey())
.append("] name[" + name)
.append("] unitCS (base unit) [" + baseunitCS)
.append("] unitPrint (base unit) [" + baseunitPrint)
.append(this.sum == null ? "" : "] sum[" + sum)
.append("] unitKindOfQty (base unit) [" + baseunitKindOfQty)
.append("] paramTypeEncoded[" + paramTypeValueEncoded)
.append("] value[" + value).append("] time[" + time)
.append("] sensorKey[" + sensorKey).append("]");
}
return builder.toString();
}
public String toPrettyString() {
StringBuilder builder = new StringBuilder();
if (this.unitCS != null) {
builder.append(name).append(": ").append("(kind: ")
.append(unitKindOfQty).append(") ").append(value)
.append(this.sum == null ? "" : " sum: " + sum)
.append(" ").append(unitPrint).append(" @ ")
.append(formatDate(time));
} else {
// Check if we have to initialize the base unit
baseUnitInit();
builder.append(name).append(": ").append("(kind (baseunit): ")
.append(baseunitKindOfQty).append(") ").append(value)
.append(" ").append(baseunitPrint).append("(baseunit) @ ")
.append(formatDate(time));
}
return builder.toString();
}
private void baseUnitInit() {
System.out.println("unit is null, parent sensor is " + sensorKey);
// Retrieve info about base unit from the parent sensor
Sensor parent = JDOStorage.getInstance().getById(sensorKey,
Sensor.class);
System.out.println("sensor is " + parent.getTitle());
String bu = parent.getBaseUnit();
System.out.println("sensor bu is " + bu);
Units baseUnits = Units.getUnit(bu);
this.baseunitCS = baseUnits.getCS();
this.baseunitKindOfQty = baseUnits.getKindofQty();
this.baseunitPrint = baseUnits.getPrint();
System.out.println("base unit is: " + this.baseunitCS);
}
private String formatDate(long ms) {
if (ms == 0)
return "now";
if (ms < 0)
return ("now - " + ms);
return df.format(new Date(ms));
}
public String getSensorKey() {
return sensorKey;
}
private String generateName() {
return UUID.randomUUID().toString();
}
}
@@ -1,21 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.UUID;
import javax.jdo.annotations.Persistent;
import fr.eurecom.senml.persistence.JDOStorage;
public class PostValAdmin implements IPostVal {
@Persistent
boolean active = true;
public PostValType addPost(String name, String val, long timeMeasure) {
PostValType m = new PostValType(UUID.randomUUID().toString(), name, val, timeMeasure);
JDOStorage.getInstance().write(m);
//JDOStorage.getInstance().deleteAll(PostValType.class);
return m;
//return null;
}
}
@@ -1,173 +0,0 @@
package fr.eurecom.senml.entity;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.UUID;
import java.util.logging.Logger;
import java.util.Map;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import fr.eurecom.senml.persistence.JDOStorage;
/**
* Immutable object. Represents the SenML Measurement entry.
*
*
*/
@PersistenceCapable(detachable="true")
public class PostValType {
public enum ParamTypeValue {
STR("sv");
private String encoded;
private final static Map<String, ParamTypeValue> mTypeValue = new HashMap<String, ParamTypeValue>();
ParamTypeValue(String encoded) {
this.encoded = encoded;
}
public String getSenML() {
return encoded;
}
public static ParamTypeValue getParamTypeValue(String senmlEncoded) {
if (mTypeValue == null) {
initMapValue();
}
return mTypeValue.get(senmlEncoded);
}
private static synchronized void initMapValue() {
if (mTypeValue.size() > 0) {
return;
}
for (ParamTypeValue v : values()) {
mTypeValue.put(v.encoded, v);
}
}
};
@NotPersistent
private static final DateFormat df = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
@NotPersistent
private static final Logger log = Logger
.getLogger("sensors.entity.PostValType");
@NotPersistent
public static final String PARAM_STRING_VALUE = "sv";
@NotPersistent
public static final String PARAM_NAME = "n";
@PrimaryKey
@Persistent
Key key;
@Persistent
private String name;
@Persistent
private String value;
@Persistent
private long time;
public String getName() {
return name;
}
public String getValue() {
return String.valueOf(value);
}
public String getTime() {
return formatDate(time);
}
public PostValType(String sensorKey, String name,
String val, long time) {
this.name = name == null || name.isEmpty() ? generateName() : name;
this.value = val;
this.time = time;
this.key = KeyFactory.createKey(PostValType.class.getSimpleName(), sensorKey + name +"" + time);
}
public void destroy() {
JDOStorage.getInstance().delete(this);
}
public String getKey() {
return key == null ? null : KeyFactory.keyToString(key);
}
public JSONObject toJSONSenML() {
try {
JSONObject entrySenML = new JSONObject();
if (name != null) {
entrySenML.put(PARAM_NAME, name);
}
entrySenML.put(PARAM_STRING_VALUE, value);
return entrySenML;
} catch (Exception e) {
e.printStackTrace();
log.warning("Error Encoding a measure");
return null;
}
}
public Node toXMLSenML(Document d) {
Element measure = d.createElement("e");
measure.setAttribute(PARAM_NAME, name);
measure.setAttribute(PARAM_STRING_VALUE, String.valueOf(value));
return measure;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("key[" + getKey())
.append("] name[" + name)
.append("] value[" + value)
.append("] time[" + formatDate(time))
.append("]");
return builder.toString();
}
public String toPrettyString() {
StringBuilder builder = new StringBuilder();
builder.append(name)
.append(": ")
.append(") ")
.append(value)
.append(" @ ")
.append(formatDate(time));
return builder.toString();
}
private String formatDate(long ms) {
if (ms == 0) return "now";
if (ms < 0) return ("now - " + ms);
return df.format(new Date(ms));
}
private String generateName() {
return UUID.randomUUID().toString();
}
}
@@ -1,188 +0,0 @@
package fr.eurecom.senml.entity;
import java.sql.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.UUID;
import java.util.logging.Logger;
import java.util.Map;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import fr.eurecom.senml.persistence.JDOStorage;
/**
* Immutable object. Represents the registered device.
*/
@PersistenceCapable(detachable="true")
public class RegisteredDeviceType {
public enum ParamTypeValue {
STR("sv");
private String encoded;
private final static Map<String, ParamTypeValue> mTypeValue = new HashMap<String, ParamTypeValue>();
ParamTypeValue(String encoded) {
this.encoded = encoded;
}
public String getSenML() {
return encoded;
}
public static ParamTypeValue getParamTypeValue(String senmlEncoded) {
if (mTypeValue == null) {
initMapValue();
}
return mTypeValue.get(senmlEncoded);
}
private static synchronized void initMapValue() {
if (mTypeValue.size() > 0) {
return;
}
for (ParamTypeValue v : values()) {
mTypeValue.put(v.encoded, v);
}
}
};
@NotPersistent
private static final DateFormat df = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss z");
@NotPersistent
private static final Logger log = Logger
.getLogger("sensors.entity.RegisteredDeviceType");
@NotPersistent
public static final String PARAM_STRING_VALUE = "sv";
@NotPersistent
public static final String PARAM_NAME = "n";
@PrimaryKey
@Persistent
Key key;
@Persistent
private String deviceType;
@Persistent
private String registrationKey;
@Persistent
private long time;
private boolean isadmin = false;
public String getDeviceType() {
return deviceType;
}
public String getValue() {
return String.valueOf(registrationKey);
}
public String getTime() {
return formatDate(time);
}
public RegisteredDeviceType(String deviceKey, String deviceType,
String val, long time) {
this.deviceType =
deviceType == null || deviceType.isEmpty() ? generateName() : deviceType;
this.registrationKey = val;
this.time = time;
this.key = KeyFactory.createKey(
RegisteredDeviceType.class.getSimpleName(),
deviceKey + deviceType +"" + time);
}
public void destroy() {
JDOStorage.getInstance().delete(this);
}
public String getKey() {
return key == null ? null : KeyFactory.keyToString(key);
}
public String getDeviceRegistrationKey() {
return this.registrationKey;
}
public JSONObject toJSONSenML() {
try {
JSONObject entrySenML = new JSONObject();
if (deviceType != null) {
entrySenML.put(PARAM_NAME, deviceType);
}
entrySenML.put(PARAM_STRING_VALUE, registrationKey);
return entrySenML;
} catch (Exception e) {
e.printStackTrace();
log.warning("Error Encoding a measure");
return null;
}
}
public Node toXMLSenML(Document d) {
Element measure = d.createElement("e");
measure.setAttribute(PARAM_NAME, deviceType);
measure.setAttribute(PARAM_STRING_VALUE, String.valueOf(registrationKey));
return measure;
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("key[" + getKey())
.append("] name[" + deviceType)
.append("] value[" + registrationKey)
.append("] time[" + formatDate(time))
.append("]");
return builder.toString();
}
public String toPrettyString() {
StringBuilder builder = new StringBuilder();
builder.append(deviceType)
.append(": ")
.append(") ")
.append(registrationKey)
.append(" @ ")
.append(formatDate(time));
return builder.toString();
}
private String formatDate(long ms) {
if (ms == 0) return "now";
if (ms < 0) return ("now - " + ms);
return df.format(new Date(ms));
}
private String generateName() {
return UUID.randomUUID().toString();
}
public boolean isIsadmin() {
return isadmin;
}
public void setIsadmin(boolean isadmin) {
this.isadmin = isadmin;
}
}
@@ -1,202 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.Iterator;
import java.util.List;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.json.JSONObject;
import org.json.JSONArray;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import fr.eurecom.senml.persistence.JDOStorage;
import fr.eurecom.senml.persistence.JDOStorageZone;
@PersistenceCapable(detachable="true")
public class Sensor implements ISensor {
@Persistent
@PrimaryKey
protected String uuid;
@Persistent
protected String title = null;
@Persistent
protected String zoneKey = null;
@Persistent
protected String baseUnit = null;
@Persistent
protected String type = null;
// Not supported. GAE load only lazy objects (empty objects) and does not support joins.
// @Persistent(defaultFetchGroup="true")
// protected Set<Measure> measures;
protected Sensor(String uuid, String title, String zoneKey) {
this.uuid = uuid;
this.title = title.trim();
this.zoneKey = zoneKey;
}
public Sensor(String uuid, String title, String zoneKey, String baseUnit, String type) {
this.uuid = uuid;
this.title = title.trim();
this.zoneKey = zoneKey;
this.baseUnit = baseUnit;
this.type = type;
}
@Override
public String getUUID() {
return uuid;
}
@Override
public String zoneType() {
return type;
}
@Override
public String getTitle() {
return title;
}
@Override
public IZone getZone() {
if (zoneKey != null) {
return JDOStorage.getInstance().getById(zoneKey, ZoneAdmin.class);
}
return null;
}
@Override
public String getBaseUnit() {
return baseUnit;
}
@Override
public JSONObject toJSONSenML() {
JSONObject sensorSenML = new JSONObject();
try {
sensorSenML.put("bn", getBaseName());
sensorSenML.put("type", zoneType());
if (getBaseUnit() != null) {
sensorSenML.put("bu", getBaseUnit());
}
JSONArray mArray = new JSONArray();
for (Measure m : getMeasures()) {
mArray.put(m.toJSONSenML());
}
if (mArray.length() > 0) {
sensorSenML.put("e", mArray);
}
}
catch (Exception e) {
e.printStackTrace();
}
// System.out.println(sensorSenML.toString());
return sensorSenML;
}
@Override
public Document toXMLSenML() {
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document d = builder.newDocument();
d.appendChild(toXMLSenML(d));
return d;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public Element toXMLSenML(Document documentRoot) {
try {
Element senml = documentRoot.createElement("senml");
senml.setAttribute("bn", getBaseName());
senml.setAttribute("type", zoneType());
if (getBaseUnit() != null) {
senml.setAttribute("bu", getBaseUnit());
}
for (Measure m : getMeasures()) {
senml.appendChild(m.toXMLSenML(documentRoot));
}
return senml;
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Title : " + title);
builder.append("\"bn\" :").append(" (" + type).append(") \"uuid:" + uuid + "\" Measures ");
builder.append("\r\n");
for (Measure m : JDOStorageZone.getInstance().getMeasures(this)) {
builder.append("\t").append(m.toString());
builder.append("\r\n");
}
return builder.toString();
}
/* @Override
public List<String> getMeasuresPrint() {
List<String> mString = new ArrayList<String>();
for (String mKey : measuresKey) {
Measure m = JDOStorage.getInstance().getById(mKey, Measure.class);
mString.add(m.toPrettyString());
}
return mString;
}
*/
/* @Override
public List<String> getMeasuresKey() {
return new ArrayList<String>(measuresKey);
}
*/
@Override
public List<Measure> getMeasures() {
return JDOStorageZone.getInstance().getMeasures(this);
}
/* HACK: "Generic Sensor" when the sensor has been created receiving a senml file (sensorin resource).
else sensor has been entered by the jsp file the uuid is generated by this program.
this is a poor workaround to support both. in a future the jsp should disappears.
*/
private final String getBaseName() {
return uuid;
//return "Generic Sensor".equals(title) ? uuid : String.format("urn:%s:uuid:%s", title.toLowerCase(), uuid);
}
public static Sensor getByUUID(String uuid) {
List<Sensor> sensors = JDOStorage.getInstance().getAll(Sensor.class);
Iterator<Sensor> iter = sensors.iterator();
while (iter.hasNext()) {
Sensor current = iter.next();
if (current.getUUID().equals(uuid)) {
return current;
}
}
return null;
}
}
@@ -1,141 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.UUID;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import org.json.JSONException;
import fr.eurecom.pushing.GCMPushingServer;
import fr.eurecom.senml.entity.Measure.ParamTypeValue;
import fr.eurecom.senml.persistence.JDOStorage;
@PersistenceCapable
@Inheritance(customStrategy = "complete-table")
public class SensorAdmin extends Sensor implements ISensorAdmin {
@NotPersistent
private final static String ZONE_UPDATED = "ZoneUpdated";
@Persistent
boolean active = true;
public SensorAdmin(String title, IZone zone, String baseUnit, String typeSensor) {
super(UUID.randomUUID().toString(), title, zone != null ? zone.getKey()
: null, baseUnit, typeSensor);
JDOStorage.getInstance().write(this);
}
public SensorAdmin(String bn, String title, IZone zone) {
super(bn, title, zone != null ? zone.getKey() : null);
JDOStorage.getInstance().write(this);
}
@Override
public void setTitle(String title) {
this.title = title;
JDOStorage.getInstance().write(this);
}
@Override
public void destroy() {
try {
JDOStorage.getInstance().delete(getMeasures());
} catch (Exception e) {
e.printStackTrace();
}
JDOStorage.getInstance().delete(this);
}
@Override
public boolean linkZone(IZone zone) {
return zone == null ? false : linkZone(zone.getKey());
}
@Override
public boolean linkZone(String zoneKey) {
if (active && checkKey(zoneKey)) {
this.zoneKey = zoneKey;
JDOStorage.getInstance().write(this);
return active;
}
return false;
}
@Override
public void unlinkZone() {
if (zoneKey != null) {
this.zoneKey = null;
JDOStorage.getInstance().write(this);
}
}
@Override
public void deleteMeasure(String measureKey) {
if (measureKey != null) {
JDOStorage.getInstance()
.delete(JDOStorage.getInstance().getById(measureKey,
Measure.class));
}
fr.eurecom.restlet.resources.common.ContactBaseResource
.sendUpdateSubscribers(ZONE_UPDATED + getZone().getName());
}
@Override
public void deleteMeasure(Measure measure) {
JDOStorage.getInstance().delete(measure);
fr.eurecom.restlet.resources.common.ContactBaseResource
.sendUpdateSubscribers(ZONE_UPDATED + getZone().getName());
}
private boolean checkKey(String key) {
return key != null && !key.trim().isEmpty();
}
@Override
public Measure addMeasure(String measureName, Units measureUnit,
ParamTypeValue measureTypeValue, String measureValue,
long timeMeasure, String type) {
Measure m = new Measure(getUUID(), measureName, measureUnit,
measureTypeValue, measureValue, timeMeasure, type);
JDOStorage.getInstance().write(m);
// fr.eurecom.restlet.resources.common.ContactBaseResource.sendUpdateSubscribers(ZONE_UPDATED
// + getZone().getName());
GCMPushingServer GCM = GCMPushingServer.getInstance();
try {
GCM.sendNotification(ZONE_UPDATED + getZone().getName());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return m;
}
@Override
public Measure addMeasure(String measureName, Units measureUnit,
ParamTypeValue measureTypeValue, String measureValue,
long timeMeasure, String type, String sum) {
Measure m = new Measure(getUUID(), measureName, measureUnit,
measureTypeValue, measureValue, timeMeasure, type, sum);
JDOStorage.getInstance().write(m);
// fr.eurecom.restlet.resources.common.ContactBaseResource.sendUpdateSubscribers(ZONE_UPDATED
// + getZone().getName());
GCMPushingServer GCM = GCMPushingServer.getInstance();
try {
GCM.sendNotification(ZONE_UPDATED + getZone().getName());
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return m;
}
}
@@ -1,169 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.HashMap;
import java.util.List;
import java.util.logging.Logger;
import java.util.Map;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import org.json.JSONObject;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import fr.eurecom.senml.persistence.JDOStorage;
/**
* Represents the list of the monitored sensors, and the relative
* minimum and maximum values (allowed range)
*/
@PersistenceCapable(detachable = "true")
public class SensorCheckAlarm {
public enum ParamTypeValue {
BOOL("bv"), FLOAT("v"), STRING("sv");
private String encoded;
private final static Map<String, ParamTypeValue> mTypeValue = new HashMap<String, ParamTypeValue>();
ParamTypeValue(String encoded) {
this.encoded = encoded;
}
public String getSenML() {
return encoded;
}
public static ParamTypeValue getParamTypeValue(String senmlEncoded) {
if (mTypeValue == null) {
initMapValue();
}
return mTypeValue.get(senmlEncoded);
}
private static synchronized void initMapValue() {
if (mTypeValue.size() > 0) {
return;
}
for (ParamTypeValue v : values()) {
mTypeValue.put(v.encoded, v);
}
}
};
@NotPersistent
private static final Logger log = Logger
.getLogger("sensors.entity.SensorCheckAlarm");
@NotPersistent
public static final String PARAM_NAME = "n";
@NotPersistent
public static final String PARAM_VALUE = "v";
@NotPersistent
public static final String PARAM_STRING_VALUE = "sv";
@NotPersistent
public static final String PARAM_RT_ALLOWED = "rt-allowed";
@PrimaryKey
@Persistent
Key key;
@Persistent
private String sensorKey;
@Persistent
private String sensorName;
@Persistent
private String zoneKey;
// This should be an Object, and then through reflection setted to the correct type
@Persistent
private float minVal;
@Persistent
private float maxVal;
public SensorCheckAlarm(String sensorKey, float minVal, float maxVal) {
this.sensorKey = sensorKey;
this.key = KeyFactory.createKey(SensorCheckAlarm.class.getSimpleName(),
sensorKey + "sensoralarm");
this.setMinVal(minVal);
this.setMaxVal(maxVal);
}
public void destroy() {
JDOStorage.getInstance().delete(this);
}
public String getKey() {
return key == null ? null : KeyFactory.keyToString(key);
}
public JSONObject toJSONSenML() {
try {
JSONObject entrySenML = new JSONObject();
HashMap<String, Float> rtAllowed = new HashMap<String, Float>();
rtAllowed.put("min", getMinVal());
rtAllowed.put("max", getMaxVal());
entrySenML.put("key", getKey());
entrySenML.put("sensorkey", getSensorKey());
entrySenML.put("sensorName", getParentSensorName());
JSONObject rtAllowedJSON = new JSONObject(rtAllowed);
entrySenML.put(PARAM_RT_ALLOWED, rtAllowedJSON);
return entrySenML;
} catch (Exception e) {
e.printStackTrace();
log.warning("Error Encoding a measure");
return null;
}
}
public Node toXMLSenML(Document d) {
//TODO
return null;
}
public String getParentSensorName() {
SensorAdmin sensor = JDOStorage.getInstance().getById(sensorKey, SensorAdmin.class);
return sensor.getTitle();
}
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("key: " + this.sensorKey).append(", [" + getMinVal() + ", ")
.append(getMaxVal() + "]");
return builder.toString();
}
public String getSensorKey() {
return sensorKey;
}
public static List<SensorCheckAlarm> getAllMonitoredSensors() {
return JDOStorage.getInstance().getAll(SensorCheckAlarm.class);
}
public float getMinVal() {
return minVal;
}
public void setMinVal(float minVal) {
this.minVal = minVal;
}
public float getMaxVal() {
return maxVal;
}
public void setMaxVal(float maxVal) {
this.maxVal = maxVal;
}
}
@@ -1,115 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.HashMap;
import java.util.Map;
/**
* Units Definition from UCUM organization.
*
* @author dalmassi
*
*/
public enum Units {
ACIDITY("acidity", "pH", "pH"), // senml 10 Nota : ucum c/s = [pH]
ACCELERATION("acceleration", "m/s2", "m/s2"), // senml 10
AMPERE("electric current", "A", "A"),
AREA("Area", "m2", "m2"), // senml 10
BATTERY_LEVEL_PERCENT("Remaining percent battery", "%EL", "%EL"), // senml 10
BATTERY_LEVEL_SECOND("Remaining seconds battery", "EL", "EL"), // senml 10
BAR("pressure", "bar", "bar"),
BEATS_PER_MINUTE("beats/minute", "beet/m", "beet/m"), // senml 10 says beet/m, but ucum m = meter, min = minutes. This is confusing, also beet looks mispelled. Check next draft version.
BEATS("Cumulative beats", "beets", "beets"), // senml 10.
BECQUEREL("becquerel", "bq", "bq"),
BEL_SOUND_LEVEL("bel sound pressure level", "Bspl", "Bspl"), // senml 10
BIT_SECOND("bits per second", "bit/s", "bit/s"), // senml 10
CANDELA("luminous intensity", "cd","cd"),
COUNT("count", "count", "count"), // senml 10
COULOMB("electric charge", "C", "C"),
DAY("time", "d", "d"),
DEGREE_ANGLE("Plan Angle", "°", "deg"),
DEGREE_CELSIUS("temperature", "°C", "Cel"),
DEGREE_FAHRENHEIT("temperature","°F", "[degF]"),
FARAD("electric capacitance", "F", "F"),
GRAM("mass", "g", "g"),
GRAM_PER_LITER("gram per liter", "g/L", "g/L"),
GRAY("gray", "Gy", "Gy"), // senml 10
KATAL("katal", "kat", "kat"), // senml 10
KELVIN("temperature", "K", "K"),
HENRY("henry", "H", "H"), // senml 10
HERTZ("hertz", "Hz", "Hz"),
HUMIDITY_RELATIVE("humidity", "%RH", "%RH"), // senml 10
HOUR ("time", "h", "h"),
IRRIDIANCE("irridiance", "W/m2", "W/m2"), // senml 10
JOULE("joule", "J", "J"),
KILO_GRAM("mass", "kg", "kg"), // senml 10
KILO_WATT_HOUR("kilo watt per hour", "kWh", "kW/h"),
LATITUDE("WGS84-Latitude", "lat", "lat"), // draft senml 10
LITER("volume", "l", "l"),
LITER_SECOND("flow liters per seconds", "l/s", "l/s"), // senml 10 Nota ucum = L/s
LUMEN("luminous flux", "lm", "lm"),
LUMINANCE("luminance", "cd/m2", "cd/m2"), // senml 10
LONGITUDE("WGS84-Longitude", "lon", "lon"), // draft senml 10
LUX("illuminance", "lx", "lx"),
METER("length", "m", "m"),
MINUTE_ANGLE("Plan angle", "′", "′"),
MINUTE_TIME("time", "min", "min"),
MOLE("mole", "mol", "mol"), // senml 10
NEWTON("newton", "N", "N"), // senml 10
OHM("electric resistance", "Ω","Ohm"),
PASCAL("pressure", "Pa", "Pa"), // draft senml 10
PERCENT("percent", "%", "UCUM:%"), // ucum
RADIAN("plane angle", "rad", "rad"),
SECOND_ANGLE("Plan Angle", "″", "″"),
SECOND_TIME("time", "s", "s"),
SIEMENS("Siemens", "S", "S"), // senml 10
SIEVERT("Sievert", "Sv", "Sv"), // senml 10
STERADIAN("steradian", "sr", "sr"), // senml 10
SWITCH("switch", "switch", "%"), // senml 10 conflict with ucum percent
TONNE("mass", "t", "t"),
TESLA("magnetic flux density", "T", "T"),
VELOCITY("velocity", "m/s", "m/s"),
VOLT("electric potential", "V", "V"),
WATT("power", "W", "W"),
WEBER("wever", "Wb", "Wb"), // senml 10
YEAR("time", "a", "a");
private final String print;
private final String cs;
private final String kindOfQty;
private final static Map<String, Units> csMap = new HashMap<String, Units>();
Units(String kind, String print, String cs) {
this.print = print;
this.cs = cs;
this.kindOfQty = kind;
}
public String getCS() {
return cs;
}
public String getKindofQty() {
return kindOfQty;
}
public String getPrint() {
return print;
}
public static Units getUnit(String cs) {
if (csMap.size() == 0) {
initCsMap();
}
return csMap.get(cs);
}
private static synchronized void initCsMap() {
if (csMap.size() > 0 ) {
return;
}
for (Units u : values()) {
csMap.put(u.cs, u);
}
}
}
@@ -1,104 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import fr.eurecom.senml.persistence.JDOStorageZone;
@PersistenceCapable(detachable="true")
public class Zone implements IZone {
@NotPersistent
private static final Logger log = Logger.getLogger("Zone");
@Persistent
@PrimaryKey
protected Key key;
@Persistent
protected String name = "";
@Persistent
protected String parentKey = null;
@Persistent
protected String zoneType = "";
/**
* Instantiates a zone.
* @param key Zone key
* @param name Zone name
* @param parentKey Zone parent key. Can be null.
* @param type
*/
protected Zone(Key key, String name, String parentKey, String type) {
this.key = key;
this.name = name;
this.parentKey = parentKey;
this.zoneType = type;
}
@Override
public List<IZone> getSubZones() {
long before = System.currentTimeMillis();
List<IZone> childs = JDOStorageZone.getInstance().getSubZones(this);
long after = System.currentTimeMillis();
log.info("getSubzone " + name + " taken ms:" + (after - before));
return childs;
}
@Override
public List<ISensor> getSensors() {
long before = System.currentTimeMillis();
List<ISensor> sensors = JDOStorageZone.getInstance().getSensors(this);
long after = System.currentTimeMillis();
log.info("getSensors " + name + " taken ms:" + (after - before));
return sensors;
}
@Override
public String getName() {
return name;
}
@Override
public String getKey() {
return KeyFactory.keyToString(key);
}
@Override
public String getType() {
return zoneType;
}
@Override
public int compareTo(IZone o) {
return this.name.compareTo(o.getName());
}
@Override
public IZone getParentZone() {
Zone p = null;
if (parentKey != null) {
try {
p = JDOStorageZone.getInstance().getById(parentKey, this.getClass());
}
catch (Exception e) {
log.log(Level.WARNING, "Error retrieving parent zone", e);
}
}
return p;
}
}
@@ -1,86 +0,0 @@
package fr.eurecom.senml.entity;
import java.util.Collections;
import java.util.List;
import java.util.SortedSet;
import java.util.logging.Logger;
import javax.jdo.annotations.Index;
import javax.jdo.annotations.Inheritance;
import javax.jdo.annotations.NotPersistent;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import fr.eurecom.senml.persistence.JDOStorage;
import fr.eurecom.senml.persistence.JDOStorageZone;
/**
* Not thread-safe.
*
* @author dalmassi
*
*/
@PersistenceCapable
@Inheritance(customStrategy = "complete-table")
// @Index(name="index_parentKey", members={"parentKeyString"})
public class ZoneAdmin extends Zone implements IZoneAdmin {
@NotPersistent
private static final Logger log = Logger.getLogger("Zone");
@Persistent
private boolean isActive = true;
public ZoneAdmin(String name, ZoneAdmin parent, String type) {
super(KeyFactory.createKey(ZoneAdmin.class.getSimpleName(), name),
name, parent == null ? null : parent.getKey(), type);
JDOStorage.getInstance().write(this);
}
@Override
public void destroy() {
isActive = false;
parentKey = null;
List<ISensorAdmin> sensors = JDOStorageZone.getInstance().getSensors(
this);
for (ISensorAdmin s : sensors) {
s.destroy();
}
JDOStorage.getInstance().delete(this);
// TODO: Possible Race condition here. The delete is not effective when
// method JDOStorage delete returns.
log.fine("Removed from database " + this.name);
}
@Override
public boolean linkParentZone(String parentZoneKey) {
if (isActive && checkKey(parentZoneKey)) {
this.parentKey = parentZoneKey;
JDOStorage.getInstance().write(this);
return isActive;
}
return false;
}
@Override
public boolean linkParentZone(IZone parentZone) {
return parentZone == null ? false : linkParentZone(parentZone.getKey());
}
@Override
public void unlinkParentZone() {
if (parentKey != null) {
parentKey = null;
JDOStorage.getInstance().write(this);
}
}
private boolean checkKey(String key) {
return key != null && !key.trim().isEmpty();
}
}
@@ -1,285 +0,0 @@
package fr.eurecom.senml.jspcontroller;
import java.util.Calendar;
import java.util.List;
import java.util.TimeZone;
import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import fr.eurecom.pushing.GCMPushingServer;
import fr.eurecom.senml.entity.IPostVal;
import fr.eurecom.senml.entity.IZone;
import fr.eurecom.senml.entity.Measure;
import fr.eurecom.senml.entity.PostValAdmin;
import fr.eurecom.senml.entity.PostValType;
import fr.eurecom.senml.entity.Sensor;
import fr.eurecom.senml.entity.SensorAdmin;
import fr.eurecom.senml.entity.SensorCheckAlarm;
import fr.eurecom.senml.entity.Units;
import fr.eurecom.senml.entity.Zone;
import fr.eurecom.senml.entity.ZoneAdmin;
import fr.eurecom.senml.persistence.JDOStorage;
@Controller
@RequestMapping("/")
public class ControllerJsp {
@RequestMapping(value = "/zones", method = RequestMethod.GET)
// @ModelAttribute
public String listZone(ModelMap model) {
List<IZone> zones = JDOStorage.getInstance().getAll(ZoneAdmin.class);
model.addAttribute("zoneList", zones);
return "zonelist";
}
@RequestMapping(value="/addZone", method = RequestMethod.POST)
public ModelAndView addZone(HttpServletRequest request) {
String name = request.getParameter("nameZone");
String nameParent = request.getParameter("parentNameZone");
String type = request.getParameter("typeZone");
ZoneAdmin parent = nameParent.isEmpty()
? null
:JDOStorage.getInstance().getById(nameParent, ZoneAdmin.class);
new ZoneAdmin(name, parent, type);
return new ModelAndView("redirect:zones");
}
@RequestMapping(value = "deleteZone/{zoneKey}", method = RequestMethod.GET)
public ModelAndView deleteZone(@PathVariable String zoneKey, HttpServletRequest request) {
ZoneAdmin z = JDOStorage.getInstance().getById(zoneKey, ZoneAdmin.class);
if (z != null) {
z.destroy();
}
return new ModelAndView("redirect:../zones");
}
@RequestMapping(value="{zoneKey}/edit", method = RequestMethod.GET)
public String editZone(@PathVariable String zoneKey, HttpServletRequest request,
ModelMap model) {
ZoneAdmin z = JDOStorage.getInstance().getById(zoneKey, ZoneAdmin.class);
model.addAttribute("zone", z);
return "detailzone";
}
@RequestMapping(value="{zoneKey}/addsubZone", method = RequestMethod.POST)
public String addSubzone(@PathVariable String zoneKey, HttpServletRequest request, ModelMap model) {
String subZone = request.getParameter("nameSubZone");
String typeZone = request.getParameter("typeZone");
ZoneAdmin zone = JDOStorage.getInstance().getById(
zoneKey, ZoneAdmin.class);
new ZoneAdmin(subZone, zone, typeZone);
model.addAttribute("zone", zone);
return "redirect:edit";
}
@RequestMapping(value="{zoneKey}/addSensor", method = RequestMethod.POST)
public String addSensor(@PathVariable String zoneKey, HttpServletRequest request, ModelMap model) {
String title = request.getParameter("title");
String baseUnit = request.getParameter("baseunit");
String typeSensor = request.getParameter("typeSensor");
ZoneAdmin za = JDOStorage.getInstance().getById(zoneKey, ZoneAdmin.class);
new SensorAdmin(title, za, baseUnit, typeSensor);
model.addAttribute("zone", za);
return "redirect:edit";
}
@RequestMapping(value= "{zoneKey}/deleteSensor/{sensorKey}", method = RequestMethod.GET)
public ModelAndView deleteSensor(@PathVariable String zoneKey,
@PathVariable String sensorKey, HttpServletRequest request, ModelMap model) {
SensorAdmin s = JDOStorage.getInstance().getById(sensorKey, SensorAdmin.class);
s.destroy();
return new ModelAndView("redirect:../edit");
}
@RequestMapping(value="{zoneKey}/delete/{subZoneKey}", method = RequestMethod.GET)
@ModelAttribute
public ModelAndView deleteZone(@PathVariable String zoneKey, @PathVariable String subZoneKey,
HttpServletRequest request, ModelMap model) {
ZoneAdmin z = JDOStorage.getInstance().getById(subZoneKey, ZoneAdmin.class);
if (z != null) {
z.destroy();
}
return new ModelAndView("redirect:../edit");
}
@RequestMapping(value="{zoneKey}/addMeasure", method = RequestMethod.POST)
public String addMeasure(@PathVariable String zoneKey,
HttpServletRequest request, ModelMap model) {
// Mandatory fields
String sensorKey = request.getParameter("sensorKey");
String unit = request.getParameter("unit");
String name = request.getParameter("name");
String typeValue = request.getParameter("typeValue");
String value = request.getParameter("value");
long time = getSecondsSince1970UTC(request.getParameter("time"));
String strVersion = request.getParameter("version");
// Optional values
String sumValue = request.getParameter("sum");
String specMeasure = request.getParameter("specmeasure");
if (specMeasure != null) System.out.println("spec measure: " + specMeasure.toString());
String baseUnit = request.getParameter("bu");
String allowed = request.getParameter("allowed");
String rtallowed = request.getParameter("rtallowed");
String type = request.getParameter("measureType");
// If version is not setted, automatically is 1
if (strVersion == null) {
strVersion = "1.0";
}
float version = Float.parseFloat(strVersion);
SensorAdmin sa = JDOStorage.getInstance().getById(sensorKey, SensorAdmin.class);
if (sumValue == null) {
if ((specMeasure == null) || (specMeasure.equalsIgnoreCase("off"))) {
System.out.println("using baseUnit " + baseUnit);
sa.addMeasure(
name,
null,
Measure.ParamTypeValue.valueOf(typeValue.toUpperCase()),
value, time, type);
} else {
System.out.println("specMeasure is " + specMeasure);
sa.addMeasure(
name,
Units.getUnit(unit),
Measure.ParamTypeValue.valueOf(typeValue.toUpperCase()),
value, time, type);
}
} else {
if ((specMeasure == null) || (specMeasure.equalsIgnoreCase("off"))) {
System.out.println("using baseUnit " + baseUnit);
sa.addMeasure(
name,
null,
Measure.ParamTypeValue.valueOf(typeValue.toUpperCase()),
value, time, type, sumValue);
} else {
System.out.println("specMeasure is " + specMeasure);
sa.addMeasure(
name,
Units.getUnit(unit),
Measure.ParamTypeValue.valueOf(typeValue.toUpperCase()),
value, time, type, sumValue);
}
}
model.addAttribute("zone", sa.getZone());
// Eventually notify the registered devices
return "redirect:edit";
}
@RequestMapping(value="{zoneKey}/addAlertMonitor", method = RequestMethod.POST)
public String addAlertMonitor(@PathVariable String zoneKey,
HttpServletRequest request, ModelMap model) {
// Mandatory fields
String sensorKey = request.getParameter("sensorKey");
float rtallowedmin = Float.parseFloat(request.getParameter("rtallowedmin"));
float rtallowedmax = Float.parseFloat(request.getParameter("rtallowedmax"));
ZoneAdmin zone = JDOStorage.getInstance().getById(zoneKey, ZoneAdmin.class);
Sensor sensor = JDOStorage.getInstance().getById(sensorKey, SensorAdmin.class);
System.out.println("Adding monitoring for " + zone.getName() + ", " + sensor.getTitle());
SensorCheckAlarm checkAlarm = new SensorCheckAlarm(sensorKey, rtallowedmin, rtallowedmax);
JDOStorage.getInstance().write(checkAlarm);
return "redirect:edit";
}
// Admin website version - TODO, filter for sensors/zones
@RequestMapping(value="{zoneKey}/listAlertsMonitor", method = RequestMethod.GET)
public String listAlertsMonitor(@PathVariable String zoneKey,
HttpServletRequest request, ModelMap model) {
//TODO IF NEEDED!!!!
return "alarms";
}
// Admin website version for all the monitors
@RequestMapping(value="/listAllAlertsMonitorJSON", method = RequestMethod.GET)
public String listAllAlertsMonitorJSON(HttpServletRequest request, ModelMap model) {
return "allalarmsJSON";
}
// Admin mobile app version
@RequestMapping(value="{zoneKey}/listAlertsMonitorJSON", method = RequestMethod.GET)
public String listAlertsMonitorJSON(@PathVariable String zoneKey,
HttpServletRequest request, ModelMap model) {
return "alarmsJSON";
}
@RequestMapping(value="{zoneKey}/removemonitor", method = RequestMethod.GET)
public String removeMonitor(@PathVariable String zoneKey,
HttpServletRequest request, ModelMap model) {
String sensorKey = request.getParameter("key");
SensorCheckAlarm s = JDOStorage.getInstance().getById(sensorKey, SensorCheckAlarm.class);
JDOStorage.getInstance().delete(s);
return "alarms";
}
@RequestMapping(value="{zoneKey}/getmonitor", method = RequestMethod.GET)
public String getMonitor(@PathVariable String zoneKey,
HttpServletRequest request, ModelMap model) {
return "sensormonitorsjson";
}
/**
* To respect the senML directives, we need seconds since 1970 UTC
* @param parameter
* @return
*/
private long getSecondsSince1970UTC(String parameter) {
Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
System.out.println("Calendar is: " + calendar);
int secondsSinceEpoch = (int) TimeUnit.MILLISECONDS.toSeconds(calendar.getTimeInMillis());
System.out.println("seconds are " + secondsSinceEpoch);
return secondsSinceEpoch;
}
@RequestMapping(value= "{zoneKey}/deleteMeasure/{keyMeasure}",
method = RequestMethod.GET)
public ModelAndView deleteMeasure(@PathVariable String zoneKey, @PathVariable String keyMeasure,
HttpServletRequest request, ModelMap model) {
Measure m = JDOStorage.getInstance().getById(keyMeasure, Measure.class);
// m.destroy();
SensorAdmin sa = JDOStorage.getInstance().getById(m.getSensorKey(), SensorAdmin.class);
sa.deleteMeasure(m);
return new ModelAndView("redirect:../edit");
}
@RequestMapping(value = "/postvals", method = RequestMethod.GET)
public String listPostVals(ModelMap model) {
List<PostValType> zones = JDOStorage.getInstance().getAll(PostValType.class);
model.addAttribute("postvalsList", zones);
return "postvalslist";
}
//
// @RequestMapping(value = "/alertsadmin", method = Request.GET)
// public String listMonitoredSensors()
}
@@ -1,14 +0,0 @@
package fr.eurecom.senml.jspcontroller;
public class ZoneTypes {
// Refers to
// http://www.sensormeasurement.appspot.com/json/m3/featureOfInterest
private static String[] zoneTypes = {"City", "Environment", "Military",
"Tracking", "Health", "Place", "Building", "Transportation",
"BrainWave"};
public static String[] getZoneTypes() {
return zoneTypes;
}
}
@@ -1,167 +0,0 @@
package fr.eurecom.senml.persistence;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import fr.eurecom.restlet.resources.persistence.PMF;
import fr.eurecom.senml.entity.Zone;
import fr.eurecom.senml.entity.ZoneAdmin;
/**
* This class is a jdo wrapper. Implementing the persistence.
* @author dalmassi
*
*/
public class JDOStorage {
private static final JDOStorage instance = new JDOStorage();
protected JDOStorage() {
}
public static JDOStorage getInstance() {
return instance;
}
@SuppressWarnings("unchecked")
/**
* Wrapper JDO PM.getById, return a detached object.
* @param key The String key
* @param c Class of the object
* @return a typed object of the class.
*/
public <T> T getById(String key, Class<T> c) {
PersistenceManager pm = PMF.get().getPersistenceManager();
Object attached, detached = null;
try {
attached = pm.getObjectById(c, key);
detached = pm.detachCopy(attached);
}
finally {
close(pm);
}
return (T) detached;
}
public <T> void refresh(String key, Class<T> c) {
PersistenceManager pm = getPM();
try {
Object attached = pm.getObjectById(c, key);
pm.refresh(attached);
}
catch (Exception e) {
e.printStackTrace();
}
}
Query q = null;
@SuppressWarnings("unchecked")
public <T> List<T> getAll(Class<?> c) {
List<T> detached = Collections.EMPTY_LIST;
PersistenceManager pm = getPM();
Query q = pm.newQuery(c);
try {
List<T> results = (List<T>) q.execute();
if (!results.isEmpty()) {
detached = (List<T>) pm.detachCopyAll(results);
}
close(q);
close(pm);
}
catch (Exception e) {
e.printStackTrace();
}
return detached;
}
/**
* Save an object to dataStore.
* @param z object to save
* @return true if ok, false otherwise.
*/
public <T> boolean write(T z) {
PersistenceManager pm = getPM();
try {
pm.makePersistent(z);
// System.out.println("write jdo done! zone name|" + z.getName() + "| key |" + z.getKey() + "|");
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
finally {
close(pm);
}
}
public <T> void delete(T z) {
PersistenceManager pm = getPM();
try {
pm.deletePersistent(z);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
close(pm);
}
}
public <T> void delete(Collection<T> z) {
PersistenceManager pm = getPM();
try {
pm.deletePersistentAll(z);
}
catch (Exception e) {
e.printStackTrace();
}
finally {
close(pm);
}
}
public long deleteAll(Class<?> c) {
PersistenceManager pm = getPM();
long count = -1;
try {
Query q = pm.newQuery(c);
count = q.deletePersistentAll();
}
catch (Exception e) {
e.printStackTrace();
}
finally {
close(q);
close(pm);
}
return count;
}
protected PersistenceManager getPM() {
return PMF.get().getPersistenceManager();
}
protected void close(PersistenceManager pm) {
if (pm != null) {
pm.close();
}
}
protected void close(Query q) {
if (q != null) {
q.closeAll();
}
}
}
@@ -1,115 +0,0 @@
package fr.eurecom.senml.persistence;
import java.util.Collections;
import java.util.List;
import javax.jdo.PersistenceManager;
import javax.jdo.Query;
import fr.eurecom.senml.entity.Measure;
import fr.eurecom.senml.entity.Sensor;
import fr.eurecom.senml.entity.SensorAdmin;
import fr.eurecom.senml.entity.Zone;
import fr.eurecom.senml.entity.ZoneAdmin;
public class JDOStorageZone extends JDOStorage {
private static final JDOStorageZone instance = new JDOStorageZone();
private Query Q_SUBZONE_ADMIN = null;
private Query Q_SENSOR_ADMIN = null;
private Query Q_MEASURE_ADMIN = null;
private JDOStorageZone() {
super();
createQuerySubZone();
createQueryZoneSensors();
createQueryMeasures();
}
public static JDOStorageZone getInstance() {
return instance;
}
@SuppressWarnings("unchecked")
public <T> List<T> getSubZones(Zone zone) {
List<T> detached = Collections.EMPTY_LIST;
try {
List<T> results = (List<T>) Q_SUBZONE_ADMIN.execute(zone.getKey());
if (!results.isEmpty()) {
detached = (List<T>) Q_SUBZONE_ADMIN.getPersistenceManager().detachCopyAll(results);
}
}
catch (Exception e) {
e.printStackTrace();
}
return detached;
}
@SuppressWarnings("unchecked")
public <T> List<T> getSensors(Zone zone) {
List<T> detached = Collections.EMPTY_LIST;
try {
List<T> results = (List<T>) Q_SENSOR_ADMIN.execute(zone.getKey());
if (!results.isEmpty()) {
detached = (List<T>) Q_SENSOR_ADMIN.getPersistenceManager().detachCopyAll(results);
}
}
catch (Exception e) {
e.printStackTrace();
}
return detached;
}
@SuppressWarnings("unchecked")
public List<Measure> getMeasures(Sensor sensor) {
List<Measure> detached = Collections.EMPTY_LIST;
try {
List<Measure> results = (List<Measure>) Q_MEASURE_ADMIN.execute(sensor.getUUID());
if (!results.isEmpty()) {
detached = (List<Measure>) Q_MEASURE_ADMIN.getPersistenceManager().detachCopyAll(results);
}
}
catch (Exception e) {
e.printStackTrace();
}
return detached;
}
private void createQuerySubZone() {
if (Q_SUBZONE_ADMIN == null) {
Q_SUBZONE_ADMIN = getPM().newQuery(ZoneAdmin.class);
Q_SUBZONE_ADMIN.setFilter("parentKey == keyParentParam");
// Q_SUBZONE.declareParameters(Key.class.getName() + " keyParentParam");
Q_SUBZONE_ADMIN.declareParameters("String keyParentParam");
Q_SUBZONE_ADMIN.compile();
}
}
private void createQueryZoneSensors() {
if (Q_SENSOR_ADMIN == null) {
PersistenceManager pm = getPM();
// pm.getFetchPlan().setDetachmentOptions( FetchPlan.DETACH_LOAD_FIELDS | FetchPlan.DETACH_UNLOAD_FIELDS);
// pm.getFetchPlan().setMaxFetchDepth(4);
Q_SENSOR_ADMIN = pm.newQuery(SensorAdmin.class);
Q_SENSOR_ADMIN.setFilter("zoneKey == zoneKeyParam");
Q_SENSOR_ADMIN.declareParameters("String zoneKeyParam");
Q_SENSOR_ADMIN.compile();
}
}
private void createQueryMeasures() {
if (Q_MEASURE_ADMIN == null) {
PersistenceManager pm = getPM();
Q_MEASURE_ADMIN = pm.newQuery(Measure.class);
Q_MEASURE_ADMIN.setFilter("sensorKey == sensorKeyParam");
Q_MEASURE_ADMIN.declareParameters("String sensorKeyParam");
Q_MEASURE_ADMIN.compile();
Q_MEASURE_ADMIN.setIgnoreCache(true);
}
}
}
@@ -1,24 +0,0 @@
# A default log4j configuration for log4j users.
#
# To use this configuration, deploy it into your application's WEB-INF/classes
# directory. You are also encouraged to edit it as you like.
# Configure the console as our one appender
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{HH:mm:ss,SSS} %-5p [%c] - %m%n
# tighten logging on the DataNucleus Categories
log4j.category.DataNucleus.JDO=WARN, A1
log4j.category.DataNucleus.Persistence=WARN, A1
log4j.category.DataNucleus.Cache=WARN, A1
log4j.category.DataNucleus.MetaData=WARN, A1
log4j.category.DataNucleus.General=WARN, A1
log4j.category.DataNucleus.Utility=WARN, A1
log4j.category.DataNucleus.Transaction=WARN, A1
log4j.category.DataNucleus.Datastore=WARN, A1
log4j.category.DataNucleus.ClassLoading=WARN, A1
log4j.category.DataNucleus.Plugin=WARN, A1
log4j.category.DataNucleus.ValueGeneration=WARN, A1
log4j.category.DataNucleus.Enhancer=WARN, A1
log4j.category.DataNucleus.SchemaTool=WARN, A1
@@ -1,4 +0,0 @@
<!-- Indices written at Mon, 16 Sep 2013 09:25:09 UTC -->
<datastore-indexes/>
@@ -1,33 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<appengine-web-app xmlns="http://appengine.google.com/ns/1.0">
<application>wlboxv2</application>
<version>2</version>
<!--
Allows App Engine to send multiple requests to one instance in parallel:
-->
<threadsafe>true</threadsafe>
<!-- Configure java.util.logging -->
<system-properties>
<property name="java.util.logging.config.file" value="WEB-INF/logging.properties"/>
</system-properties>
<warmup-requests-enabled>true</warmup-requests-enabled>
<!--
HTTP Sessions are disabled by default. To enable HTTP sessions specify:
<sessions-enabled>true</sessions-enabled>
It's possible to reduce request latency by configuring your application to
asynchronously write HTTP session data to the datastore:
<async-session-persistence enabled="true" />
With this feature enabled, there is a very small chance your app will see
stale session data. For details, see
http://code.google.com/appengine/docs/java/config/appconfig.html#Enabling_Sessions
-->
</appengine-web-app>
@@ -1,10 +0,0 @@
<backends>
<backend name="back">
<class>B1</class>
<instances>1</instances>
<options>
<dynamic>false</dynamic>
<public>true</public>
</options>
</backend>
</backends>

Some files were not shown because too many files have changed in this diff Show More