فهرست منبع

Merge branch 'master' of https://bitbucket.org/ikflowdat/ftth

Daniel Libonati 7 سال پیش
والد
کامیت
93e4313152

+ 1 - 1
Dockerfile

@@ -40,4 +40,4 @@ CMD eval $(ssh-agent) ; ssh-add /opt/keys/bitbucket.id_rsa ; composer install --
  	cp app/config/hwioauthbundle/parameters.yml.docker app/config/hwioauthbundle/parameters.yml ;\
 	cp app/config/bundles/ik/device-bundle/parameters.yml.docker app/config/bundles/ik/device-bundle/parameters.yml ;\
     composer run-script post-install-cmd --no-interaction ;\
- 	cat app/config/hwioauthbundle/parameters.yml ; bin/console server:run 0.0.0.0 --env=dev
+ 	cat app/config/hwioauthbundle/parameters.yml ; bin/console server:run 0.0.0.0 

+ 5 - 0
app/config/routing.yml

@@ -69,3 +69,8 @@ audit:
     resource: "@AuditBundle/Controller/"
     type:     annotation
     prefix:   /
+
+ftth_profile_api:
+    resource: "@FTTHBundle/Controller/ProfileRESTController.php"
+    type:   rest
+    prefix:   /api

+ 2 - 0
app/config/security.yml

@@ -38,4 +38,6 @@ security:
     access_control:
         - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/admin/, role: ROLE_ADMIN }
+        - { path: ^/api/onus/onus/migrate.json, role: IS_AUTHENTICATED_ANONYMOUSLY }
+        - { path: ^/api/profiles/profiles/migrate.json, role: IS_AUTHENTICATED_ANONYMOUSLY }
         - { path: ^/api, role: ROLE_USER }

+ 197 - 0
src/FTTHBundle/Command/ImportDataONUCommand.php

