Sonata Admin image upload issue - sonata-admin

I have a problem when I try to upload an image to an entity.
ENTITY
<?php
namespace app\PibeBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;
use Gedmo\Translatable\Translatable;
use Application\Sonata\MediaBundle\Entity\Media;
/**
* Pibe
*
* #ORM\Table()
* #ORM\Entity
*/
class pibe
{
/**
* #var integer
*
* #ORM\Column(name="id", type="integer")
* #ORM\Id
* #ORM\GeneratedValue(strategy="AUTO")
*/
private $id;
/**
* #var string
* #var \Application\Sonata\MediaBundle\Entity\Media
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"}, fetch="LAZY")
*/
private $imagen;
/**
* #var string
* #var \Application\Sonata\MediaBundle\Entity\Media
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"}, fetch="LAZY")
*/
private $logoEs;
/**
* #var string
* #var \Application\Sonata\MediaBundle\Entity\Media
* #ORM\ManyToOne(targetEntity="Application\Sonata\MediaBundle\Entity\Media", cascade={"persist"}, fetch="LAZY")
*/
private $logoEn;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="titulo", type="text",nullable=true)
*/
private $titulo;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="script", type="text", nullable=true)
*/
private $script;
/**
* #var string
*/
private $scriptEn;
/**
* Set imagen
*
* #param string $imagen
* #return ImagenesHome
*/
public function setScript($script)
{
$this->script = $script;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getScript()
{
return $this->script;
}
/**
* Set imagen
*
* #param string $imagen
* #return ImagenesHome
*/
public function setScriptEn($scriptEn)
{
$this->scriptEn = $scriptEn;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getScriptEn()
{
return $this->scriptEn;
}
/**
* #var string
*/
private $tituloEn;
/**
* #var string
* #Gedmo\Translatable
* #ORM\Column(name="texto", type="text",nullable=true)
*/
private $texto;
/**
* #var string
*/
private $textoEn;
/**
* #var boolean
*
* #ORM\Column(name="activo", type="boolean")
*/
private $activo;
/**
* #var integer
*
* #ORM\Column(name="ranking", type="integer")
*/
private $ranking;
/**
* #var string
* #Gedmo\Locale
*/
private $locale;
/**
* Get id
*
* #return integer
*/
public function getId()
{
return $this->id;
}
/**
* Set imagen
*
* #param string $imagen
* #return BannerHome
*/
public function setImagen(Media $imagen=null)
{
$this->imagen = $imagen;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getImagen()
{
return $this->imagen;
}
/**
* Set imagen
*
* #param string $imagen
* #return BannerHome
*/
public function setLogoEs(Media $logoEs)
{
$this->logoEs = $logoEs;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getLogoEs()
{
return $this->logoEs;
}
/**
* Set imagen
*
* #param string $imagen
* #return BannerHome
*/
public function setLogoEn(Media $logoEn)
{
$this->logoEn = $logoEn;
return $this;
}
/**
* Get imagen
*
* #return string
*/
public function getLogoEn()
{
return $this->logoEn;
}
/**
* Set titulo
*
* #param string $titulo
* #return BannerHome
*/
public function setTitulo($titulo)
{
$this->titulo = $titulo;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTitulo()
{
return $this->titulo;
}
/**
* Set titulo
*
* #param string $titulo
* #return BannerHome
*/
public function setTituloEn($tituloEn)
{
$this->tituloEn = $tituloEn;
return $this;
}
/**
* Get titulo
*
* #return string
*/
public function getTituloEn()
{
return $this->tituloEn;
}
/**
* Set texto
*
* #param string $texto
* #return BannerHome
*/
public function setTexto($texto)
{
$this->texto = $texto;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTexto()
{
return $this->texto;
}
/**
* Set texto
*
* #param string $texto
* #return BannerHome
*/
public function setTextoEn($textoEn)
{
$this->textoEn = $textoEn;
return $this;
}
/**
* Get texto
*
* #return string
*/
public function getTextoEn()
{
return $this->textoEn;
}
/**
* Set activoBoolean
*
* #param string $activoBoolean
* #return BannerHome
*/
public function setActivo($activo)
{
$this->activo = $activo;
return $this;
}
/**
* Get activoBoolean
*
* #return string
*/
public function getActivo()
{
return $this->activo;
}
/**
* Set ranking
*
* #param integer $ranking
* #return BannerHome
*/
public function setRanking($ranking)
{
$this->ranking = $ranking;
return $this;
}
/**
* Get ranking
*
* #return integer
*/
public function getRanking()
{
return $this->ranking;
}
public function setTranslatableLocale($locale) {
$this->locale = $locale;
}
}
ADMIN
<?php
namespace app\PibeBundle\Admin;
use Sonata\AdminBundle\Admin\Admin;
use Sonata\AdminBundle\Datagrid\DatagridMapper;
use Sonata\AdminBundle\Datagrid\ListMapper;
use Sonata\AdminBundle\Form\FormMapper;
use Sonata\AdminBundle\Show\ShowMapper;
class PibeAdmin extends Admin
{
/**
* #param DatagridMapper $datagridMapper
*/
protected function configureDatagridFilters(DatagridMapper $datagridMapper)
{
$datagridMapper
//->add('id')
->add('titulo')
//->add('texto')
->add('activo')
->add('ranking')
;
}
/**
* #param ListMapper $listMapper
*/
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->add('id')
->add('titulo',null,array('required'=>false))
//->add('imagenEs')
->add('imagen',null,array(
'template'=>"PibeBundle:Default:imagen.html.twig"
))
->add('activo',null,array('editable'=>true))
->add('ranking')
->add('_action', 'actions', array(
'actions' => array(
'show' => array(),
'edit' => array(),
'delete' => array(),
)
))
;
}
/**
* #param FormMapper $formMapper
*/
protected function configureFormFields(FormMapper $formMapper)
{
$idioma=$this->getRequest()->getLocale();
$formMapper
->add('imagen', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Imagen'
), array(
'link_parameters' => array(
'context' => 'pibe',
'provider' => 'sonata.media.provider.image'
)
)
)
;
if($idioma=='es'){
$formMapper
->add('logoEs', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Logo Español'
), array(
'link_parameters' => array(
'context' => 'pibe',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('logoEn', 'sonata_type_model_list', array(
'required' => false,
'label'=>'Logo Ingles'
), array(
'link_parameters' => array(
'context' => 'pibe',
'provider' => 'sonata.media.provider.image'
)
)
)
->add('titulo','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Titulo Español','required'=>false))
->add('tituloEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Titulo Ingles','data'=>'','required'=>false))
->add('script','text',array('label'=>'Script Video Español','required'=>false))
->add('scriptEn','text',array('label'=>'Script Video Ingles','data'=>'','required'=>false))
->add('texto','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Español','required'=>false))
->add('textoEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Ingles','data'=>'','required'=>false))
;
}else{
$formMapper
->add('tituloEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Titulo Ingles','data'=>'','required'=>false))
->add('titulo','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Titulo Español','required'=>false))
->add('scriptEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Script Video Ingles','data'=>'','required'=>false))
->add('script','text',array('label'=>'Script Video Español','required'=>false))
->add('textoEn','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Ingles','data'=>'','required'=>false))
->add('texto','textarea', array('attr' => array('class' => 'ckeditor'),'label'=>'Texto Español','required'=>false))
;
}
$formMapper
->add('activo')
->add('ranking')
;
$container = $this->getConfigurationPool()->getContainer();
$em = $container->get('doctrine.orm.entity_manager');
if($idioma=='es' && $this->getSubject()->getId()!=null){
//$titoriginal=$em->getRepository('HomeBundle:ImagenesHome')->find($this->getSubject()->getId());
// $titoriginal->setTranslatableLocale('en');
//$em->refresh($titoriginal);
//buscamos su traduccion en la tabal de traducciones.
$repository = $em->getRepository('Gedmo\Translatable\Entity\Translation');
$translations = $repository->findTranslations($this->getSubject());
//rellenamos el campo con la traduccion.
if(count($translations)>0){
if(array_key_exists("titulo",$translations['en'])){
$formMapper->get('tituloEn')->setData($translations['en']['titulo']);
}
if(array_key_exists("texto",$translations['en'])){
$formMapper->get('textoEn')->setData($translations['en']['texto']);
}
if(array_key_exists("script",$translations['en'])){
$formMapper->get('scriptEn')->setData(trim($translations['en']['script']));
}
};
}else if($idioma=='en' && $this->getSubject()->getId()!=null){
$titoriginal=$em->getRepository('PibeBundle:Pibe')->find($this->getSubject()->getId());
//cambiamos el locale a 'es' para coger el texto en español
$titoriginal->setTranslatableLocale('en');
$em->refresh($titoriginal);
//una vez que lo cogemos, volvemos a cambiar el locale a 'en'
$formMapper->get('tituloEn')->setData($titoriginal->getTitulo());
$formMapper->get('textoEn')->setData($titoriginal->getTexto());
$formMapper->get('scriptEn')->setData(trim($titoriginal->getScript()));
$titoriginal->setTranslatableLocale('es');
$em->refresh($titoriginal);
}
}
/**
* #param ShowMapper $showMapper
*/
protected function configureShowFields(ShowMapper $showMapper)
{
$showMapper
->add('id')
->add('titulo')
->add('texto')
->add('activo')
->add('ranking')
;
}
public function prePersist($object) {
$container = $this->getConfigurationPool()->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
//insertar en español.
$object->setTitulo($object->getTitulo());
$object->setTexto($object->getTexto());
$object->setscript($object->getscript());
$object->setTranslatableLocale('es');
$entityManager->persist($object);
$entityManager->flush();
//insertar en ingles.
$object->setTitulo($object->getTituloEn());
$object->setTexto($object->getTextoEn());
//$object->setscript($object->getscriptEn());
if(!$object->getscriptEn()){
$object->setscript(' ');
}
else{
$object->setscript($object->getscriptEn());
}
$object->setTranslatableLocale('en');
$entityManager->persist($object);
$entityManager->flush();
}
public function preUpdate($object) {
$container = $this->getConfigurationPool()->getContainer();
$entityManager = $container->get('doctrine.orm.entity_manager');
//insertar en español.
$object->setTitulo($object->getTitulo());
$object->setTexto($object->getTexto());
$object->setscript($object->getscript());
$object->setTranslatableLocale('es');
$entityManager->persist($object);
$entityManager->flush();
//insertar en ingles.
$object->setTitulo($object->getTituloEn());
$object->setTexto($object->getTextoEn());
//$object->setscript($object->getscriptEn());
if(!$object->getscriptEn()){
$object->setscript(' ');
}
else{
$object->setscript($object->getscriptEn());
}
$object->setTranslatableLocale('en');
$entityManager->persist($object);
$entityManager->flush();
}
}
If I upload an image of 1500x1000 its works perfect:
But if the image is 1920x1080 it doesn´t works:
When I click crear it doesn´t add the image:
The php returns an error 500 from the server,but the image is in uploads/media. And I haven´t set a size(height/widht) limit

