Package com.lbslocal.cc.common

Source Code of com.lbslocal.cc.common.Functions

package com.lbslocal.cc.common;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.regex.Pattern;


import com.lbslocal.cc.objects.v0.common.City;
import com.lbslocal.cc.objects.v0.common.Extent;
import com.lbslocal.cc.objects.v0.common.LinePoint;
import com.lbslocal.cc.objects.v0.common.MapSize;
import com.lbslocal.cc.objects.v0.common.Pagination;
import com.lbslocal.cc.objects.v0.common.Point;
import com.lbslocal.cc.objects.v0.common.ShapeDetect;
import com.lbslocal.master.common.ConfigurationManager;
import com.lbslocal.master.common.LogHandler;
import com.sun.rowset.CachedRowSetImpl;
import com.vividsolutions.jts.geom.Coordinate;

public class Functions {
  static List<Country> countryList = new ArrayList<Country>();
  static Calendar updCountry = Calendar.getInstance();

  static List<String> _maquinas = new ArrayList<String>();
  static Calendar updMaquinas = Calendar.getInstance();

  public static String retornaCodUf(String uf) {
    String codUf = "";

    if (uf.equals("RO"))
      codUf = "11";

    if (uf.equals("AC"))
      codUf = "12";

    if (uf.equals("AM"))
      codUf = "13";

    if (uf.equals("RR"))
      codUf = "14";

    if (uf.equals("PA"))
      codUf = "15";

    if (uf.equals("AP"))
      codUf = "16";

    if (uf.equals("TO"))
      codUf = "17";

    if (uf.equals("MA"))
      codUf = "21";

    if (uf.equals("PI"))
      codUf = "22";

    if (uf.equals("CE"))
      codUf = "23";

    if (uf.equals("RN"))
      codUf = "24";

    if (uf.equals("PB"))
      codUf = "25";

    if (uf.equals("PE"))
      codUf = "26";

    if (uf.equals("AL"))
      codUf = "27";

    if (uf.equals("SE"))
      codUf = "28";

    if (uf.equals("BA"))
      codUf = "29";

    if (uf.equals("MG"))
      codUf = "31";

    if (uf.equals("ES"))
      codUf = "32";

    if (uf.equals("RJ"))
      codUf = "33";

    if (uf.equals("SP"))
      codUf = "35";

    if (uf.equals("PR"))
      codUf = "41";

    if (uf.equals("SC"))
      codUf = "42";

    if (uf.equals("RS"))
      codUf = "43";

    if (uf.equals("MS"))
      codUf = "50";

    if (uf.equals("MT"))
      codUf = "51";

    if (uf.equals("GO"))
      codUf = "52";

    if (uf.equals("DF"))
      codUf = "53";

    return codUf;
  }

  public static ShapeDetect getCity(Point ptClick, String server, Integer port, String dataSource) throws Exception {
    if (ptClick.getX() == 0 && ptClick.getY() == 0) {
      throw (new Exception("Coordenadas do ponto devem ser informadas."));
    }

    ShapeDetect shp = new ShapeDetect();

    try {
      TCPClientDecarta tcpDecarta = new TCPClientDecarta(server, port);
      String response = tcpDecarta.Send("S2LN|%LL=" + String.valueOf(ptClick.getY()).replace(",", ".") + ","
          + String.valueOf(ptClick.getX()).replace(",", ".") + "|%RAD=m15%INTERPADDR%ALLATTRS%LL%DS=" + dataSource + "||");

      String[] part = response.split(Pattern.quote("%"));

      for (Integer x = 0; x < part.length; x++) {
        if (part[x].indexOf("S2=") >= 0 && part[x].indexOf("\\") > 0) {
          shp.BAIRRO = CamelCase(part[x].replace("S2=", "").split(Pattern.quote("\\"))[0]);
          shp.NAME = CamelCase(part[x].replace("S2=", "").split(Pattern.quote("\\"))[1]);
        }

        if (part[x].indexOf("S1=") >= 0 && part[x].indexOf("\\") > 0)
          shp.APLICATIVO = convertCountry(part[x].replace("S1=", "").split(Pattern.quote("\\"))[0].substring(0, 2));
      }
    } catch (Exception ex) {
      throw (new Exception("Nao foi possivel encontrar dados para estas coordenadas: X=" + ptClick.getX() + ", y=" + ptClick.getY() + " | "
          + ex.getMessage()));
    }

    try {
      shp.APLICATIVO = convertCountry(shp.APLICATIVO);
    } catch (Exception ex) {
    }

    return shp;
  }