@@ -0,0 +1,197 @@
+<?php
+
+namespace FTTHBundle\Command;
+
+use mysqli;
+use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Input\InputOption;
+use Symfony\Component\Console\Output\OutputInterface;
+
+class ImportDataONUCommand extends ContainerAwareCommand
+{
+    protected function configure()
+    {
+        $this
+            ->setName('import:data:onu')
+            ->setAliases(array("ik:data:onu"))
+            ->setDescription('Import data from flowdat 2')
+            ->setHelp('Import data from flowdat 2. Only from database.')
+            ->addOption('dbname', null, InputOption::VALUE_OPTIONAL, 'Database name. Default: flowdat2')
+            ->addOption('user', null, InputOption::VALUE_OPTIONAL, 'User name for database. Default: root')
+            ->addOption('password', null, InputOption::VALUE_OPTIONAL, 'Password form database.Default: "empty_value"')
+            ->addOption('host', null, InputOption::VALUE_OPTIONAL, 'Host of database. Default: localhost')
+            ->addOption('webservice', null, InputOption::VALUE_OPTIONAL, 'Webservice URL. Default: http://admin:adminpass@ftth:8000/api/onus/onus/migrate.json')
+            ->addOption('error', null, InputOption::VALUE_OPTIONAL, 'Show fullt error. Default: false')
+            ->addOption('id', null, InputOption::VALUE_OPTIONAL, 'Id to migrate.')
+            ->addOption('from', null, InputOption::VALUE_OPTIONAL, 'Id from.')
+            ->addOption('to', null, InputOption::VALUE_OPTIONAL, 'Id to.')
+            ->addOption('sentence', null, InputOption::VALUE_OPTIONAL, 'Show sql to migrate. Default: false');
+    }
+
+    protected function execute(InputInterface $input, OutputInterface $output)
+    {
+        try {
+            $this->output = $output;
+            $dbname = $input->getOption('dbname');
+            if (!$dbname) {
+                $dbname = 'flowdat2';
+            }
+            $user = $input->getOption('user');
+            if (!$user) {
+                $user = 'root';
+            }
+            $password = $input->getOption('password');
+            if (!$password) {
+                $password = '';
+            }
+            $host = $input->getOption('host');
+            if (!$host) {
+                $host = 'localhost';
+            }
+            $webservice = $input->getOption('webservice');
+            if (!$webservice) {
+                $webservice = 'http://admin:adminpass@ftth:8000/api/onus/onus/migrate.json';
+            }
+            $error = $input->getOption('error');
+            if (!$error) {
+                $error = false;
+            }
+            $id = $input->getOption('id');
+            if (!$id) {
+                $id = null;
+            }
+            $from = $input->getOption('from');
+            if (!$from) {
+                $from = null;
+            }
+            $to = $input->getOption('to');
+            if (!$to) {
+                $to = null;
+            }
+            $sentence = $input->getOption('sentence');
+            if (!$sentence) {
+                $sentence = false;
+            }
+            $conn = new mysqli($host, $user, $password, $dbname);
+            $sql = "select * from ONU";
+            $where = "";
+            if ($id) {
+                $where .= " id = " . $id;
+            }
+            if ($from) {
+                $where .= (strlen($where) > 0 ? " and " : "") . " id >= " . $from;
+            }
+            if ($to) {
+                $where .= (strlen($where) > 0 ? " and " : "") . " id <= " . $to;
+            }
+
+            if (strlen($where) > 0) {
+                $sql .= " where " . $where;
+            }
+
+            if ($sentence) {
+                echo $sql . "\n";
+            }
+            $rs = $conn->query($sql);
+
+            $log = $this->getContainer()->get('logger');
+
+            while ($d = $rs->fetch_assoc()) {
+                try {
+                    $extraData = '{importado: {' .
+                        'split_id:' . $d['split_id'] . ',' .
+                        'pon_port_id:' . $d['pon_port_id'] . ',' .
+                        'device_type_id:' . $d['device_type_id'] . ',' .
+                        'data:' . $d['data'] . ',' .
+                        'voip:' . $d['voip'] . ',' .
+                        'iptv:' . $d['iptv'] . ',' .
+                        'olt_port:' . $d['olt_port'] . ',' .
+                        'state:' . $d['state'] . ',' .
+                        'target_state:' . $d['target_state'] . ',' .
+                        'access_id:' . $d['access_id'] . ',' .
+                        'radius:' . $d['radius'] . ',' .
+                        'city_id:' . $d['city_id'] . ',' .
+                        'latitude:' . $d['latitude'] . ',' .
+                        'longitude:' . $d['longitude'] . ',' .
+                        'address:' . $d['address'] . ',' .
+                        'firmware_tr069:' . $d['firmware_tr069'] . ',' .
+                        'laser_id:' . $d['laser_id'] .
+                        '}}';
+                    $fields = array(
+                        'id' => $d['id'],
+                        'olt_id' => $d['olt_id'],
+                        'model' => $d['model_onu_id'],
+                        'profile' => $d['profile_id'],
+                        'ip' => $d['ip'],
+                        'mac' => $d['mac'],
+                        'serialNumber' => $d['serial_number'],
+                        'ponSerialNumber' => $d['pon_serial_number'],
+                        'clientId' => $d['client_id'],
+                        'created' => $d['created'],
+                        'updated' => $d['updated'],
+                        'tenancyId' => $d['tenancy_id'],
+                        'nap' => '',
+                        'workflow_id' => '',
+                        'current_state' => '',
+                        'administrativeState' => '',
+                        'transitionState' => '\"\"',
+                        'extraData' => json_encode($extraData),
+                        'position' => '',
+                        'location_id' => ''
+                    );
+                    $respuesta = $this->runPost($webservice, $fields);
+                    $json = json_decode($respuesta, true);
+                    if ($json) {
+                        if (isset($json['error']) && isset($json['error']['code']) && isset($json['error']['message'])) {
+                            echo "Error id = " . $d['id'] . " and pon_serial_number = '" . $d['pon_serial_number'] . "'\n";
+                            echo "\t\tCode: " . $json['error']['code'] . "\n";
+                            echo "\t\tMessage: " . $json['error']['message'] . "\n";
+                            if ($error) {
+                                $log->err($respuesta);
+                            }
+                        } else if ($d['pon_serial_number'] != $json['ponSerialNumber']) {
+                            echo "Error id from " . $d['id'] . " and pon_serial_number from '" . $d['pon_serial_number'] . "', id to " . $json['id'] . ". Validation gestion_id - external_id\n";
+                        }
+                    } else {
+                        echo "Error id = " . $d['id'] . " and pon_serial_number = '" . $d['pon_serial_number'] . "'\n";
+                        if ($error) {
+                            $log->err($respuesta);
+                        }
+                    }
+                } catch (\Throwable $e) {
+                    var_dump($e->getMessage());
+                    var_dump($e->getTraceAsString());
+                    echo "Error id = " . $d['id'] . " and pon_serial_number = '" . $d['pon_serial_number'] . "'\n";
+                    if ($error) {
+                        $log->err($e);
+                    }
+                }
+            }
+        } catch (\Throwable $e) {
+            echo("\nERROR CODE: " . $e->getCode() . "\nERROR MESSAGE: " . $e->getMessage() . "\n");
+            echo("\nTRACE: \n" . $e->getTraceAsString() . "\n\n");
+        }
+    }
+
+    /**
+     * Ejecuta una accion por post.
+     * @param string $url Contiene la url.
+     * @param array $fields Contiene los campos a enviar.
+     * @return mixed true on success or false on failure. However, if the CURLOPT_RETURNTRANSFER
+     * option is set, it will return the result on success, false on failure.
+     */
+    private function runPost($url, $fields)
+    {
+        $curl = curl_init();
+        curl_setopt_array($curl, array(
+            CURLOPT_RETURNTRANSFER => 1,
+            CURLOPT_URL => $url,
+            CURLOPT_POST => 1,
+            CURLOPT_POSTFIELDS => $fields
+        ));
+        $result = curl_exec($curl);
+        curl_close($curl);
+        return $result;
+    }
+}

