Pesquisa personalizada

2009/03/12

Coding: Avoiding unnecessary locking

The code bellow, extracted from java.util.regex.Pattern, avoids unnecessary locking. Look the statement if (!compiled) {, it appears twice times because in the first time, we don't need to create a lock point, but if the code isn't "compiled" (!compiled evaluates true), so it creates a lock point and because the condition of variable compiled can be changed from the first time that it was evaluated (eg.: now !compiled can be evaluated to false, because it was "compiled" by another thread, between the first evaluation and the lock point). It avoids unnecessary retention in the case of the first evaluation was false, because in the entire lifecicly of the object there is only a transition of the variable compiled, from false to true, so only one time in the entire lifecicly, the lock point will be reached. It's a good technique! Think about it!
   1:    /**
   2:     * Creates a matcher that will match the given input against this pattern.
   3:     * </p>
   4:     *
   5:     * @param  input
   6:     *         The character sequence to be matched
   7:     *
   8:     * @return  A new matcher for this pattern
   9:     */
  10:    public Matcher matcher(CharSequence input) {
11: if (!compiled) { 12: synchronized(this) { 13: if (!compiled) 14: compile(); 15: } 16: }
17: Matcher m = new Matcher(this, input); 18: return m; 19: } 20:

Labels: , ,

2009/03/07

Poor Coding

It'snt a joke - the source code below was extracted from the website Mercado Livre.
   1://document.form1.as_observaciones.innerText = '';
   2:if ('N'=='Y'){
   3:document.form1.as_retiro[0].checked = true;}
   4:else{document.form1.as_retiro[1].checked = true;}
   5:
Do you believe?!

Labels: ,

2009/03/06

Instalando permanentemente um GPS Bluetooth no carro

Uso muito GPSs em meus testes de desenvolvimento e por isso os tenho por perto para essas horas programadas, mas já não os uso tanto para me localizar, pois aqui no Plano Piloto de Brasília, tudo é de fácil localização. Por isso, não é a todo momento que eu preciso de auxílio de algum sistema de navegação por GPS, mas quando se precisa, muitas vezes não tenho o GPS em mão, naquela hora, naquele momento - mesmo tendo à disposição uma dezena de diferentes modelos... Uma coisa que eu sempre ando, é com meus celulares: Nokia N80 e HTC Touch P3451 (Windows Mobile 6), mas eles não tem GPS interno e por isso, preciso de um GPS Bluetooth para usar com estes celulares. Poderia usar o sistema do Google Maps das células da rede GSM, mas a margem de erro frequentemente é maior que 900 metros e isso nem sempre é tolerável. Também poderia deixar meu GPS Garmin 60CSX no carro ou usar um navegador veicular, mas sempre corro o risco de deixá-los no carro e quando voltar ao veículo, vê-lo arrombado e sem o GPS...

Para quem não sabe, desde outubro de 2005, tenho trabalhando intensivamente com projetos relacionados a GIS e GPS. Além disso, tenho vendido GPS e componentes eletrônicos. Devido às vendas, já faz tempo que acumulei alguns produtos defeituosos por aqui, principalmente GPS Bluetooth.

PCI do GPS

Testando alguns dos GPS Bluetooth que foram devolvidos pelos clientes e que acumulo por aqui, verifiquei alguns casos onde o GPS Bluetooth funcionava somente quando estava sendo alimentado externamente - nesse caso, constatei que o problema era no minúsculo CI MAX1555 que faz a carga da bateria de íons de lítio e ainda cuida de alimentar o resto do circuito. Resolvi, então, usar um deles no carro, mas não de forma temporária, e, sim, permanente.

Instalação Fixa do GPS Bluetooth

A idéia é bem simples: utilizo o próprio adaptador veicular que veio com o GPS para alimentá-lo, mas ao invés de ligar no socket (antigo acendedor de cigarros) do alimentador do veículo, ligo o alimentador do GPS à bateria do carro. Fiz isso de modo que somente quando a ignição do veículo estiver acionada é que o GPS é alimentado. Para essa ligação, utilizei o próprio chicote de som do veículo, visto que o chicote já estava lá com tudo pronto e era só conectar os fios nele, sem necessidade de mexer em qualquer outra coisa no resto da parte elétrica do veículo.

Instalação do Alimentador Veicular

Tive que fazer uma pequena adaptação no GPS Bluetooth para que ele fosse ligado automaticamente assim que fosse alimentado (ignição ativada), mas foi bem simples, só tive que fazer uma ponte no switch de on/off do GPS. Para uma melhor segurança, mas ainda assim possibilitando a recepção, o coloquei sob o painel do veículo de modo que ficasse logo abaixo da parte plástica do painel (parte mais fina onde não há nenhum outro obstáculo acima do GPS exceto o próprio painel).

Ponte Necessária para Ligar Automaticamente o GPS

Testado tudo, funcionou direitinho. O GPS fica totalmente escondido e agora não tenho mais que me preocupar em levar/tirar o GPS para o carro. Além de dar uso para um GPS que ficaria encostado, sem serventia alguma, tido como prejuízo, fiquei feliz por ter um GPS Bluetooth lá no veículo para quando eu precisar.

Holux M-1000C

Holux M-1000C

E por falar em GPS Bluetooth, se você procura o melhor GPS Bluetooth que há, por um preço bem camarada, com nota fiscal, garantia, tudo certinho, dê uma olhada no Holux M-1000C.

O Holux M-1000 tem características inigualáveis no que tange a sua sensibilidade, precisão e principalmente o cold start - é ultra-rápido. Ele também é um datalogger e grava até 200 mil pontos e sua bateria é recarregável, compatível com a de vários celulares da Nokia e de longa duração. Ele acompanha o software ezTour para Geotag de fotos e download do tracklog.

Labels: ,

2009/03/04

Easy XSS/AJAX using Greasemonkey

Did you have tried to use Greasemonkey? Try it! It's great!

Greasemonkey is a simple but extremely powerful addon to Mozilla Firefox. There are more than a thousand of user scripts to it. With Greasemonkey, you can develop your own script to (aka user script) customize, modify, extract data, insert and whatever you need to do with *any* page!

Easy XSS - Cross-Site Scripting

Recently I need to integrate a website from a customer with external data from another website, but it must occurs when the employee uses the customer website and without more requirements, except: Firefox, Greasemonkey and one little user script to do XSS. I need to do XSS because some part of the application data is extracted from another website (and domain). If you don't know nothing about what's XSS or Same Origin Police, take a read at Wikipedia and you'll know that isn't so easy to do XSS...

Along the rest of this article you will read the acronym XSS, but, please, understand XSS don't as "injection code", but as "The term "cross-site scripting" originated from the fact that a malicious web site could load another web site into another frame or window, then use Javascript to read/write data on the other web site." (or something near its).

When I need to do XSS, I have a couple of options, like: Greasemonkey, Selenium, Firefox Chrome, HTA, Httpunit, customized http clients via TCP sockets, customized browser version, proxy servers, fake dns/ip (eg.: editing system host file to resolve DNS to another IP and changing the document.domain to correspond to the same base domain) and some hacks. For my last application I choose to use Greasemonkey.

Greasemonkey has a javascript function called GM_xmlhttpRequest to be used for AJAX requests; but it, also, can be used to XSS because it runs as a Mozzilla Chrome context. It's amazing! 'cause to do XSS nowadays is so difficulty...

I've created a smaller user script to grease monkey allow me to do AJAX request between diferent domains. See bellow (click to automatically greasemonkey install it):

   1:// ==UserScript==
   2:// @name           UnlockXss
   3:// @namespace      net.marciowb.unlock.xss
   4:// @include        http://127.0.0.1:8080/
   5:// @include        http://www.trilha21.com.br/
   6:// ==/UserScript==
   7:// Copyright Marcio Wesley Borges<marciowb@gmail.com>, Created: 2009/03/05
   8:
   9:unsafeWindow.xss = {};
  10:unsafeWindow.xss._requests = new Array();
  11:
  12:unsafeWindow.xss.call = function(req) {
  13:        unsafeWindow.xss._requests.push(req);
  14:        window.setTimeout( xssExecutor, 1 );
  15:};
  16:
  17:function _xssExecutor() {
  18:        var reqs = unsafeWindow.xss._requests;
  19:        if (reqs.length<1)
  20:                return;
  21:                        
  22:        var req = reqs[reqs.length-1];
  23:        reqs.pop();
  24:        
  25:        GM_xmlhttpRequest(req);
  26:}
  27:
  28:function xssExecutor() {
  29:        try {
  30:                _xssExecutor();
  31:        } catch (ex) {
  32:                GM_log(ex);
  33:        }       
  34:}
  35:
  36:unsafeWindow.GM_xmlhttpRequest = unsafeWindow.xss.call;
  37:

To use it, take a look in the GM_xmlhttpRequest documentation. The example code, from Greasemonkey website, remains valid and works with the UnlockXss script:

   1:GM_xmlhttpRequest({
   2:    method: 'GET',
   3:    url: 'http://greaseblog.blogspot.com/atom.xml',
   4:    headers: {
   5:        'User-agent': 'Mozilla/4.0 (compatible) Greasemonkey',
   6:        'Accept': 'application/atom+xml,application/xml,text/xml',
   7:    },
   8:    onload: function(responseDetails) {
   9:        alert('Request for Atom feed returned ' + responseDetails.status +
  10:              ' ' + responseDetails.statusText + '\n\n' +
  11:              'Feed data:\n' + responseDetails.responseText);
  12:    }
  13:});

Remember: Now, you can embbending GM_xmlhttpRequest in your code, but, also, you must tell to greasemonkey where you run your user script. Do it, adding an entry as the above @include for each domain where you want to enable the XSS/Ajax request.

Assorted Greasemonkey Tips

Do you want compile your Greasemonkey User Script into a XPI extension to Firefox? Okay, you can! See the Greasemonkey Compiler.

Do you need to inject Dojo into a page via Greasemonkey? Don't know how? Do, it:

   1:// ==UserScript==
   2:// @name           ML - Copiar dados da Lista de Envios
   3:// @namespace      net.marciowb.ml.lista.envios
   4:// @description    Copia os dados da lista de envios do ML
   5:// @include        http://www.mercadolivre.com.br/jm/impressionList
   6:// ==/UserScript==
   7:
   8:var script = document.createElement("script");
   9:script.id="scriptInjectedDojo";
  10:script.src="http://www.trilha21.com.br/Webs/js/dojo/dojo.js";
  11:document.getElementsByTagName("head")[0].appendChild(script);
  12:
  13:var link = document.createElement("link");
  14:link.id = "linkInjectedTundra" 
  15:link.rel = "stylesheet";
  16:link.type= "text/css";
  17:link.href="http://www.trilha21.com.br/Webs/js/dijit/themes/tundra/tundra.css";
  18:document.getElementsByTagName("head")[0].appendChild(link);
  19:....

Labels: , ,