  public static Extent doZoom(Extent ext, double percZoom) {
    if (percZoom == 0)
      return ext; // n�o faz nada

    if (percZoom > 1 || percZoom < -1)
      percZoom = 0;

    double deltaX = ((ext.getXMax() - ext.getXMin()) * percZoom) / 2;
    double deltaY = ((ext.getYMax() - ext.getYMin()) * percZoom) / 2;

    if (deltaX < 0)
      deltaX = -deltaX;
    if (deltaY < 0)
      deltaY = -deltaY;

    if (percZoom > 0) // zoomOut - aumenta o extent
    {
      ext.setXMax(ext.getXMax() + deltaX);
      ext.setXMin(ext.getXMin() - deltaX);
      ext.setYMax(ext.getYMax() + deltaY);
      ext.setYMin(ext.getYMin() - deltaY);
    } else
    // zoomIn - diminui o extent
    {
      ext.setXMax(ext.getXMax() - deltaX);
      ext.setXMin(ext.getXMin() + deltaX);
      ext.setYMax(ext.getYMax() - deltaY);
      ext.setYMin(ext.getYMin() + deltaY);
    }

    return ext;
  }

  public static boolean isNumeric(String str) {
    try {
      Double.parseDouble(str);
    } catch (NumberFormatException nfe) {
      return false;
    }
    return true;
  }