+ 161 - 0
src/FTTHBundle/Command/ImportDataProfileCommand.php

@@ -0,0 +1,161 @@
+<?php
+
+namespace FTTHBundle\Command;
+
+use mysqli;
+use Symfony\Bundle\FrameworkBundle\Command\ContainerAwareCommand;
+use Symfony\Component\Console\Input\InputInterface;
+use Symfony\Component\Console\Input\InputOption;
+use Symfony\Component\Console\Output\OutputInterface;
+
+class ImportDataProfileCommand extends ContainerAwareCommand
+{
+    protected function configure()
+    {
+        $this
+            ->setName('import:data:profile')
+            ->setAliases(array("ik:data:profile"))
+            ->setDescription('Import data from flowdat 2')
+            ->setHelp('Import data from flowdat 2. Only from database.')
+            ->addOption('dbname', null, InputOption::VALUE_OPTIONAL, 'Database name. Default: flowdat2')
+            ->addOption('user', null, InputOption::VALUE_OPTIONAL, 'User name for database. Default: root')
+            ->addOption('password', null, InputOption::VALUE_OPTIONAL, 'Password form database.Default: "empty_value"')
+            ->addOption('host', null, InputOption::VALUE_OPTIONAL, 'Host of database. Default: localhost')
+            ->addOption('webservice', null, InputOption::VALUE_OPTIONAL, 'Webservice URL. Default: http://admin:adminpass@base:8000/api/profiles/profiles/migrate.json')
+            ->addOption('error', null, InputOption::VALUE_OPTIONAL, 'Show fullt error. Default: false')
+            ->addOption('id', null, InputOption::VALUE_OPTIONAL, 'Id to migrate.')
+            ->addOption('from', null, InputOption::VALUE_OPTIONAL, 'Id from.')
+            ->addOption('to', null, InputOption::VALUE_OPTIONAL, 'Id to.')
+            ->addOption('sentence', null, InputOption::VALUE_OPTIONAL, 'Show sql to migrate. Default: false');
+    }
+
+    protected function execute(InputInterface $input, OutputInterface $output)
+    {
+        try {
+            $this->output = $output;
+            $dbname = $input->getOption('dbname');
+            if (!$dbname) {
+                $dbname = 'flowdat2';
+            }
+            $user = $input->getOption('user');
+            if (!$user) {
+                $user = 'root';
+            }
+            $password = $input->getOption('password');
+            if (!$password) {
+                $password = '';
+            }
+            $host = $input->getOption('host');
+            if (!$host) {
+                $host = 'localhost';
+            }
+            $webservice = $input->getOption('webservice');
+            if (!$webservice) {
+                $webservice = 'http://admin:adminpass@ftth:8000/api/profiles/profiles/migrate.json';
+            }
+            $error = $input->getOption('error');
+            if (!$error) {
+                $error = false;
+            }
+            $id = $input->getOption('id');
+            if (!$id) {
+                $id = null;
+            }
+            $from = $input->getOption('from');
+            if (!$from) {
+                $from = null;
+            }
+            $to = $input->getOption('to');
+            if (!$to) {
+                $to = null;
+            }
+            $sentence = $input->getOption('sentence');
+            if (!$sentence) {
+                $sentence = false;
+            }
+
+            $conn = new mysqli($host, $user, $password, $dbname);
+            $sql = "select * from FtthProfile";
+            $where = "";
+            if ($id) {
+                $where .= " id = " . $id;
+            }
+            if ($from) {
+                $where .= (strlen($where) > 0 ? " and " : "") . " id >= " . $from;
+            }
+            if ($to) {
+                $where .= (strlen($where) > 0 ? " and " : "") . " id <= " . $to;
+            }
+
+            if (strlen($where) > 0) {
+                $sql .= " where " . $where;
+            }
+
+            if ($sentence) {
+                echo $sql . "\n";
+            }
+            $rs = $conn->query($sql);
+
+            $log = $this->getContainer()->get('logger');
+
+            while ($d = $rs->fetch_assoc()) {
+                try {
+                    $fields = array(
+                        'id' => $d['id'],
+                        'name' => $d['name'],
+                        'tenancyId' => $d['tenancy_id'],
+                        'download' => $d['max_download'],
+                        'upload' => $d['max_upload']);
+                    $respuesta = $this->runPost($webservice, $fields);
+                    $json = json_decode($respuesta, true);
+                    if ($json) {
+                        if (isset($json['error']) && isset($json['error']['code']) && isset($json['error']['message'])) {
+                            echo "Error id = " . $d['id'] . " and name = '" . $d['name'] . "'\n";
+                            echo "\t\tCode: " . $json['error']['code'] . "\n";
+                            echo "\t\tMessage: " . $json['error']['message'] . "\n";
+                            if ($error) {
+                                $log->err($respuesta);
+                            }
+                        } else if ($d['name'] != $json['name']) {
+                            echo "Error id from " . $d['id'] . " and name from '" . $d['name'] . "', id to " . $json['id'] . ". Validation gestion_id - external_id\n";
+                        }
+                    } else {
+                        echo "Error id = " . $d['id'] . " and name = '" . $d['name'] . "'\n";
+                        if ($error) {
+                            $log->err($respuesta);
+                        }
+                    }
+                } catch (\Throwable $e) {
+                    echo "Error id = " . $d['id'] . " and name = '" . $d['name'] . "'\n";
+                    if ($error) {
+                        $log->err($e);
+                    }
+                }
+            }
+        } catch (\Throwable $e) {
+            echo("\nERROR CODE: " . $e->getCode() . "\nERROR MESSAGE: " . $e->getMessage() . "\n");
+            echo("\nTRACE: \n" . $e->getTraceAsString() . "\n\n");
+        }
+    }
+
+    /**
+     * Ejecuta una accion por post.
+     * @param string $url Contiene la url.
+     * @param array $fields Contiene los campos a enviar.
+     * @return mixed true on success or false on failure. However, if the CURLOPT_RETURNTRANSFER
+     * option is set, it will return the result on success, false on failure.
+     */
+    private function runPost($url, $fields)
+    {
+        $curl = curl_init();
+        curl_setopt_array($curl, array(
+            CURLOPT_RETURNTRANSFER => 1,
+            CURLOPT_URL => $url,
+            CURLOPT_POST => 1,
+            CURLOPT_POSTFIELDS => $fields
+        ));
+        $result = curl_exec($curl);
+        curl_close($curl);
+        return $result;
+    }
+}