The probles os this malfunction is the php extension php_fileinfo,with it disabled I get the error,with it enabled all works as expected

Related

How-to send sub data array to api-platform in a ManyToOne relation?

I've got a nice entity with 3 ManyToOne relations.
A final entity linked with the ID fields.
I want to send to my API each value for each parameter and save it in my database.
See my code below:
One of my linked entity (Mode and Customer are "quasi" the same):
/**
* #ApiResource(
* normalizationContext={"groups"={"user:read"}},
* denormalizationContext={"groups"={"user:write"}},
* collectionOperations={
* "get",
* "post"={"security"="is_granted('ROLE_ADMIN')"}
* },
* itemOperations={
* "get",
* "put"={"security"="is_granted('ROLE_ADMIN')"},
* },
* attributes={"order"={"name": "ASC"}}
* )
* #ApiFilter(OrderFilter::class)
* #ApiFilter(SearchFilter::class, properties={"id": "exact", "name": "ipartial"})
* #UniqueEntity(fields={"name"})
* #ORM\Entity(repositoryClass="App\Repository\ParameterRepository")
*/
class Parameter
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #ApiProperty(identifier=true)
* #Groups({"user:read"})
*/
private $id;
/**
* #ApiSubresource
* #Groups({"user:read", "user:write"})
* #ORM\Column(type="string", length=255)
* #Assert\NotBlank()
* #Assert\Unique()
*/
private $name;
/**
* #Groups({"user:read", "user:write"})
* #ORM\Column(type="text", length=65535, nullable=true)
*/
private $help;
/**
* #ORM\OneToMany(targetEntity=CustomersParameters::class, mappedBy="parameter")
*/
private $param;
The entity who have the linked results:
/**
* #ApiResource(
* normalizationContext={"groups"={"user:read"}},
* denormalizationContext={"groups"={"user:write"}},
* collectionOperations={
* "get",
* "post"={"security"="is_granted('ROLE_ADMIN')"},
* },
* itemOperations={
* "get",
* "put"={"security"="is_granted('ROLE_ADMIN')"},
* "delete"={"security"="is_granted('ROLE_ADMIN')"},
* },
* )
* #ApiFilter(GroupFilter::class, arguments={"parameterName": "group_on", "overrideDefaultGroups": false, "whitelist": {"allowed_group"}})
* #ApiFilter(OrderFilter::class, properties={"value","createdAt","updatedAt","customer.name","customer.id","parameter.name","parameter.id","mode.name","mode.id"})
* #ApiFilter(SearchFilter::class, properties={"id": "exact", "value": "ipartial", "customer.name": "ipartial", "customer.id": "exact", "parameter.name": "ipartial", "parameter.id": "exact", "mode.name": "ipartial", "mode.id": "exact"})
* #ORM\Entity(repositoryClass="App\Repository\CustomersParametersRepository")
*/
class CustomersParameters
{
/**
* #ORM\Id
* #ORM\GeneratedValue
* #ORM\Column(type="integer")
* #Groups({"CustomersParameters:read","user:read"})
* #ApiProperty(identifier=true)
*/
private $id;
/**
* #ORM\Column(type="string", length=255, nullable=false)
* #Groups({"user:read","user:write"})
* #Assert\NotBlank()
*/
private $value;
/**
* #ORM\ManyToOne(targetEntity=Customer::class, inversedBy="param")
* #ORM\JoinColumn(nullable=false)
* #Groups({"user:read","user:write"})
* #Assert\NotBlank()
*/
private $customer;
/**
* #ORM\ManyToOne(targetEntity=Parameter::class, inversedBy="param")
* #ORM\JoinColumn(nullable=false)
* #Groups({"user:read","user:write"})
* #Assert\NotBlank()
*/
private $parameter;
/**
* #ORM\ManyToOne(targetEntity=Mode::class, inversedBy="param")
* #ORM\JoinColumn(nullable=false)
* #Groups({"user:read","user:write"})
* #Assert\NotBlank()
*/
private $mode;
/**
* #ORM\Column(type="datetime", nullable=false)
* #Groups({"user:read"})
*/
private $createdAt;
/**
* #ORM\Column(type="datetime", nullable=true)
* #Groups({"user:read"})
*/
private $updatedAt;
I want to use in react-admin this component:
const CustomersParametersCreate =(props) => (
<Create {...props} title={"Creation d'un lien client/paramètre"}>
<SimpleForm toolbar={<Tools.CreateToolbar/>} warnWhenUnsavedChanges>
<ReferenceInput
label='Client'
source="customer.name"
reference="customers"
validate={required()}
filterToQuery={searchText => ({name: searchText, order: 'ASC', pagination: false})}
fullWidth
>
<AutocompleteInput name={'customer'} optionText={"name"} allowNull={false}/>
</ReferenceInput>
<ReferenceInput
label='Fonctionnement'
source="mode.name"
reference="modes"
validate={required()}
sort={{field: 'name', order: 'DESC'}}
fullWidth
>
<AutocompleteInput optionText={"name"} allowNull={false}/>
</ReferenceInput>
<ArrayInput label={"Paramètrage"} source={'parameter'}>
<SimpleFormIterator>
<ReferenceInput label='Paramètre' reference={'parameters'} source={'parameter.name'} filterToQuery={searchText => ({name: searchText, order: 'ASC', pagination: false})} fullWidth>
<SelectInput optionText={'name'} />
</ReferenceInput>
<TextInput source="value" label='Valeur' validate={required()} fullWidth/>
</SimpleFormIterator>
</ArrayInput>
</SimpleForm>
</Create>
);
And the POST result is:
{
"customer":
{"name":"/api/customers/1"},
"mode":
{"name":"/api/modes/1"},
"parameter":
[{
"parameter":
{
"name":"/api/parameters/1"
},
"value":"1"
},
{
"parameter":
{
"name":"/api/parameters/2"
},
"value":"1"
}]
}
What can I do to have the 'value' of the CustomersParameters entity linked with the parameter?
Try this
{
"customer":"/api/customers/1",
"mode":"/api/modes/1",
"parameter": [
"/api/parameters/1",
"/api/parameters/2"
]
}

function doesn't work in PHP

this a part of a class, trying to handle arrays and numbers in the response content but i encountered a problem:
public function is_jsonable($content){
if(is_array($this->content) || is_numeric($this->content)){
json_decode($this->content,true);
}
elseif (null !== $this->$content && !is_string($this->$content) && !is_numeric($this->$content)) {
throw new Exception('Response Content is Invalid !');
}
return $this->content;
}
/**
* Set Response's content
*
* #param string
*
*/
function __construct($content = false, $httpCode = 200)
{
$this->httpCode = $this->httpStatuses[$httpCode];
$this->header('content-type', 'text/html');
$this->content = $content;
}
public function header($name, $value)
{
$this->headers[$name] = $value;
return $this;
}
/**
* Returns the Response as a string
*
* #return string
*
*/
public function __toString()
{
if(!headers_sent()){
header("$this->httpProtocole 200 $this->httpCode");
foreach ($this->headers as $name => $value) {
header($name.':'.$value,false);
}
}
return $this->content;
}
};
and this is the index :
<?php
ini_set('display_errors', 1);
require_once dirname(__DIR__) . '/Core/Http/Response.php';
use \Core\Http\Response;
$test = new Response(200);
echo $test ;
?>
the problem is that is_jsonable doesn't work, it works fine when i just instantiate the class with a string value
enter image description here