  public static double formatDouble(double value, String format) {
    DecimalFormat df = new DecimalFormat(format.replace("0", "#"));
    df.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));
    return Double.parseDouble(df.format(value));
  }

  public static double formatDouble(String value, String format) {
    DecimalFormat df = new DecimalFormat(format.replace("0", "#"));
    df.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));
    return Double.parseDouble(df.format(Double.parseDouble(value)));
  }

  public static String formatDoubleToString(double value, int digits) {
    DecimalFormat df = new DecimalFormat();
    df.setMaximumFractionDigits(digits);
    df.setDecimalFormatSymbols(DecimalFormatSymbols.getInstance(Locale.ENGLISH));
    return df.format(value);
  }

  double getDistanceDegree(Point p1, Point p2) {
    return Math.sqrt(Math.pow((p2.getX() - p1.getX()), 2) + Math.pow((p2.getY() - p1.getY()), 2));
  }

  public static Extent CalcRadius(Integer radius, Point point) {
    /*** Calcula o extent do raio ***/
    double raio = radius * 9.7125097125097125097125097125097e-6;

    // Envelope env = new EnvelopeClass();
    Extent ext = new Extent(point.getX() - raio, point.getY() - raio, point.getX() + raio, point.getY() + raio);

    return ext;
  }

  public static java.awt.Point ConvertToPixelPoint(Point point, MapSize ms, Extent ext) throws Exception {
    java.awt.Point pt = new java.awt.Point();

    try {
      pt.x = (int) (((point.getX() - ext.getXMin()) * ms.getWidth()) / (ext.getXMax() - ext.getXMin()));
      pt.y = (int) (ms.getHeight() - (((point.getY() - ext.getYMin()) * ms.getHeight()) / (ext.getYMax() - ext.getYMin())));
    } catch (Exception e) {
      throw (new Exception("ConvertCoordsToPixel(CustomPoint): Falha ao converter coordenadas. "));
    }
    return pt;
  }

  public static java.awt.Point ConvertToPixel(Point point, MapSize ms, Extent ext) throws Exception {
    java.awt.Point pt = new java.awt.Point();

    try {
      pt.x = (int) (((point.getX() - ext.getXMin()) * ms.getWidth()) / (ext.getXMax() - ext.getXMin()));
      pt.y = (int) (ms.getHeight() - (((point.getY() - ext.getYMin()) * ms.getHeight()) / (ext.getYMax() - ext.getYMin())));
    } catch (Exception ex) {
      throw (new Exception("ConvertCoordsToPixel(CustomPoint): Falha ao converter coordenadas. "));
    }

    return pt;
  }

  public static String convertCountry(String country) {
    try {
      if (country.toUpperCase() == "BR") {
        country = "Brasil";
      }

      if (country.toUpperCase() == "AR") {
        country = "Argentina";
      }
    } catch (Exception ex) {
    }
    ;

    return country;
  }

  public static String CamelCase(String text) {
    if (!text.isEmpty()) {
      text = text.substring(0, 1).toUpperCase() + text.substring(1).toLowerCase();

      text = text.replace(" a", " A");
      text = text.replace(" b", " B");
      text = text.replace(" c", " C");
      text = text.replace(" d", " D");
      text = text.replace(" e", " E");

      text = text.replace(" f", " F");
      text = text.replace(" g", " G");
      text = text.replace(" j", " J");
      text = text.replace(" h", " H");
      text = text.replace(" l", " L");
      text = text.replace(" m", " M");

      text = text.replace(" n", " N");
      text = text.replace(" o", " O");
      text = text.replace(" p", " P");
      text = text.replace(" q", " Q");
      text = text.replace(" i", " I");

      text = text.replace(" r", " R");
      text = text.replace(" s", " S");
      text = text.replace(" t", " T");
      text = text.replace(" u", " U");

      text = text.replace(" v", " V");
      text = text.replace(" x", " X");
      text = text.replace(" y", " Y");
      text = text.replace(" z", " Z");
      text = text.replace(" w", " W");

      text = text.replace("/a", "/A");
      text = text.replace("/b", "/B");
      text = text.replace("/c", "/C");
      text = text.replace("/d", "/D");
      text = text.replace("/e", "/E");

      text = text.replace("/f", "/F");
      text = text.replace("/g", "/G");
      text = text.replace("/j", "/J");
      text = text.replace("/h", "/H");
      text = text.replace("/l", "/L");
      text = text.replace("/m", "/M");

      text = text.replace("/n", "/N");
      text = text.replace("/o", "/O");
      text = text.replace("/p", "/P");
      text = text.replace("/q", "/Q");
      text = text.replace("/i", "/I");

      text = text.replace("/r", "/R");
      text = text.replace("/s", "/S");
      text = text.replace("/t", "/T");
      text = text.replace("/u", "/U");

      text = text.replace("/v", "/V");
      text = text.replace("/x", "/X");
      text = text.replace("/y", "/Y");
      text = text.replace("/z", "/Z");
      text = text.replace("/w", "/W");

      text = text.replace(" DO ", " do ");
      text = text.replace(" DA ", " da ");
      text = text.replace(" DE ", " de ");
      text = text.replace(" DI ", " di ");
      text = text.replace(" DU ", " du ");

      text = text.replace(" DOS ", " dos ");
      text = text.replace(" DAS ", " das ");
      text = text.replace(" DES ", " des ");
      text = text.replace(" DIS ", " dis ");
      text = text.replace(" DUS ", " dus ");

      text = text.replace(" Do ", " do ");
      text = text.replace(" Da ", " da ");
      text = text.replace(" De ", " de ");
      text = text.replace(" Di ", " di ");
      text = text.replace(" Du ", " du ");

      text = text.replace(" Dos ", " dos ");
      text = text.replace(" Das ", " das ");
      text = text.replace(" Des ", " des ");
      text = text.replace(" Dis ", " dis ");
      text = text.replace(" Dus ", " dus ");

      text = text.replace("Br-", "BR-");
      text = text.replace("Ac-", "AC-");
      text = text.replace("Al-", "AL-");
      text = text.replace("Am-", "AM-");
      text = text.replace("Ap-", "AP-");
      text = text.replace("Ba-", "BA-");
      text = text.replace("Ce-", "CE-");
      text = text.replace("Df-", "DF-");
      text = text.replace("Es-", "ES-");
      text = text.replace("Go-", "GO-");
      text = text.replace("Ma-", "MA-");
      text = text.replace("Mg-", "MG-");
      text = text.replace("Ms-", "MS-");
      text = text.replace("Mt-", "MT-");
      text = text.replace("Pa-", "PA-");
      text = text.replace("Pb-", "PB-");
      text = text.replace("Pe-", "PE-");
      text = text.replace("Pi-", "PI-");
      text = text.replace("Pr-", "PR-");
      text = text.replace("Rj-", "RJ-");
      text = text.replace("Rn-", "RN-");
      text = text.replace("Ro-", "RO-");
      text = text.replace("Rr-", "RR-");
      text = text.replace("Rs-", "RS-");
      text = text.replace("Sc-", "SC-");
      text = text.replace("Se-", "SE-");
      text = text.replace("Sp-", "SP-");
      text = text.replace("To-", "TO-");

      text = text.replace("Br ", "BR ");
      text = text.replace("Ac ", "AC ");
      text = text.replace("Al ", "AL ");
      text = text.replace("Am ", "AM ");
      text = text.replace("Ap ", "AP ");
      text = text.replace("Ba ", "BA ");
      text = text.replace("Ce ", "CE ");
      text = text.replace("Df ", "DF ");
      text = text.replace("Es ", "ES ");
      text = text.replace("Go ", "GO ");
      text = text.replace("Ma ", "MA ");
      text = text.replace("Mg ", "MG ");
      text = text.replace("Ms ", "MS ");
      text = text.replace("Mt ", "MT ");
      text = text.replace("Pa ", "PA ");
      text = text.replace("Pb ", "PB ");
      text = text.replace("Pe ", "PE ");
      text = text.replace("Pi ", "PI ");
      text = text.replace("Pr ", "PR ");
      text = text.replace("Rj ", "RJ ");
      text = text.replace("Rn ", "RN ");
      text = text.replace("Ro ", "RO ");
      text = text.replace("Rr ", "RR ");
      text = text.replace("Rs ", "RS ");
      text = text.replace("Sc ", "SC ");
      text = text.replace("Se ", "SE ");
      text = text.replace("Sp ", "SP ");
      text = text.replace("To ", "TO ");

      text = text.replace(" �", " �");
      text = text.replace(" �", " �");
      text = text.replace(" �", " �");
      text = text.replace(" �", " �");
      text = text.replace(" �", " �");

      text = text.replace(" E ", " e ");

      text = text.replace("'", "`");
    }

    if (text.contains("\\"))
      text = text.trim().substring(0, text.trim().indexOf('\\'));

    return text.trim();
  }

  public static boolean IsNullOrEmpty(String str) {
    return str == null || str.trim().length() == 0;
  }

  public static Pagination definePage(Integer recordCount, Integer recordsPerPage, Integer pageIndex) throws Exception {
    try {
      Pagination pg = new Pagination();

      pg.setRecordCount(recordCount);
      pg.setPageIndex(pageIndex);

      if (pg.getPageIndex() <= 0)
        pg.setPageIndex(1);
      else
        pg.setPageIndex(pageIndex);

      if (pg.getRecordCount() <= 0)
        return new Pagination();

      if (recordsPerPage == 0)
        pg.setRecordsPerPage(recordCount);
      else
        pg.setRecordsPerPage(recordsPerPage);

      pg.setRecordsInitial(((pg.getPageIndex() - 1) * pg.getRecordsPerPage()) + 1);
      pg.setRecordsFinal((Integer) (pg.getPageIndex() * pg.getRecordsPerPage()));

      pg.setPageCount((Integer) pg.getRecordCount() / pg.getRecordsPerPage());

      if ((pg.getRecordCount() % pg.getRecordsPerPage()) != 0)
        pg.setPageCount(pg.getPageCount() + 1);

      if (pg.getPageIndex() % pg.getRecordsPerPage() == 0)
        pg.setPageMin(pg.getPageIndex() - (pg.getRecordsPerPage() - 1));
      else {
        pg.setPageMin(((pg.getPageIndex() / pg.getRecordsPerPage()) * pg.getRecordsPerPage()) + 1);
      }

      pg.setPageMax(pg.getPageMin() + pg.getRecordsPerPage() - 1);

      if (pg.getPageMax() > pg.getPageCount())
        pg.setPageMax(pg.getPageCount());

      if (pg.getPageIndex() == pg.getPageCount())
        pg.setRecordsFinal((Integer) (pg.getRecordsFinal() - (Integer) (pg.getRecordsFinal() - pg.getRecordCount())));

      return pg;
    } catch (Exception ex) {
      throw (new Exception("Erro ao paginar busca!"));
    }
  }

  // Modificado para nao acessar banco
  public static Country getCountryByDataBase(String dataB) {

    ConfigurationManager cm = ConfigurationManager.getInstance();

    return new Country(cm.getAppSettings("DATABASE_SOURCE_RUAS"), cm.getAppSettings("COUNTRY"));
  }

  // Modificado para nao acessar banco
  public static Country getDataBase(int idLicenca, String country) throws SQLException {
    ConfigurationManager cm = ConfigurationManager.getInstance();

    return new Country(cm.getAppSettings("DATABASE_SOURCE_RUAS"), cm.getAppSettings("COUNTRY"));

  }

  // public static Country getCountryByDataBase(String dataB) throws
  // SQLException {
  // loadCountryList();
  //
  // Country[] CountryAux = countryList.toArray(new Country[0]);
  //
  // for (int x = 0; x < CountryAux.length; x++) {
  // if (CountryAux[x].getSource().equals(dataB))
  // return CountryAux[x];
  // }
  //
  // return new Country();
  // }

  // public static Country getDataBase(int idLicenca, String country) throws
  // SQLException {
  // loadCountryList();
  //
  // Country[] CountryAux = countryList.toArray(new Country[0]);
  //
  // for (int x = 0; x < CountryAux.length; x++) {
  // if (CountryAux[x].getId_licenca() == idLicenca &&
  // CountryAux[x].getName().toLowerCase().equals(country.toLowerCase()))
  // return CountryAux[x];
  // }
  //
  // return new Country();
  // }

  // private static void loadCountryList() throws SQLException {
  // Calendar data = Calendar.getInstance();
  // data.setTime(updCountry.getTime());
  // data.add(Calendar.HOUR, 1);
  //
  // if (countryList.size() == 0 ||
  // updCountry.getTime().after(data.getTime())) {
  // countryList.clear();
  // countryList = new ArrayList<Country>();
  //
  // Connection con = dataBase.getConnection("DADOS_WEBSERVICES");
  //
  // Statement st = con.createStatement();
  // String sql = " select a.id_licenca, " +
  // " b.id_pais, b.nome as country, b.datasource " + " from " +
  // " tb_pais as b,  "
  // + " tb_licenca_pais as a, " + " licencas as d  " +
  // " where a.id_pais = b.id_pais " + " and d.id = a.id_licenca "
  // + " and d.status = 1 ";
  // ResultSet rr = st.executeQuery(sql.toUpperCase());
  //
  // while (rr.next()) {
  // Country ctr = new Country();
  // ctr.setId_licenca(rr.getInt("id_licenca"));
  // ctr.setName(rr.getString("country"));
  // ctr.setId(rr.getInt("id_pais"));
  // ctr.setSource(rr.getString("datasource"));
  //
  // countryList.add(ctr);
  // }
  //
  // updCountry = Calendar.getInstance();
  // }
  // }

  public static String getTabelaRuas(City city, int idLicenca, String dataB) throws Exception {
    String tabelaRuas = "";

    Connection con = dataBase.getConnection(dataB);

    if (!dataBase.status.equals("Connection opened")){
      throw (new Exception("Erro ao abrir o banco de dados: " + dataBase.status));
    }
   
    Statement st = con.createStatement();

    ResultSet rr = st.executeQuery("SELECT GEOCODE FROM TB_CIDADES WHERE FONETICO LIKE CONCAT('%', fncFonetico('" + city.getName()
        + "'), '%') AND ( UF LIKE '%" + city.getState() + "%' ) AND GEOCODE IS NOT NULL ORDER BY LENGTH(MUNICY) LIMIT 1; ".toUpperCase());

    CachedRowSetImpl crs = new CachedRowSetImpl();
    crs.populate(rr);

    if (crs.size() == 0) {
      st = con.createStatement();
      rr = st.executeQuery("SELECT GEOCODE FROM TB_CIDADES WHERE FONETICO LIKE CONCAT('%', fncFonetico('%" + city.getName()
          + "%'), '%)' AND ( ESTADO like '%" + city.getState()
          + "%' ) AND GEOCODE IS NOT NULL ORDER BY LENGTH(MUNICY) LIMIT 1 ".toUpperCase());

      crs = new CachedRowSetImpl();
      crs.populate(rr);

      if (crs.size() == 0) {
        throw (new Exception("Nao é possivel encontrar endereços dentro desta cidade : " + city.getName() + "-" + city.getState() + "."));
      } else {
        tabelaRuas = crs.getString("GEOCODE");
      }
    } else {
      crs.next();
      tabelaRuas = crs.getString("GEOCODE");
    }

    st = con.createStatement();

    rr = st.executeQuery("show tables like '" + tabelaRuas + "'");
    crs = new CachedRowSetImpl();
    crs.populate(rr);

    if (crs.size() == 0)
      throw (new Exception("Nao foi possivel encontrar esta cidade " + city.getName() + "-" + city.getState() + "."));

    return tabelaRuas;
  }

  public static Point getGeocodeSQL(int lf, int lt, int rf, int rt, String numero, String coords) {
    LinePoint[] line;
    Point pOrigem, pFim, pFinal = null;
    String format = "0.00000";

    Encrypt ce = new Encrypt();
    if ((!(coords.indexOf(" ") > 0)) && (!(coords.indexOf(",") > 0)) && (!(coords.indexOf(";") > 0)))
      coords = ce.Decode(coords);

    // -2551100,-4924916,-118,59,42,103,-20,10,-115,58
    if (!(coords.indexOf(';') > 0)) {
      format = "0.0000000";
      coords = convertFromDecarta(7, coords);
    }

    boolean blnPar, blnInverse, blnLeftPar = true;
    int L_F_ADD, L_T_ADD, R_F_ADD, R_T_ADD, houseNumber = 0, to, from, intAux;
    int i, z = 0;

    double totalLenght = 0, percentLine = 0, angle;

    if (!numero.equals(""))
      houseNumber = Integer.parseInt(numero); // Atribui valor ao inteiro
    if (houseNumber % 2 == 0)
      blnPar = true;
    else
      blnPar = false; // Buscar por Par ou �mpar

    L_F_ADD = lf;
    L_T_ADD = lt;
    R_F_ADD = rf;
    R_T_ADD = rt;

    to = L_T_ADD;
    from = L_F_ADD;

    if (coords.lastIndexOf(';') == coords.length())
      coords = coords.substring(0, coords.length() - 1);

    if (coords.substring(coords.length() - 1).equals(";"))
      coords = coords.substring(0, coords.length() - 1);

    // Qual lado � par - Left � default
    if (L_F_ADD != 0) {
      if (L_F_ADD % 2 != 0)
        blnLeftPar = false;
    }
    if (R_F_ADD != 0) {
      if (R_F_ADD % 2 == 0)
        blnLeftPar = false;
    }

    // Atribu to / from caso necessario - to e from default left
    if (blnPar) {
      if (!blnLeftPar) {
        to = R_T_ADD;
        from = R_F_ADD;
      }
    } else {
      if (blnLeftPar) {
        to = R_T_ADD;
        from = R_F_ADD;
      }
    }

    // verifica leitura inversa
    if (from > to) {
      intAux = from;
      from = to;
      to = intAux;
      blnInverse = true;
    } else
      blnInverse = false;

    line = new LinePoint[coords.split(";").length];

    // l� inversamente caso necess�rio
    if (!blnInverse) {
      for (i = 0; i < line.length; i++) {
        line[i] = new LinePoint();
        line[i].setPoint(new Point());
        line[i].getPoint().setX(Double.parseDouble(coords.split(";")[i].split(" ")[0].toString()));
        line[i].getPoint().setY(Double.parseDouble(coords.split(";")[i].split(" ")[1].toString()));
      }
    } else {
      for (i = line.length - 1; i > -1; i--) {
        line[z] = new LinePoint();
        line[z].setPoint(new Point());
        line[z].getPoint().setX(Double.parseDouble(coords.split(";")[i].split(" ")[0].toString()));
        line[z].getPoint().setY(Double.parseDouble(coords.split(";")[i].split(" ")[1].toString()));
        z++;
      }
    }

    // Tamanho Total / Parcial
    for (i = 0; i < line.length; i++) {
      if (i + 1 < line.length) {
        line[i].setLength(Math.sqrt(Math.pow((line[i].getPoint().getX() - line[i + 1].getPoint().getX()), 2)
            + Math.pow((line[i].getPoint().getY() - line[i + 1].getPoint().getY()), 2)));
        totalLenght += line[i].getLength();
      }
    }

    // Numero na linha
    if (to - from != 0)
      percentLine = ((houseNumber - from) * totalLenght) / (to - from);

    // Escolhe o segmento
    for (i = 0; i < line.length - 1; i++) {
      if (line[i].getLength() >= percentLine)
        break;
      else
        percentLine -= line[i].getLength();
    }

    // Caso de perda de precis�o
    if (i == line.length - 1) {
      i--;
      percentLine += line[i].getLength();
    }

    pFinal = new Point();
    pFinal.setX(0);
    pFinal.setY(0);

    pOrigem = line[i].getPoint();
    pFim = line[i + 1].getPoint();

    if ((pOrigem.getX() - pFim.getX()) == 0 || (pOrigem.getY() - pFim.getY()) == 0)
      angle = 0;
    else {
      angle = Math.abs(Math.atan((pOrigem.getY() - pFim.getY()) / (pOrigem.getX() - pFim.getX())));
    }

    // 1 Quadrante
    if (pOrigem.getX() < pFim.getX() && pOrigem.getY() < pFim.getY()) {
      pFinal.setX(pOrigem.getX() + percentLine * Math.cos(angle));
      pFinal.setY(pOrigem.getY() + percentLine * Math.sin(angle));
    }

    // 2 Quadrante
    if (pOrigem.getX() > pFim.getX() && pOrigem.getY() < pFim.getY()) {
      pFinal.setX(pOrigem.getX() - percentLine * Math.cos(angle));
      pFinal.setY(pOrigem.getY() + percentLine * Math.sin(angle));
    }

    // 3 Quadrante
    if (pOrigem.getX() > pFim.getX() && pOrigem.getY() > pFim.getY()) {
      pFinal.setX(pOrigem.getX() - percentLine * Math.cos(angle));
      pFinal.setY(pOrigem.getY() - percentLine * Math.sin(angle));
    }

    // 4 Quadrante
    if (pOrigem.getX() < pFim.getX() && pOrigem.getY() > pFim.getY()) {
      pFinal.setX(pOrigem.getX() + percentLine * Math.cos(angle));
      pFinal.setY(pOrigem.getY() - percentLine * Math.sin(angle));
    }

    if (pFinal.getX() == 0 || pFinal.getY() == 0) {
      // 0 ou 360 graus
      if (pOrigem.getX() < pFim.getX() && pOrigem.getY() == pFim.getY()) {
        pFinal.setX(pOrigem.getX() + percentLine);
        pFinal.setY(pOrigem.getY());
      }

      // 90 graus
      if (pOrigem.getX() == pFim.getX() && pOrigem.getY() < pFim.getY()) {
        pFinal.setX(pOrigem.getX());
        pFinal.setY(pOrigem.getY() + percentLine);
      }

      // 180 graus
      if (pOrigem.getX() > pFim.getX() && pOrigem.getY() == pFim.getY()) {
        pFinal.setX(pOrigem.getX() - percentLine);
        pFinal.setY(pOrigem.getY());
      }

      // 270 graus
      if (pOrigem.getX() == pFim.getX() && pOrigem.getY() > pFim.getY()) {
        pFinal.setX(pOrigem.getX());
        pFinal.setY(pOrigem.getY() - percentLine);
      }
    }

    if (pFinal.getX() == 0 && pOrigem.getX() != 0) {
      pFinal = pOrigem;
    }

    if (pFinal.getX() == 0 && pFim.getX() != 0) {
      pFinal = pFim;
    }

    try {
      pFinal.setX(Functions.formatDouble(pFinal.getX(), format));
      pFinal.setY(Functions.formatDouble(pFinal.getY(), format));
    } catch (Exception ex) {
    }

    return pFinal;
  }

  // public static void loadMaquinas() throws SQLException {
  // Calendar data = Calendar.getInstance();
  // data.setTime(updMaquinas.getTime());
  // data.add(Calendar.HOUR, 1);
  //
  // if (_maquinas.size() == 0 || updMaquinas.getTime().after(data.getTime()))
  // {
  // _maquinas.clear();
  // _maquinas = new ArrayList<String>();
  //
  // Connection con = dataBase.getConnection("DADOS_WEBSERVICES");
  //
  // Statement st = con.createStatement();
  //
  // ResultSet rr =
  // st.executeQuery("SELECT id_maquina, nome FROM TB_MAQUINAS order by id_maquina".toUpperCase());
  //
  // while (rr.next()) {
  // StringBuilder tk = new StringBuilder();
  // tk.append(rr.getString("id_Maquina"));
  // tk.append("|");
  // tk.append(rr.getString("nome"));
  //
  // _maquinas.add(tk.toString());
  // }
  //
  // updMaquinas = Calendar.getInstance();
  // }
  // }

  // public static int findIdMaquina(String maquina) throws SQLException {
  // if (_maquinas.size() == 0)
  // loadMaquinas();
  //
  // maquina = maquina.replace("-", ".");
  //
  // for (int x = 0; x < _maquinas.size(); x++) {
  // if (_maquinas.get(x).indexOf(maquina) > -1)
  // return
  // Integer.parseInt(_maquinas.get(x).split(Pattern.quote("|"))[0].toString());
  // }
  //
  // return -1;
  // }

  public static String convertFromDecarta(int precision, String coords) {
    List<Point> ptList = new ArrayList<Point>();

    int y = 0;

    String format = "0.";

    for (int x = 0; x < precision; x++)
      format += "0";

    String[] co = coords.split(",");

    for (int z = 0; z < co.length; z++) {

      if (((co[z + 1]).toString().replace("|", "").length() < (precision + 2))) {
        DecimalFormat df = new DecimalFormat(format.replace("0", "#"));
        df.setMinimumFractionDigits(precision);

        Point pt = new Point();
        pt.setY(Double.parseDouble(df.format(
            (Integer.parseInt(df.format(ptList.get(y).getY()).replace(",", "").replace(".", "")) + Integer.parseInt(co[z]))
                * Math.pow(10, -precision)).replace(",", ".")));
        pt.setX(Double.parseDouble(df.format(
            (Integer.parseInt(df.format(ptList.get(y).getX()).replace(",", "").replace(".", "")) + Integer.parseInt(co[z + 1]))
                * Math.pow(10, -precision)).replace(",", ".")));

        ptList.add(pt);

        y++;
      } else {
        DecimalFormat df = new DecimalFormat(format.replace("0", "#"));
        df.setMinimumFractionDigits(precision);

        Point pt = new Point();
        pt.setY(Double.parseDouble(df.format(Integer.parseInt(co[z]) * Math.pow(10, -precision)).replace(",", ".")));
        pt.setX(Double.parseDouble(df.format(Integer.parseInt(co[z + 1]) * Math.pow(10, -precision)).replace(",", ".")));

        ptList.add(pt);
      }

      z++;
    }

    String coordsRet = "";
    for (int x = 0; x < ptList.size(); x++) {
      coordsRet += String.valueOf(ptList.get(x).getX()) + " " + String.valueOf(ptList.get(x).getY()) + ";";
    }

    return coordsRet;
  }
  public static Point[] convertFromDecartaPoints(int precision, String coords) {
    List<Point> ptList = new ArrayList<Point>();

    int y = 0;

    String format = "0.";

    for (int x = 0; x < precision; x++)
      format += "0";

    String[] co = coords.split(",");

    for (int z = 0; z < co.length; z++) {

      if (((co[z + 1]).toString().replace("|", "").length() < (precision + 2))) {
        DecimalFormat df = new DecimalFormat(format.replace("0", "#"));
        df.setMinimumFractionDigits(precision);

        Point pt = new Point();
        pt.setY(Double.parseDouble(df.format(
            (Integer.parseInt(df.format(ptList.get(y).getY()).replace(",", "").replace(".", "")) + Integer.parseInt(co[z]))
                * Math.pow(10, -precision)).replace(",", ".")));
        pt.setX(Double.parseDouble(df.format(
            (Integer.parseInt(df.format(ptList.get(y).getX()).replace(",", "").replace(".", "")) + Integer.parseInt(co[z + 1]))
                * Math.pow(10, -precision)).replace(",", ".")));

        ptList.add(pt);

        y++;
      } else {
        DecimalFormat df = new DecimalFormat(format.replace("0", "#"));
        df.setMinimumFractionDigits(precision);

        Point pt = new Point();
        pt.setY(Double.parseDouble(df.format(Integer.parseInt(co[z]) * Math.pow(10, -precision)).replace(",", ".")));
        pt.setX(Double.parseDouble(df.format(Integer.parseInt(co[z + 1]) * Math.pow(10, -precision)).replace(",", ".")));

        ptList.add(pt);
      }

      z++;
    }

   
    return ptList.toArray(new Point[0]);
  }
  public static Coordinate[] convertFromDecartaCoordinates(int precision, String coords) {
    List<Coordinate> ptList = new ArrayList<Coordinate>();

    int y = 0;

    String format = "0.";

    for (int x = 0; x < precision; x++)
      format += "0";

    String[] co = coords.split(",");

    for (int z = 0; z < co.length; z++) {

      if (((co[z + 1]).toString().replace("|", "").length() < (precision + 2))) {
        DecimalFormat df = new DecimalFormat(format.replace("0", "#"));
        df.setMinimumFractionDigits(precision);

        double yC;
        double xC;
       
        yC = (Double.parseDouble(df.format(
            (Integer.parseInt(df.format(ptList.get(y).y).replace(",", "").replace(".", "")) + Integer.parseInt(co[z]))
                * Math.pow(10, -precision)).replace(",", ".")));
        xC = (Double.parseDouble(df.format(
            (Integer.parseInt(df.format(ptList.get(y).x).replace(",", "").replace(".", "")) + Integer.parseInt(co[z + 1]))
                * Math.pow(10, -precision)).replace(",", ".")));

        ptList.add(new Coordinate(xC,yC));

        y++;
      } else {
        DecimalFormat df = new DecimalFormat(format.replace("0", "#"));
        df.setMinimumFractionDigits(precision);

        double yT;
        double xT;
        yT = (Double.parseDouble(df.format(Integer.parseInt(co[z]) * Math.pow(10, -precision)).replace(",", ".")));
        xT = (Double.parseDouble(df.format(Integer.parseInt(co[z + 1]) * Math.pow(10, -precision)).replace(",", ".")));

        ptList.add(new Coordinate(xT,yT));
      }

      z++;
    }

    return ptList.toArray(new Coordinate[0]);
  }
  public static void gravarLogUnique(int idLicenca, int idWebService, int points, long time, int idMaquina) {
    long t = System.currentTimeMillis() - time;
    String text = idLicenca + "|" + idWebService + "|" + String.valueOf((t / 1000) % 60) + "|" + points;
    LogHandler.getInstance().getDataLog().writeLog("LOG_PLATAFORMA_", text);
  }

  public static void writeFile(String path, String fileName, String text) {
    // String.format("%1$tY%1$tm%1$td%1$tH%1$tM",ca)

    try {
      File fileDir = new File(path);
      if (!fileDir.exists())
        fileDir.mkdirs();

      Writer out = new OutputStreamWriter(new FileOutputStream(path + File.separator + fileName, true), "UTF-8");
      try {
        out.write(text);
      } finally {
        out.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

  }
  //
  // private static double DateDiff(Date startDate, Date endDate) {
  // Calendar cal1 = Calendar.getInstance();
  // cal1.setTime(startDate);
  //
  // Calendar cal2 = Calendar.getInstance();
  // cal2.setTime(endDate);
  //
  // long milis1 = cal1.getTimeInMillis();
  // long milis2 = cal2.getTimeInMillis();
  //
  // return milis1 - milis2;
  // }
}
TOP

Related Classes of com.lbslocal.cc.common.Functions

TOP
Copyright © 2018 www.massapi.com. All rights reserved.
All source code are property of their respective owners. Java is a trademark of Sun Microsystems, Inc and owned by ORACLE Inc. Contact coftware#gmail.com.