+ 36 - 96
src/FTTHBundle/Controller/ONURESTController.php

@@ -11,6 +11,7 @@ use FOS\RestBundle\View\View as FOSView;
 use Symfony\Component\HttpFoundation\Request;
 use Symfony\Component\HttpFoundation\Response;
 use WebserviceBundle\Controller\RESTController;
+use FOS\RestBundle\Controller\Annotations as Rest;
 
 use FOS\RestBundle\Controller\Annotations\Patch;
 
@@ -37,101 +38,41 @@ class ONURESTController extends RESTController
         return get_class(new ONUType());
     }
 
-//    /**
-//     * Create a ONU entity.
-//     *
-//     * @View(statusCode=201, serializerEnableMaxDepthChecks=true)
-//     *
-//     * @param Request $request
-//     *
-//     * @return Response
-//     *
-//     */
-//    public function postAction(Request $request)
-//    {
-//        $entity = new ONU();
-//        $form = $this->createForm(get_class(new ONUType()), $entity, array("method" => $request->getMethod()));
-//        $this->removeExtraFields($request, $form);
-//        $form->handleRequest($request);
-//
-//        if ($form->isValid()) {
-//            $em = $this->getDoctrine()->getManager();
-//            $em->persist($entity);
-//            $em->flush();
-//
-//            return $entity;
-//        }
-//
-//        return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
-//    }
-//
-//    /**
-//     * Update a ONU entity.
-//     *
-//     * @View(serializerEnableMaxDepthChecks=true)
-//     *
-//     * @param Request $request
-//     * @param $entity
-//     *
-//     * @return Response
-//     */
-//    public function putAction(Request $request, ONU $entity)
-//    {
-//        try {
-//            $em = $this->getDoctrine()->getManager();
-//            $request->setMethod('PATCH'); //Treat all PUTs as PATCH
-//            $form = $this->createForm(get_class(new ONUType()), $entity, array("method" => $request->getMethod()));
-//            $this->removeExtraFields($request, $form);
-//            $form->handleRequest($request);
-//            if ($form->isValid()) {
-//                $em->flush();
-//
-//                return $entity;
-//            }
-//
-//            return FOSView::create(array('errors' => $form->getErrors()), Codes::HTTP_INTERNAL_SERVER_ERROR);
-//        } catch (\Exception $e) {
-//            return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
-//        }
-//    }
-//
-//    /**
-//     * Partial Update to a ONU entity.
-//     *
-//     * @View(serializerEnableMaxDepthChecks=true)
-//     *
-//     * @param Request $request
-//     * @param $entity
-//     *
-//     * @return Response
-//     */
-//    public function patchAction(Request $request, ONU $entity)
-//    {
-//        return $this->putAction($request, $entity);
-//    }
-//
-//    /**
-//     * Delete a ONU entity.
-//     *
-//     * @View(statusCode=204)
-//     *
-//     * @param Request $request
-//     * @param $entity
-//     *
-//     * @return Response
-//     */
-//    public function deleteAction(Request $request, ONU $entity)
-//    {
-//        try {
-//            $em = $this->getDoctrine()->getManager();
-//            $em->remove($entity);
-//            $em->flush();
-//
-//            return null;
-//        } catch (\Exception $e) {
-//            return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
-//        }
-//    }
+    /**
+     * Create a entity.
+     *
+     * @View(statusCode=201, serializerEnableMaxDepthChecks=true)
+     *
+     * @param Request $request Contiene el request.
+     * @Rest\Post
+     * @return FOSView|mixed Retorna el FOSView o la entidad.
+     */
+    public function migrateOnuAction(Request $request)
+    {
+        $values = $request->request->all();
+        // deshabilito la tenencia
+        $tenancyService = $this->getTenancyService();
+        if (empty($values['tenancy'])) {
+            $tenancyService->setTenancy(1);
+        } else {
+            $tenancyService->setTenancy($values['tenancy']);
+        }
+        $criteria = new \Doctrine\Common\Collections\Criteria();
+        $criteria->andWhere($criteria->expr()->eq("ponSerialNumber", $values['ponSerialNumber']));
+        $em = $this->getDoctrine()->getManager();
+        $repo = $em->getRepository($this->getRepository());
+        $entities = $repo->matching($criteria)->toArray();
+
+        if (count($entities) > 0 && $entities[0]) {
+            // la entidad existe por lo tanto la actualizo
+            $resp = $this->putAction($request, $entities[0]);
+        } else {
+            // la entidad no existe, entonces la creo
+            // deshabilito el auto increment del id
+            $resp = $this->postAction($request);
+        }
+        return $resp;
+    }
 
     /**
      * PATCH Route annotation.
@@ -172,5 +113,4 @@ class ONURESTController extends RESTController
             return FOSView::create($e->getMessage(), Codes::HTTP_INTERNAL_SERVER_ERROR);
         }
     }
-
 }

+ 75 - 0
src/FTTHBundle/Controller/ProfileRESTController.php

@@ -0,0 +1,75 @@
+<?php
+
+namespace FTTHBundle\Controller;
+
+use FTTHBundle\Entity\ONU;
+use FTTHBundle\Form\ONUType;
+use FOS\RestBundle\Controller\Annotations\RouteResource;
+use FOS\RestBundle\Controller\Annotations\View;
+use FOS\RestBundle\Util\Codes;
+use FOS\RestBundle\View\View as FOSView;
+use FTTHBundle\Form\ProfileType;
+use Symfony\Component\HttpFoundation\Request;
+use Symfony\Component\HttpFoundation\Response;
+use WebserviceBundle\Controller\RESTController;
+use FOS\RestBundle\Controller\Annotations as Rest;
+
+/**
+ * Profile controller.
+ * @RouteResource("Profile")
+ */
+class ProfileRESTController extends RESTController
+{
+
+    /**
+     * @return string Retorna el nombre de la Entity de trabajo.
+     */
+    public function getRepository()
+    {
+        return 'FTTHBundle:Profile';
+    }
+
+    /**
+     * @return string Retorna el tipo de la clase.
+     */
+    public function getFormEntityType()
+    {
+        return get_class(new ProfileType());
+    }
+
+    /**
+     * Create a entity.
+     *
+     * @View(statusCode=201, serializerEnableMaxDepthChecks=true)
+     *
+     * @param Request $request Contiene el request.
+     * @Rest\Post
+     * @return FOSView|mixed Retorna el FOSView o la entidad.
+     */
+    public function migrateProfileAction(Request $request)
+    {
+        $values = $request->request->all();
+        // deshabilito la tenencia
+        $tenancyService = $this->getTenancyService();
+        if (empty($values['tenancy'])) {
+            $tenancyService->setTenancy(1);
+        } else {
+            $tenancyService->setTenancy($values['tenancy']);
+        }
+        $criteria = new \Doctrine\Common\Collections\Criteria();
+        $criteria->andWhere($criteria->expr()->eq("name", $values['name']));
+        $em = $this->getDoctrine()->getManager();
+        $repo = $em->getRepository($this->getRepository());
+        $entities = $repo->matching($criteria)->toArray();
+
+        if (count($entities) > 0 && $entities[0]) {
+            // la entidad existe por lo tanto la actualizo
+            $resp = $this->putAction($request, $entities[0]);
+        } else {
+            // la entidad no existe, entonces la creo
+            // deshabilito el auto increment del id
+            $resp = $this->postAction($request);
+        }
+        return $resp;
+    }
+}