How to get all video files from phone internal storage(Nexus 5) in android

I want to get all video files from the internal memory of the device.
I have tried the following ways without getting a result
File file[] = Environment.getExternalStorageDirectory().listFiles();
File file= Environment.getDataDirectory();
File file[] = Environment.getRootDirectory().listFiles();
File file = Environment.getExternalStoragePublicDirectory();
I got the solution for this..Please look into below code
import android.os.Environment;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class ExternalStorage {
public static final String SD_CARD = "sdCard";
public static final String EXTERNAL_SD_CARD = "externalSdCard";
/**
* #return True if the external storage is available. False otherwise.
*/
public static boolean isAvailable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state) || Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
return true;
}
return false;
}
public static String getSdCardPath() {
return Environment.getExternalStorageDirectory().getPath() + "/";
}
/**
* #return True if the external storage is writable. False otherwise.
*/
public static boolean isWritable() {
String state = Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)) {
return true;
}
return false;
}
/**
* #return A map of all storage locations available
*/
public static Map<String, File> getAllStorageLocations() {
Map<String, File> map = new HashMap<String, File>(10);
List<String> mMounts = new ArrayList<String>(10);
List<String> mVold = new ArrayList<String>(10);
mMounts.add("/mnt/sdcard");
mVold.add("/mnt/sdcard");
try {
File mountFile = new File("/proc/mounts");
if(mountFile.exists()){
Scanner scanner = new Scanner(mountFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("/dev/block/vold/")) {
String[] lineElements = line.split(" ");
String element = lineElements[1];
// don't add the default mount path
// it's already in the list.
if (!element.equals("/mnt/sdcard"))
mMounts.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
try {
File voldFile = new File("/system/etc/vold.fstab");
if(voldFile.exists()){
Scanner scanner = new Scanner(voldFile);
while (scanner.hasNext()) {
String line = scanner.nextLine();
if (line.startsWith("dev_mount")) {
String[] lineElements = line.split(" ");
String element = lineElements[2];
if (element.contains(":"))
element = element.substring(0, element.indexOf(":"));
if (!element.equals("/mnt/sdcard"))
mVold.add(element);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
for (int i = 0; i < mMounts.size(); i++) {
String mount = mMounts.get(i);
if (!mVold.contains(mount))
mMounts.remove(i--);
}
mVold.clear();
List<String> mountHash = new ArrayList<String>(10);
for(String mount : mMounts){
File root = new File(mount);
if (root.exists() && root.isDirectory() && root.canWrite()) {
File[] list = root.listFiles();
String hash = "[";
if(list!=null){
for(File f : list){
hash += f.getName().hashCode()+":"+f.length()+", ";
}
}
hash += "]";
if(!mountHash.contains(hash)){
String key = SD_CARD + "_" + map.size();
if (map.size() == 0) {
key = SD_CARD;
} else if (map.size() == 1) {
key = EXTERNAL_SD_CARD;
}
mountHash.add(hash);
map.put(key, root);
}
}
}
mMounts.clear();
if(map.isEmpty()){
map.put(SD_CARD, Environment.getExternalStorageDirectory());
}
return map;
}
}

JFreeChart LogAxis Frequency/Resistance multipliers

I'm trying to figure out how to dynamically format the values on the axes of my line chart based on the multiplier.
I'm using LogAxis for both the X and Y axes, as follows:
final LogAxis rangeAxis = new LogAxis(valueAxisLabel);
rangeAxis.setStandardTickUnits(LogAxis.createLogTickUnits(Locale.ENGLISH));
rangeAxis.setRange(0.01, 10.0); //10 mOhms to 10 Ohms
plot.setRangeAxis(rangeAxis);
final LogAxis domainAxis = new LogAxis(frequencyAxisLabel);
domainAxis.setStandardTickUnits(LogAxis.createLogTickUnits(Locale.ENGLISH));
domainAxis.setRange(100, 10000000); //100Hz to 10MHz
plot.setDomainAxis(domainAxis);
I currently have the following values on my Y axis:
0.01, 0.1, 1, 10
But would like it to display as
10mOhm, 100mOhm, 1Ohm, 10Ohm
and on the X axis I have
100, 1,000, 10,000, 100,000, 1,000,000, 10,000,000
but would like to see
100Hz, 1kHz, 10kHz, 100kHz, 1MHz, 10MHz
I know you can override the NumberFormat used on the axis, but I haven't found a way to do so to where the NumberFormat is overridden dynamically based on the value like this. Is this possible? Do I need to extend NumberFormat to do this?
EDIT:
Per the accepted answer, I extended NumberFormat as follows (Note that the implementation isn't complete but rather hacked for quick demo purposes for my boss)
public class UnitNumberFormat extends NumberFormat
{
/**
*
*/
private static final long serialVersionUID = -8544764432101798895L;
private UnitValue unitValue;
public UnitNumberFormat(UnitValue unitValue)
{
super();
this.unitValue = unitValue;
}
/*
* (non-Javadoc)
* #see java.text.NumberFormat#format(double, java.lang.StringBuffer,
* java.text.FieldPosition)
*/
#Override
public StringBuffer format(double number, StringBuffer toAppendTo, FieldPosition pos)
{
StringBuffer formattedValue = new StringBuffer();
BigDecimal bd = new BigDecimal(number);
BigDecimal multiplier = new BigDecimal(1);
String multiplierString = "";
if(number < 1 && number > 0)
{
multiplier = new BigDecimal(1000);
multiplierString = "m";
}
else if(number < 1000 && number >= 1)
{
multiplier = new BigDecimal(1);
multiplierString = "";
}
else if(number < 1000000 && number >= 1000)
{
multiplier = new BigDecimal(1. / 1000);
multiplierString = "k";
}
else if(number < 1000000000 && number >= 1000000)
{
multiplier = new BigDecimal(1. / 1000000);
multiplierString = "M";
}
else
{
throw new NumberFormatException("This formatter doesn't yet support values beyond Mega");
}
bd = bd.multiply(multiplier).round(new MathContext(1, RoundingMode.HALF_UP));
formattedValue.append(bd.toPlainString());
formattedValue.append(" ");
formattedValue.append(multiplierString);
formattedValue.append(this.unitValue.getUnit());
return formattedValue;
}
/*
* (non-Javadoc)
* #see java.text.NumberFormat#format(long, java.lang.StringBuffer,
* java.text.FieldPosition)
*/
#Override
public StringBuffer format(long number, StringBuffer toAppendTo, FieldPosition pos)
{
return null;
}
/*
* (non-Javadoc)
* #see java.text.NumberFormat#parse(java.lang.String,
* java.text.ParsePosition)
*/
#Override
public Number parse(String source, ParsePosition parsePosition)
{
return null;
}
}
and UnitValue is as follows:
public enum UnitValue {
HERTZ("Hz"),
OHMS("Ω"),
;
private final String unit;
private UnitValue(String unit)
{
this.unit = unit;
}
/**
* #return the unit
*/
public String getUnit()
{
return unit;
}
}
Yes you do need to subclass NumberFormat there is an example here

Control Volume Code for J2ME

I have nokia xpressmusic 5130 c-2 working on symbian (j2me) the volume buttons has been broken, so i decided to make a j2me program to control the volume (increase,decrease)
I have found many codes through the internet but often not work or have many errors because not complied with the program flow diagram and screen
regards
If the device have support to the JSR 256: Mobile Sensor API, then you can use your API:
http://jcp.org/en/jsr/detail?id=256
My class that uses the JSR 256:
/*
* REVISION HISTORY:
*
* Date Author(s)
* CR Headline
* =============================================================================
* 22/Oct/2009 Douglas Daniel Del Frari
* <CR51674> Initial Version
* =============================================================================
* 25/Feb/2010 Douglas Daniel Del Frari
* <CR52577> Added more one sensor (charge state) to detection of charger state.
* =============================================================================
*/
package j2me.mobilesensor;
import java.io.IOException;
import javax.microedition.io.Connector;
import javax.microedition.sensor.Data;
import javax.microedition.sensor.DataListener;
import javax.microedition.sensor.SensorConnection;
import javax.microedition.sensor.SensorInfo;
import javax.microedition.sensor.SensorManager;
/**
* This class uses the resource of the mobile sensor (JSR-256) to capture the
* phone battery level, and the volume level of the phone
*
* #author Douglas D. Del Frari (douglas.frari#gmail.com)
*/
public class MobileSensorManager implements DataListener, Runnable{
/** ID for the alert dialog */
public static final int ID_DIALOG_BATTERY_CHARGE = 90;
/**
* String used to get the battery charge level.
*/
private static final String BATTERY = "battery_charge";
/**
* String used to get the charger state (plugged on or off).
*/
private static final String BATTERY_CHARGER_STATE = "charger_state";
/**
* String used to get the sound level
*/
private static final String SOUND_LEVEL = "sound_level_setting";
// sensors
private static SensorConnection batterySensor = null;
private SensorConnection soundSensor = null;
// SensorInfo objects containing info about
private SensorInfo infos[];
// Is sensor thread running?
private static boolean isStopped = false;
// Buffer for the sensor data
private static final int BUFFER_SIZE = 1;
/**
* Indicate the minimal value of battery level of the game
*/
public static final int BATTERY_LIFE_LIMIT = 25;
// Thread for initializing and listening
private Thread thread = null;
/*
* Sensor quantity string received from the dataReceived() method
*/
private String sensorString = "";
// Sensor value (battery_charge)
private String batteryString = "";
private String volumeString = "";
private boolean isActiveBatterySensor;
private boolean isLowBatteryCharge;
private int batteryChargeValue;
private int volumeValue;
private SensorConnection batteryChargerState;
private boolean chargeState;
// instance this class
private static MobileSensorManager instance;
/**
* default constructor
*/
private MobileSensorManager() {
}
/**
* Get the MobileSensorManager instance
*
* #return instance this
*/
public static MobileSensorManager getInstance() {
if (instance == null) {
instance = new MobileSensorManager();
}
return instance;
}
/**
* #param stopped
*/
private synchronized void setStopped(boolean stopped) {
isStopped = stopped;
notify();
if (thread != null)
thread = null;
}
/**
* start the mobile sensors
*/
public synchronized void start() {
setStopped(false);
if (thread == null)
thread = new Thread(this);
thread.start();
}
/**
* stop the mobile sensors
*/
public synchronized void stop() {
setStopped(true);
thread = null;
}
/* (non-Javadoc)
* #see java.lang.Runnable#run()
*/
public void run() {
initSensors();
}
/**
* Initializes (opens) the sensors and sets the DataListener. Takes also
* care of removing the DataListeners and closing the connections
*/
private synchronized void initSensors() {
batterySensor = openSensor(BATTERY);
if (batterySensor == null) {
isActiveBatterySensor = false;
return;
} else {
isActiveBatterySensor = true;
}
batteryChargerState = openSensor(BATTERY_CHARGER_STATE);
soundSensor = openSensor(SOUND_LEVEL);
try {
batterySensor.setDataListener(this, BUFFER_SIZE);
if (soundSensor !=null) {
soundSensor.setDataListener(this, BUFFER_SIZE);
}
if (batteryChargerState != null) {
batteryChargerState.setDataListener(this, BUFFER_SIZE);
}
while (!isStopped) {
try {
wait();
} catch (InterruptedException ie) {
}
}
batterySensor.removeDataListener();
if (soundSensor !=null) {
soundSensor.removeDataListener();
}
if (batteryChargerState != null) {
batteryChargerState.removeDataListener();
}
} catch (IllegalMonitorStateException imse) {
imse.printStackTrace();
} catch (IllegalArgumentException iae) {
iae.printStackTrace();
}
try {
if (batterySensor!=null) {
batterySensor.close();
}
if (soundSensor !=null) {
soundSensor.close();
}
if (batteryChargerState != null) {
batteryChargerState.close();
}
} catch (IOException ioe) {
ioe.printStackTrace();
}
if (isStopped) {
batterySensor = null;
soundSensor = null;
batteryChargerState = null;
}
}
/**
* Searches sensors of desired quantity and if found returns a
* SensorConnection opened to it.
*
* #return SensorConnection, which has been opened to a sensor matching the
* criteria
*/
private SensorConnection openSensor(String quantity) {
infos = SensorManager.findSensors(quantity, null);
if (infos.length == 0)
return null;
String sensor_url = infos[0].getUrl();
try {
return (SensorConnection) Connector.open(sensor_url);
} catch (IOException ioe) {
ioe.printStackTrace();
return null;
}
}
/* (non-Javadoc)
* #see javax.microedition.sensor.DataListener#dataReceived(javax.microedition.sensor.SensorConnection, javax.microedition.sensor.Data[], boolean)
*/
public void dataReceived(SensorConnection sensor, Data[] data, boolean isDataLost) {
sensorString = sensor.getSensorInfo().getQuantity();
int values[] = data[0].getIntValues();
if (sensorString.equals(BATTERY)) {
setBatteryString("" + values[0] + "%");
batteryChargeValue = values[0];
}
if (sensorString.equals(SOUND_LEVEL)) {
setVolumeString("" + values[0] + " sound level");
volumeValue = values[0];
}
if (sensorString.equals(BATTERY_CHARGER_STATE)) {
int value = values[0];
if (value == 0)
chargeState = false;
else if (value == 1)
chargeState = true;
}
if (values[0] <= BATTERY_LIFE_LIMIT) {
isLowBatteryCharge = true;
} else {
isLowBatteryCharge = false;
}
}
/**
* #return the batteryString
*/
public String getBatteryString() {
return batteryString;
}
/**
* #param batteryString the batteryString to set
*/
public void setBatteryString(String batteryString) {
this.batteryString = batteryString;
}
/**
* #return the isLowBatteryCharge
*/
public boolean isLowBatteryCharge() {
return isLowBatteryCharge;
}
/**
* #return the isActiveBatterySensor
*/
public boolean isActiveBatterySensor() {
return isActiveBatterySensor;
}
/**
* #return the batteryChargeValue
*/
public int getBatteryChargeValue() {
return batteryChargeValue;
}
/**
* #param volumeString the volumeString to set
*/
public void setVolumeString(String volumeString) {
this.volumeString = volumeString;
}
/**
* #return the volumeString
*/
public String getVolumeString() {
return volumeString;
}
/**
* #param volumeValue the volumeValue to set
*/
public void setVolumeValue(int volumeValue) {
this.volumeValue = volumeValue;
}
/**
* #return the volumeValue
*/
public int getVolumeValue() {
return volumeValue;
}
/**
* Get state of battery charge
*
* #return True if the charge is plugged in, otherwise not plugged in
*/
public boolean isChargedState() {
return chargeState;
}
}

Resources