+ 12 - 0
src/FTTHBundle/Entity/Profile.php

@@ -74,6 +74,18 @@ class Profile implements TenancyIdTraitInterface
         return $this->id;
     }
 
+    /**
+     * @param int $id
+     * 
+     * @return Profile
+     */
+    public function setId($id)
+    {
+        $this->id = $id;
+        
+        return $this;
+    }
+
     /**
      * @param string $name
      *

+ 3 - 3
src/FTTHBundle/Form/ONUType.php

@@ -41,8 +41,7 @@ class ONUType extends AbstractType
             ->add('nap')
             ->add('ponSerialNumber')
             ->add('clientId')
-           //->add('administrativeState')
-           //->add('transitionState')
+            ->add('extraData')
             ->add('tenancyId');
 
         $builder->addEventListener(
@@ -100,7 +99,8 @@ class ONUType extends AbstractType
     public function configureOptions(OptionsResolver $resolver)
     {
         $resolver->setDefaults(array(
-            'data_class' => 'FTTHBundle\Entity\ONU'
+            'data_class' => 'FTTHBundle\Entity\ONU',
+            'csrf_protection' => false
         ));
     }
 

+ 62 - 0
src/FTTHBundle/Form/ProfileType.php

@@ -0,0 +1,62 @@
+<?php
+
+namespace FTTHBundle\Form;
+
+use Symfony\Component\Form\AbstractType;
+use Symfony\Component\Form\FormBuilderInterface;
+use Symfony\Component\OptionsResolver\OptionsResolver;
+
+use Symfony\Component\Form\Extension\Core\Type\TextType;
+
+use Symfony\Component\Form\FormEvent;
+use Symfony\Component\Form\FormEvents;
+
+class ProfileType extends AbstractType
+{
+
+    protected $webservice = null;
+
+    public function setWebService($ws)
+    {
+        $this->webservice = $ws;
+    }
+
+    protected $em = null;
+
+    public function setEntityManager($em)
+    {
+        $this->em = $em;
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function buildForm(FormBuilderInterface $builder, array $options)
+    {
+        $builder->add('id')
+            ->add('name')
+            ->add('upload')
+            ->add('download')
+            ->add('tenancyId')
+            ->add('extraData');
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function configureOptions(OptionsResolver $resolver)
+    {
+        $resolver->setDefaults(array(
+            'data_class' => 'FTTHBundle\Entity\Profile',
+            'csrf_protection' => false
+        ));
+    }
+
+    /**
+     * {@inheritdoc}
+     */
+    public function getBlockPrefix()
+    {
+        return 'ftthbundle_profile';
+    }
+}

+ 73 - 1
src/FTTHBundle/tests/ONURESTControllerTest.php

@@ -8,7 +8,7 @@ use Symfony\Component\HttpFoundation\Response;
 use Symfony\Bundle\FrameworkBundle\Client;
 
 /**
- * Class ClientRESTControllerTest
+ * Class ONURESTControllerTest
  * @package FTTHBundle\tests
  * En caso de modificar las tablas solo se deberia modificar la funcion "obtainData" agregando los campos necesarios.
  */
@@ -267,4 +267,76 @@ class ONURESTControllerTest extends WebTestCaseBase
         $validator->setWebservice($webservicemock);
         $this->setContainerObject('device.device_validator', $validator);
     }
+
+
+    /**
+     * Realiza el alta.
+     * post_onu -> /api/onus.{_format}
+     * controller: ClientBundle:ClientREST:post
+     * Method: POST
+     */
+    public function testMIGRATIONS()
+    {
+        // inicializo con los datos del webservicemock
+        $this->initDefault($this->obtainDataWebService());
+        // seteo los datos del listener
+        $this->setListener();
+        // hago la inserccion llamando al servicio por post
+        $this->getClient()->request('POST', '/api/onus/onus/migrate.json', $this->obtainData());
+        // obtengo la respuesta
+        $response = $this->getClient()->getResponse();
+        $this->assertEquals(201, $response->getStatusCode(), "Error en la respuesta http.");
+    }
+
+    /**
+     * Realiza una busqueda.
+     * get_onus -> /api/onus.{_format}
+     * controller: ClientBundle:ClientREST:cget
+     * Method: GET
+     */
+    public function testGET_MIGRATIONS()
+    {
+        // obtengo la respuesta
+        $response = $this->generateGET();
+        // verifco el resultado
+        $this->assertEquals(200, $response->getStatusCode(), "Error en la respuesta http.");
+        $this->assertJson($response->getContent(), "No se obtuvo un objeto json.");
+        $this->assertContains($this->obtainData('ponSerialNumber'), strtolower($response->getContent()), "Error al buscar al onu.");
+    }
+
+    /**
+     * Realiza una baja.
+     * delete_onu -> /api/onus.{_format}
+     * controller: ClientBundle:ClientREST:delete
+     * Method: DELETE
+     */
+    public function testDELETE_MIGRATIONS()
+    {
+        // realizo la consulta
+        $response = $this->generateGET();
+        // obtengo el id de la respuesta de la busqueda
+        $id = $this->getProperty($response, 'id');
+        $this->initDefault();
+        // realizo la consulta
+        $data = array('tenancy' => 1);
+        $this->getClient()->request('DELETE', $this->getUriPutDelete() . $id, $data);
+        // obtengo la respuesta
+        $response = $this->getClient()->getResponse();
+        $this->assertEquals(204, $response->getStatusCode(), "Error en la respuesta http.");
+    }
+
+    /**
+     * Realiza una busqueda.
+     * get_onus -> /api/onus.{_format}
+     * controller: ClientBundle:ClientREST:cget
+     * Method: GET
+     */
+    public function testGET_DELETE_MIGRATIONS()
+    {
+        $response = $this->generateGET();
+        // verifco el resultado
+        $this->assertEquals(200, $response->getStatusCode(), "Error en la respuesta http.");
+        $this->assertJson($response->getContent(), "No se obtuvo un objeto json.");
+    }
+
 }

+ 258 - 0
src/FTTHBundle/tests/ProfileRESTControllerTest.php

@@ -0,0 +1,258 @@
+<?php
+
+namespace FTTHBundle\tests;
+
+use WebserviceBundle\tests\WebTestCaseBase;
+use Symfony\Bundle\FrameworkBundle\Test\WebTestCase;
+use Symfony\Component\HttpFoundation\Response;
+use Symfony\Bundle\FrameworkBundle\Client;
+
+/**
+ * Class ProfileRESTControllerTest
+ * @package FTTHBundle\tests
+ * En caso de modificar las tablas solo se deberia modificar la funcion "obtainData" agregando los campos necesarios.
+ */
+class ProfileRESTControllerTest extends WebTestCaseBase
+{
+    /**
+     * @return string Retorna la uri a consultar.
+     */
+    protected function getUri()
+    {
+        return '/api/profiles.json';
+    }
+
+    /**
+     * @return string Retorna la uri a consultar.
+     */
+    protected function getUriPutDelete()
+    {
+        return '/api/profiles/';
+    }
+
+    /**
+     * Genera los datos a manipular.
+     * @param string $key Contiene la key a buscar en los datos.
+     * @return array|string Retorna el array con los datos o el valor de la key pasada como parametro.
+     * @throws \Exception Lanza un excepcion en caso de no encontrar la key.
+     */
+    protected function obtainData($key = null)
+    {
+        $datos = array();
+        $datos['name'] = '5m-1m wifi';
+        $datos['tenancyId'] = '1';
+        $datos['download'] = '5120000';
+        $datos['upload'] = '1024000';
+        $datos['extraData'] = json_encode('{prueba:pp}');
+
+        if ($key == null) {
+            return $datos;
+        } else {
+            if (isset($datos[$key])) {
+                return $datos[$key];
+            } else {
+                throw new \Exception("No se seteo la key del dato a obtener. key=" . $key);
+            }
+        }
+    }
+
+    /**
+     * Realiza una busqueda.
+     * get_profiles -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:cget
+     * Method: GET
+     * @param string $uri Contiene la direccion.
+     * @param array $data Contiene los filtros a utilizar en la busqueda.
+     * @return null|Response Retorna el response.
+     */
+    private function generateGET($uri = null, $data = null)
+    {
+        $this->initDefault();
+        if ($uri == null) {
+            $uri = $this->getUri();
+        }
+        // realizo la consulta
+        if ($data == null) {
+            $data = array('name' => $this->obtainData('name'), 'tenancyId' => $this->obtainData('tenancyId'));
+        }
+        $this->getClient()->request('GET', $uri . $this->generateFilters($data));
+        // obtengo la respuesta
+        return $this->getClient()->getResponse();
+    }
+
+    /**
+     * Realiza el alta.
+     * post_profile -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:post
+     * Method: POST
+     */
+    public function testPOST()
+    {
+        // inicializo con los datos del webservicemock
+        $this->initDefault();
+        // hago la inserccion llamando al servicio por post
+        $this->getClient()->request('POST', $this->getUri(), $this->obtainData());
+        // obtengo la respuesta
+        $response = $this->getClient()->getResponse();
+        $this->assertEquals(201, $response->getStatusCode(), "Error en la respuesta http.");
+    }
+
+    /**
+     * Realiza una busqueda.
+     * get_profiles -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:cget
+     * Method: GET
+     */
+    public function testGET_POST()
+    {
+        // obtengo la respuesta
+        $response = $this->generateGET();
+        // verifco el resultado
+        $this->assertEquals(200, $response->getStatusCode(), "Error en la respuesta http.");
+        $this->assertJson($response->getContent(), "No se obtuvo un objeto json.");
+        $this->assertContains($this->obtainData('name'), strtolower($response->getContent()), "Error al buscar al onu.");
+    }
+
+    /**
+     * Realiza una modificacion.
+     * put_profile -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:put
+     * Method: PUT
+     */
+    public function testPUT()
+    {
+        // realizo la consulta
+        $response = $this->generateGET();
+        // busco el id
+        $id = $this->getProperty($response, 'id');
+        // inicializo con los datos del webservicemock
+        $this->initDefault();
+        // creo el nuevo set de datos a enviar.
+        $data = $this->obtainDataChange($this->obtainData(), array('upload' => '111222333', 'id' => $id));
+        // hago la modificacion llamando al servicio por put
+        $this->getClient()->request('PUT', $this->getUriPutDelete() . $id, $data);
+        // obtengo la respuesta
+        $response = $this->getClient()->getResponse();
+        $this->assertEquals(200, $response->getStatusCode(), "Error en la respuesta http.");
+    }
+
+    /**
+     * Realiza una busqueda.
+     * get_profiles -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:cget
+     * Method: GET
+     */
+    public function testGET_PUT()
+    {
+        $response = $this->generateGET();
+        // verifco el resultado
+        $this->assertEquals(200, $response->getStatusCode(), "Error en la respuesta http.");
+        $this->assertJson($response->getContent(), "No se obtuvo un objeto json.");
+        $this->assertContains('111222333', strtolower($response->getContent()), "Error al buscar al onu modificado.");
+    }
+
+
+    /**
+     * Realiza una baja.
+     * delete_profile -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:delete
+     * Method: DELETE
+     */
+    public function testDELETE()
+    {
+        // realizo la consulta
+        $response = $this->generateGET();
+        // obtengo el id de la respuesta de la busqueda
+        $id = $this->getProperty($response, 'id');
+        $this->initDefault();
+        // realizo la consulta
+        $data = array('tenancy' => 1);
+        $this->getClient()->request('DELETE', $this->getUriPutDelete() . $id, $data);
+        // obtengo la respuesta
+        $response = $this->getClient()->getResponse();
+        $this->assertEquals(204, $response->getStatusCode(), "Error en la respuesta http.");
+    }
+
+    /**
+     * Realiza una busqueda.
+     * get_profiles -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:cget
+     * Method: GET
+     */
+    public function testGET_DELETE()
+    {
+        $response = $this->generateGET();
+        // verifco el resultado
+        $this->assertEquals(200, $response->getStatusCode(), "Error en la respuesta http.");
+        $this->assertJson($response->getContent(), "No se obtuvo un objeto json.");
+    }
+
+    /**
+     * Realiza el alta.
+     * post_profile -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:post
+     * Method: POST
+     */
+    public function testMIGRATIONS()
+    {
+        // inicializo con los datos del webservicemock
+        $this->initDefault();
+        // hago la inserccion llamando al servicio por post
+        $this->getClient()->request('POST', '/api/profiles/profiles/migrate.json', $this->obtainData());
+        // obtengo la respuesta
+        $response = $this->getClient()->getResponse();
+        $this->assertEquals(201, $response->getStatusCode(), "Error en la respuesta http.");
+    }
+
+    /**
+     * Realiza una busqueda.
+     * get_profiles -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:cget
+     * Method: GET
+     */
+    public function testGET_MIGRATIONS()
+    {
+        // obtengo la respuesta
+        $response = $this->generateGET();
+        // verifco el resultado
+        $this->assertEquals(200, $response->getStatusCode(), "Error en la respuesta http.");
+        $this->assertJson($response->getContent(), "No se obtuvo un objeto json.");
+        $this->assertContains($this->obtainData('name'), strtolower($response->getContent()), "Error al buscar al onu.");
+    }
+
+    /**
+     * Realiza una baja.
+     * delete_profile -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:delete
+     * Method: DELETE
+     */
+    public function testDELETE_MIGRATIONS()
+    {
+        // realizo la consulta
+        $response = $this->generateGET();
+        // obtengo el id de la respuesta de la busqueda
+        $id = $this->getProperty($response, 'id');
+        $this->initDefault();
+        // realizo la consulta
+        $data = array('tenancy' => 1);
+        $this->getClient()->request('DELETE', $this->getUriPutDelete() . $id, $data);
+        // obtengo la respuesta
+        $response = $this->getClient()->getResponse();
+        $this->assertEquals(204, $response->getStatusCode(), "Error en la respuesta http.");
+    }
+
+    /**
+     * Realiza una busqueda.
+     * get_profiles -> /api/profiles.{_format}
+     * controller: FTTHBundle:ProfileREST:cget
+     * Method: GET
+     */
+    public function testGET_DELETE_MIGRATIONS()
+    {
+        $response = $this->generateGET();
+        // verifco el resultado
+        $this->assertEquals(200, $response->getStatusCode(), "Error en la respuesta http.");
+        $this->assertJson($response->getContent(), "No se obtuvo un objeto json.");
+    }
+
+}