Exemplo n.º 1
0
  DirectoryAnswer getDA(DirectoryRequest dr) throws P2PDDSQLException {
    String sql =
        "select addresses, timestamp, strftime('%Y%m%d%H%M%fZ',timestamp,'unixepoch') from registered where global_peer_ID = ?;";
    ArrayList<ArrayList<Object>> adr = db_dir.select(sql, new String[] {dr.globalID}, DEBUG);
    if (DEBUG) System.out.println("Query: " + sql + " with ?= " + Util.trimmed(dr.globalID));
    if (DEBUG) System.out.println("Found addresses #: " + adr.size());
    DirectoryAnswer da = new DirectoryAnswer();
    da.version = dr.version;
    if (adr.size() != 0) {
      Integer time = Util.Ival(adr.get(0).get(1));
      if (time == null) {
        time = new Integer(0);
        out.println("EMPTY TIME. WHY?");
      }
      Date date = new Date();
      date.setTime(time.longValue());
      da.date.setTime(date);

      String addresses = (String) adr.get(0).get(0);
      if (DEBUG) System.out.println("This address: " + addresses);
      String a[] = Address.split(addresses);
      for (int k = 0; k < a.length; k++) {
        if ((a[k] == null) || ("".equals(a[k])) || ("null".equals(a[k]))) continue;
        if (DEBUG) System.out.println("This address [" + k + "]" + a[k]);
        da.addresses.add(new Address(a[k]));
      }
    } else {
      if (DEBUG) out.print("Empty ");
    }
    return da;
  }
Exemplo n.º 2
0
  public static ArrayList<Address> getOrderedCertifiedTypedAddresses(ArrayList<Address> addr) {
    if (DEBUG) System.out.println("Address:getOrdCTA: start " + Util.concatA(addr, "---", "NULL"));
    if ((addr == null) || (addr.size() == 0)) return null;
    ArrayList<Address> result = new ArrayList<Address>();
    int k = 0;
    for (Address ta : addr) {
      if (ta == null) {
        if (DEBUG || DD.DEBUG_TODO) {
          System.out.println("TypedAddress:getOrdCer: No address: " + k);

          for (int i = 0; i < addr.size(); i++) {
            System.out.println("TypedAddress:getOrdCert: adr[" + i + "]=" + ta);
          }
        }
        continue;
      }
      if (!ta.certified) continue;
      if ((ta.address == null) && (ta.domain == null)) continue;
      if (ta.domain == null) ta._setAddress(ta.address);
      result.add(ta);
      k++;
    }
    if (DEBUG)
      System.out.println("Address:getOrdCTA: result " + Util.concatA(result, "---", "NULL"));
    if (result.size() == 0) return null;
    // Address[] r = result.toArray(new TypedAddress[]{});
    // Collections.sort(result, new TypedAddressComparator());
    // Arrays.sort(result, new TypedAddressComparator());
    Collections.sort(result, new TypedAddressComparator());
    return result;
  }
Exemplo n.º 3
0
  public void updateVisibleOutput() {
    String output = null;
    if (!outputWaiting) {
      Cell playerCell = player.getCell();
      ArrayList<Item> items = playerCell.getItems();
      output = Util.capitalizeFirstLetter(player.getCell().getGroundProto().getName()) + ". ";
      if (!items.isEmpty()) {
        if (items.size() > 1) output += "Several items lying. ";
        else output += Util.capitalizeFirstLetter(items.get(0).getName()) + " lying. ";
      }
      output += outputTemp;
    } else output = outputTemp;

    output = Util.splitToLines(output, WIDTH_FOR_TEXT);
    int maxLength = (OUTPUTBOX_HEIGHT) * WIDTH_FOR_TEXT - (int) (WIDTH_FOR_TEXT * 0.7);
    if (visibleOutput.length() < maxLength) {
      if (output.length() > maxLength) {
        visibleOutput = output.substring(0, maxLength) + " ... PRESS SPACE TO READ MORE";
        outputTemp = output.substring(maxLength);
        outputWaiting = true;
      } else {
        visibleOutput = output;
        outputWaiting = false;
      }
    }
  }
Exemplo n.º 4
0
 public void store(String peer_ID, String instance_ID) throws P2PDDSQLException {
   // boolean DEBUG = true;
   if (DEBUG) System.out.println("Address: store: " + peer_ID + " inst=" + instance_ID);
   String params[];
   assert (Util.equalStrings_null_or_not(instance_ID, this.instance_ID_str));
   if (instance_ID_str == null) setInstanceID(instance_ID);
   if (peer_address_ID == null) params = new String[table.peer_address.FIELDS_NOID];
   else params = new String[table.peer_address.FIELDS];
   params[table.peer_address.PA_INSTANCE_ID] = instance_ID_str;
   params[table.peer_address.PA_PEER_ID] = peer_ID;
   params[table.peer_address.PA_TYPE] = pure_protocol;
   params[table.peer_address.PA_DOMAIN] = domain;
   params[table.peer_address.PA_CERTIFIED] = Util.bool2StringInt(certified);
   params[table.peer_address.PA_PRIORITY] = "" + priority;
   params[table.peer_address.PA_CONTACT] = last_contact;
   params[table.peer_address.PA_ARRIVAL] = arrival_date;
   params[table.peer_address.PA_TCP_PORT] = "" + this.tcp_port;
   params[table.peer_address.PA_UDP_PORT] = "" + this.udp_port;
   params[table.peer_address.PA_ADDRESS] = address;
   if (peer_address_ID == null) {
     peer_address_ID =
         ""
             + Application.db.insert(
                 table.peer_address.TNAME, table.peer_address.fields_noID_list, params, DEBUG);
   } else {
     params[table.peer_address.PA_PEER_ADDR_ID] = peer_address_ID;
     Application.db.update(
         table.peer_address.TNAME,
         table.peer_address.fields_noID_list,
         new String[] {table.peer_address.peer_address_ID},
         params,
         DEBUG);
   }
 }
Exemplo n.º 5
0
  /**
   * Parse a line of UNITSPOT.DAT data.
   *
   * @param s
   * @param file_name
   * @param line_nr
   * @return double[]
   */
  public static double[] getCosts(String s, String file_name, int line_nr) {

    double[] ret_val = new double[C.UNIT_SPOT_MOVE];

    Pattern planet_type = Pattern.compile("\"[a-zA-Z]+\"");
    Matcher m = planet_type.matcher(s);
    // skip "planet type"
    Util.testFFErrorAndExit(m.find(), file_name, line_nr);
    // last one is a big string of ten of decimal numbers
    Pattern costs_pattern = Pattern.compile("\"[0-9][0-9\\. ]+[0-9]\"");
    m = costs_pattern.matcher(s);
    //        System.out.println("s = " + s);
    Util.testFFErrorAndExit(m.find(), file_name, line_nr);
    //        String costs = s.substring(m.start() + 1, m.end() - 1);
    String costs = s.substring(m.start() + 1, m.end());
    //        System.out.println("costs = " + costs);
    //        costs_pattern = Pattern.compile("[0-9]+\\.[0-9]+");
    //
    //        m = costs_pattern.matcher(costs);
    //
    //        for (int i = 0; i < C.UNIT_SPOT_MOVE; i++) {
    //            System.out.println("i = " + i);
    //            ret_val[i] = processDoubleVal(costs, m, file_name, line_nr);
    //        }

    processDoubleVals(costs, ret_val, file_name, line_nr);

    return ret_val;
  }
  private void atualizarTabela(List<Servico> listaServico)
      throws ClassNotFoundException, SQLException {

    Double valor = 0.0;
    Double total = 0.0;
    List<TipoServico> tipoServico = mbTipoServico.listarTipoServicos();

    ((DefaultTableModel) table.getModel()).setRowCount(0);
    for (int j = 0; j < tipoServico.size(); j++) {
      for (int k = 0; k < listaServico.size(); k++) {
        if (tipoServico.get(j).getIdtipoServico()
                == listaServico.get(k).getTipoServico().getIdtipoServico()
            && listaServico.get(k).getValor() != 0) {
          valor = (Double) (listaServico.get(k).getValor() + valor);
          ((DefaultTableModel) table.getModel())
              .addRow(
                  new String[] {
                    listaServico.get(k).getVeiculo().getPlaca(),
                    listaServico.get(k).getVeiculo().getOdometro() + "",
                    listaServico.get(k).getFornecedor().getNome(),
                    tipoServico.get(j).getNome() + "",
                    listaServico.get(k).getData2().toString().substring(8, 10)
                        + "/"
                        + listaServico.get(k).getData2().toString().substring(5, 7)
                        + "/"
                        + listaServico.get(k).getData2().toString().substring(0, 4),
                    "" + util.retornaMoeda(valor),
                  });
        }
        total += valor;
        valor = 0.0;
      }
    }
    txtTotal.setText(util.retornaMoeda(total));
  }
Exemplo n.º 7
0
 /**
  * --V0 Address ::= SEQUENCE { address UTF8String, type PrintableString, priority INTEGER IF
  * certified }
  *
  * @return
  */
 public Encoder getEncoder_V0() {
   Encoder enc = new Encoder().initSequence();
   String port = "" + tcp_port;
   // if (tcp_port <= 0) port = "" + udp_port;
   // else port = "" + tcp_port;
   String __address = domain + ":" + port;
   String ___address = pure_protocol + "://" + domain + ":" + port;
   if (!Util.equalStrings_null_or_not(__address, address)
       && !Util.equalStrings_null_or_not(__address + ":" + udp_port, address)
       && !Util.equalStrings_null_or_not(
           ___address, address)) { // eventually I want to migrate to __address from address
     System.out.println(
         "Address:getEncoder_V0: computed="
             + __address
             + " vs expected="
             + address
             + " in="
             + this.toLongString());
     Util.printCallPath("Address:" + this.toLongString());
   }
   enc.addToSequence(new Encoder(address).setASN1Type(Encoder.TAG_UTF8String));
   enc.addToSequence(new Encoder(pure_protocol).setASN1Type(Encoder.TAG_PrintableString));
   if (certified) {
     enc.addToSequence(new Encoder(priority));
   }
   return enc;
 }
Exemplo n.º 8
0
 public Address decode(Decoder dec) {
   Decoder content;
   try {
     content = dec.getContent();
   } catch (ASN1DecoderFail e) {
     e.printStackTrace();
     return this;
   }
   if (content.getTypeByte() != DD.TAG_AC0) {
     if (content.getTypeByte() == Encoder.TAG_UTF8String) version_structure = V0;
     else if (content.getTypeByte() == Encoder.TAG_PrintableString) version_structure = V1;
     else {
       Util.printCallPath("Type=" + content.getTypeByte());
       throw new RuntimeException("Unknow Address version");
     }
   } else {
     if (DEBUG) System.out.println("Address:decode tag=" + content.getTypeByte());
     version_structure = content.getFirstObject(true).getInteger().intValue();
   }
   switch (version_structure) {
     case V0:
       if (DEBUG) System.out.println("Address:dec:V0");
       return decode_V0(content);
     case V1:
       if (DEBUG) System.out.println("Address:dec:V1");
       return decode_V1(content);
     case V2:
     case V3:
       if (DEBUG) System.out.println("Address:dec:V2");
       return decode_V2(content);
     default:
       Util.printCallPath("Type not yet supported=" + version_structure);
       throw new RuntimeException("Unknow Address version:" + version_structure);
   }
 }
Exemplo n.º 9
0
    long update() throws P2PDDSQLException {
      // System.out.println("=================================>update "+this);
      if (registered_ID <= 0) return this.storeNew();
      D_Directory_Storage.need_saving_remove(globalIDhash, instance); // need_saving = false;
      String params[] = new String[table.registered.fields_list.length];
      params[table.registered.REG_GID] = globalID;
      params[table.registered.REG_GID_HASH] = globalIDhash;
      params[table.registered.REG_INSTANCE] = instance;
      params[table.registered.REG_CERT] =
          (certificate.length == 0) ? null : Util.stringSignatureFromByte(certificate);
      params[table.registered.REG_ADDR] = Address.joinAddresses(addresses);
      params[table.registered.REG_SIGN] =
          (signature.length == 0) ? null : Util.stringSignatureFromByte(signature);
      if (timestamp == null) timestamp = Util.CalendargetInstance();
      params[table.registered.REG_TIME] =
          Encoder.getGeneralizedTime(
              timestamp); // (Util.CalendargetInstance().getTimeInMillis()/1000)+"";
      params[table.registered.REG_ID] = Util.getStringID(this.registered_ID);

      Application.db_dir.update(
          table.registered.TNAME,
          table.registered.fields_noID_list,
          new String[] {table.registered.registeredID},
          params,
          DEBUG);
      //					new
      // String[]{table.registered.global_peer_ID,table.registered.certificate,table.registered.addresses,table.registered.signature,table.registered.timestamp},
      return registered_ID;
    }
Exemplo n.º 10
0
 @Override
 public boolean equals(Object o) {
   if (!(o instanceof KEY)) return false;
   KEY k = (KEY) o;
   if (!Util.equalStrings_null_or_not(hash, k.hash)) return false;
   if (!Util.equalStrings_null_or_not(instance, k.instance)) return false;
   return true;
 }
Exemplo n.º 11
0
 public void salvar(Loja loja) {
   try {
     this.dao.salvar(loja);
     util.Util.aviso("loja salva");
   } catch (Exception e) {
     util.Util.aviso("erro: " + e.getCause().toString());
   }
 }
Exemplo n.º 12
0
 public static Calendar getUpdateDate(Calendar serverDate, Calendar localDate) {
   String lDate = Util.getGeneralizedTime();
   Calendar newLocalDate = Util.getCalendar(lDate);
   long timeMil = 0;
   if (serverDate.compareTo(localDate) == 1)
     timeMil = serverDate.getTimeInMillis() - localDate.getTimeInMillis();
   if (DEBUG) System.out.println("Time def btw server and client: " + timeMil);
   return Util.incCalendar(newLocalDate, (int) timeMil);
 }
Exemplo n.º 13
0
  private void gen4() {
    int totalNum = Util.getRandomNumberInRange(5, 8);
    int duplicates = Util.getRandomNumberInRange(2, 4);

    list.add(new Int(totalNum));
    list.add(new Int(duplicates));

    int answer = Util.perm(totalNum, totalNum) / Util.factorial(duplicates);
    ans = new Int(answer);
  }
Exemplo n.º 14
0
 public String toString() {
   return "D_ReleaseQuality [\n"
       + "\n    _quality="
       + Util.concat(_quality, "  ||| ")
       + "\n    subQualities="
       + Util.concat(subQualities, "  ||| ")
       + "\n    description="
       + description
       + "\n]";
 }
Exemplo n.º 15
0
 /**
  * [<PROT>://]domain:...:...:....:<active_int_boolean>[:...]
  *
  * @param address
  * @return
  */
 public static boolean getActive(String address) {
   String domain;
   String[] protos = address.split(Pattern.quote(ADDR_PROT_INTERN_SEP));
   if (protos.length > 1) domain = protos[1];
   else domain = protos[0];
   String[] ports = domain.split(Pattern.quote(ADDR_PART_SEP));
   if (DEBUG)
     System.out.println("Address:getActive " + domain + " ports=" + Util.concat(ports, "=="));
   if (ports.length < 5) return true;
   return Util.stringInt2bool(ports[4], false);
 }
Exemplo n.º 16
0
 public void countGrams(int n, HashMap<String, Integer> count, boolean word) {
   List<String> nGram = new ArrayList<String>();
   int i;
   for (i = 0; i < n; i++) nGram.add(pairs.get(i).getContent(word));
   for (; i < pairs.size(); i++) {
     Util.incrementMap(count, nGram.toString());
     nGram.add(pairs.get(i).getContent(word));
     nGram.remove(0);
   }
   Util.incrementMap(count, nGram.toString());
 }
Exemplo n.º 17
0
  public void AtualizaComboData() {
    try {

      lstServicoData =
          mbServico.ServicoPorData(util.getCMBData(cmbDataInicio), util.getCMBData(cmbDataFinal));

      if (lstServicoData != null) {

        List<Veiculo> lstVeiculo = new ArrayList<>();
        cmbPlaca.removeAllItems();
        for (int i = 0; i < lstServicoData.size(); i++) {
          if (!lstVeiculo.contains(lstServicoData.get(i).getVeiculo())) {
            lstVeiculo.add(lstServicoData.get(i).getVeiculo());
            cmbPlaca.addItem(lstServicoData.get(i).getVeiculo().getPlaca());
          }
        }

        cmbPlaca.insertItemAt("TODOS", 0);
        cmbPlaca.setSelectedIndex(0);

        List<Veiculo> listaVeiculo = mbVeiculo.VeiculoPorServico(lstServicoData);
        List<Unidade> listaUnidade = mbUnidade.UnidadesPorVeiculos(listaVeiculo);
        List<Modelo> listaModelo = mbModelo.ModeloPorVeiculo(listaVeiculo);
        List<Marca> listaMarca = mbMarca.MarcaModelo(listaModelo);
        List<Motorista> listaMotorista = mbMotorista.MotoristaServico(lstServicoData);
        List<TipoServico> listaTipoServico = mbTipoServico.TipoServicoPorServico(lstServicoData);
        List<Fornecedor> listaFornecedor = mbFornecedor.FornecedorServico(lstServicoData);

        // cmbUnidade.removeAllItems();
        // AtualizaCombo(cmbUnidade, listaUnidade);

        cmbTipoServico.removeAllItems();
        AtualizaCombo(cmbTipoServico, listaTipoServico);

        cmbFornecedor.removeAllItems();
        AtualizaCombo(cmbFornecedor, listaFornecedor);

        cmbMarca.removeAllItems();
        AtualizaCombo(cmbMarca, listaMarca);

        cmbModelo.removeAllItems();
        AtualizaCombo(cmbModelo, listaModelo);

        cmbMotorista.removeAllItems();
        AtualizaCombo(cmbMotorista, listaMotorista);
      }
    } catch (ClassNotFoundException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    } catch (SQLException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
Exemplo n.º 18
0
 /**
  * Retorna uma String com o valores concatenados através do conector, passado como argumento.
  *
  * @param valor1
  * @param valor2
  * @param conector
  * @return String
  */
 public static String getValorConcatenado(String valor1, String valor2, String conector) {
   StringBuffer str = new StringBuffer();
   if (!Util.isValorVazio(valor1)) {
     str.append(valor1);
   }
   str.append(conector);
   if (!Util.isValorVazio(valor2)) {
     str.append(valor2);
   }
   return str.toString();
 }
Exemplo n.º 19
0
  @Override
  public void create() {
    Arrays.fill(heights, defaultHeight);

    Core.interval(.0005).onEvent(this::step).addChild(this);

    //        onUpdate(dt -> {
    //            Util.repeat(detail, i -> heights[i] += dt * speeds[i]);
    //            Util.repeat(detail - 1, i -> {
    //                deltas[i] = heights[i + 1] - heights[i];
    //                speeds[i] += deltas[i] * dt * 3000;
    //                speeds[i + 1] -= deltas[i] * dt * 3000;
    //            });
    //            Util.repeat(detail, i -> speeds[i] = speeds[i] * Math.pow(.1, dt * dt) + dt * 10 *
    // (defaultHeight - heights[i]));
    //            Util.repeat(detail - 1, i -> {
    //                heights[i] += deltas[i] * dt;
    //                heights[i + 1] -= deltas[i] * dt;
    //            });
    //        });
    onRender(
        () -> {
          glDisable(GL_TEXTURE_2D);
          glBegin(GL_TRIANGLE_STRIP);
          Util.repeat(
              detail,
              i -> {
                double x = position.x + width * (2. * i / detail - 1);
                new Color4(0, 0, .6).glColor();
                new Vec2(x, bottom).glVertex();
                new Color4(0, .2, 1).glColor();
                new Vec2(x, heights[i]).glVertex();
              });
          glEnd();
        });
    Core.renderLayer(1)
        .onEvent(
            () -> {
              glDisable(GL_TEXTURE_2D);
              glBegin(GL_TRIANGLE_STRIP);
              Util.repeat(
                  detail,
                  i -> {
                    double x = position.x + width * (2. * i / detail - 1);
                    new Color4(0, 0, .6, .5).glColor();
                    new Vec2(x, bottom).glVertex();
                    new Color4(0, .2, 1, .5).glColor();
                    new Vec2(x, heights[i]).glVertex();
                  });
              glEnd();
            })
        .addChild(this);
  }
Exemplo n.º 20
0
  public static void newUpload() throws IOException {
    models.Upload upload = new models.Upload();
    upload.owner = getUser();
    upload.created = Util.currentTimeInUTC();
    upload.create();
    File uploadDir = Util.getUploadDir(upload.id);
    if (!uploadDir.mkdirs())
      throw new RuntimeException("Failed to create upload dir " + uploadDir.getAbsolutePath());

    MyCache.evictUploadsForOwner(upload.owner);

    view(upload.id);
  }
Exemplo n.º 21
0
  private static byte[] _monitor_handleAnnouncement(
      DirectoryAnnouncement da, String detected_sa, DBInterface db, boolean storeNAT)
      throws P2PDDSQLException {
    if (DEBUG) System.out.println("Got announcement: " + da);
    if (da.getGID() != null)
      db.deleteNoSyncNULL(
          table.registered.TNAME,
          new String[] {table.registered.global_peer_ID, table.registered.instance},
          new String[] {da.getGID(), da.instance},
          DEBUG);
    else
      db.deleteNoSyncNULL(
          table.registered.TNAME,
          new String[] {table.registered.global_peer_ID_hash, table.registered.instance},
          new String[] {da.getGIDH(), da.instance},
          DEBUG);
    String adr = da.address.addresses();
    // da.address.domain+":"+da.address.port+ADDR_SEP+detected_sa,
    if (storeNAT) adr = Address.joinAddresses(detected_sa, adr);

    String params[] = new String[table.registered.fields_noID_list.length];
    params[table.registered.REG_GID] = da.getGID();
    params[table.registered.REG_GID_HASH] = da.getGIDH();
    params[table.registered.REG_INSTANCE] = da.instance;
    params[table.registered.REG_BRANCH] = da.branch;
    params[table.registered.REG_AGENT_VERSION] = Util.getVersion(da.agent_version);
    params[table.registered.REG_NAME] = da.name;
    params[table.registered.REG_CERT] =
        (da.certificate.length == 0) ? null : Util.stringSignatureFromByte(da.certificate);
    params[table.registered.REG_ADDR] = adr;
    params[table.registered.REG_SIGN] =
        (da.signature.length == 0) ? null : Util.stringSignatureFromByte(da.signature);
    Calendar timestamp = da.date;
    if (timestamp == null) timestamp = Util.CalendargetInstance();
    params[table.registered.REG_TIME] =
        Encoder.getGeneralizedTime(
            timestamp); // (Util.CalendargetInstance().getTimeInMillis()/1000)+"";

    long id =
        db.insert(
            table.registered.TNAME,
            table.registered.fields_noID_list,
            //				new
            // String[]{table.registered.global_peer_ID,table.registered.certificate,table.registered.addresses,table.registered.signature,table.registered.timestamp},
            params);
    if (DEBUG) out.println("DirectoryServer: mon_handleAnnoncement:inserted with ID=" + id);
    byte[] answer = new DirectoryAnnouncement_Answer(detected_sa).encode();
    if (DEBUG) out.println("sending answer: " + Util.byteToHexDump(answer));
    return answer;
  }
Exemplo n.º 22
0
 /** Adjust city loyalty, create rebels, place rebels. */
 public void adjustCityLoyalty() {
   List<Structure> cities = game.getStructures();
   List<Structure> fully_rebel = new LinkedList<>();
   for (Structure city : cities) {
     if (city.owner == game.getTurn()) {
       game.adjustCityLoyalty(city, calculateCityLoyalty(tax_rate, efs_ini, game));
       if (city.loyalty < C.LOYALTY_REBEL_LIMIT) {
         int rebel_pop = 0;
         for (int i = city.health; i > 0; i -= 10) {
           float prob = (1 - city.loyalty / C.LOYALTY_REBEL_LIMIT) * C.LOYALTY_REBEL_HIGH_P;
           Util.dP(prob);
           if (game.getRandom().nextFloat() < prob) {
             rebel_pop += 10;
           }
         }
         if (rebel_pop == 0) {
           continue;
         }
         //                    if (rebel_pop > city.health) {
         //                        rebel_pop = city.health;
         //                    }
         game.adjustCityHealth(city, city.health - rebel_pop);
         LinkedList<Unit> rebels = new LinkedList<>();
         Util.dP(rebel_pop);
         for (int i = rebel_pop; i > 0; i -= 10) {
           rebels.add(
               new Unit(
                   city.p_idx,
                   city.x,
                   city.y,
                   C.NEUTRAL,
                   C.NEUTRAL,
                   C.PARTISAN_UNIT_TYPE,
                   0,
                   -1,
                   -1,
                   game));
         }
         placeRebels(rebels, Util.FindHexesAround.Hextype.LAND);
         if (city.health <= 0) {
           fully_rebel.add(city);
         }
       }
     }
   }
   for (Structure city : fully_rebel) { // this here or else ConcurrentModificationException
     game.destroyCity(city.p_idx, city.x, city.y);
   }
 }
Exemplo n.º 23
0
 public static int getTCP(String address) {
   String domain;
   String[] protos = address.split(Pattern.quote(ADDR_PROT_INTERN_SEP));
   if (DEBUG)
     System.out.println(
         "Address:getTCP: adr=" + address + " splits=" + Util.concat(protos, " - "));
   if (protos.length > 1) domain = protos[1];
   else domain = protos[0];
   String[] ports = domain.split(Pattern.quote(ADDR_PART_SEP));
   if (DEBUG)
     System.out.println("Address:getTCP: dom=" + domain + " splits=" + Util.concat(ports, " - "));
   if (ports.length < 2) return -1;
   if ((ports[1] == null) || (ports[1].length() == 0)) return 0;
   return Integer.parseInt(ports[1]);
 }
Exemplo n.º 24
0
  public static void deleteFile(Long id, String path, boolean returnToBrowse) throws IOException {
    models.Upload upload = Uploads.getUpload(id);
    File uploadsDir = Util.getUploadDir(upload.id);
    File file = new File(uploadsDir, path);

    deleteFileImpl(path, file, uploadsDir, upload);

    if (returnToBrowse) {
      File parent = file.getParentFile();
      String parentPath = JavaExtensions.relativeTo(parent, upload);
      // if we do viewFile directly we get silly %2F escapes in the URL
      redirect(Util.viewPublicUploadUrl(upload, parentPath));
    } else {
      Uploads.view(id);
    }
  }
Exemplo n.º 25
0
 @Override
 public String toString() {
   String r = "DirAnsInst [";
   r += "\t\ninstance=" + instance;
   r += "\t\nbranch=" + branch;
   r += "\t\nagent_version=" + Util.concat(agent_version, ".", "NULL");
   r += "\t\nsignature_peer=" + Util.byteToHexDump(signature_peer);
   r += "\t\ndate_last_contact=" + Encoder.getGeneralizedTime(date_last_contact);
   if (instance_terms != null) {
     for (int i = 0; i < instance_terms.length; i++) {
       r += "\t\ninstance_terms=" + instance_terms[i];
     }
   }
   r += "\t\n addr=" + Util.concat(addresses, " , ", "NULL");
   return r + "]";
 }
Exemplo n.º 26
0
 public String toRecString(boolean _parent) {
   String r = "D_DirEntry[";
   r += "\n\t" + "known=" + known + " root=" + root;
   r += "\n\t" + "ID=" + registered_ID;
   r += "\n\t" + "GID=" + globalID;
   r += "\n\t" + "GIDH=" + globalIDhash;
   r += "\n\t" + "inst=" + instance;
   r += "\n\t" + "cert=" + certificate;
   r += "\n\t" + "addr=" + Util.concat(addresses, "\n\t\t", "NULL");
   r += "\n\t" + "sign=" + Util.byteToHexDump(signature);
   r += "\n\t" + "time=" + Encoder.getGeneralizedTime(timestamp);
   if (_parent && (parent != null) && (parent != this))
     r += "\n\t" + "parent=" + parent.toSummary();
   r += "\n\t" + "instances=" + Util.concat(instances.values(), "}{", "NULL") + "\n]";
   return r;
 }
Exemplo n.º 27
0
  public static void uploadRepo(Long id, @Required File repo, String module, String version)
      throws ZipException, IOException {
    models.Upload upload = Uploads.getUpload(id);
    File uploadsDir = Util.getUploadDir(upload.id);

    if (validationFailed()) {
      Uploads.uploadRepoForm(id);
    }

    String name = repo.getName().toLowerCase();

    if (name.endsWith(".zip")) uploadZip(repo, null, uploadsDir);
    else {
      boolean found = false;
      for (String postfix : SupportedExtensions) {
        if (name.endsWith(postfix)) {
          uploadArchive(repo, postfix, uploadsDir, module, version, id);
          found = true;
          break;
        }
      }
      if (!found)
        error(
            HttpURLConnection.HTTP_BAD_REQUEST,
            "Invalid uploaded file (must be zip, car, jar or src)");
    }

    Uploads.view(id);
  }
Exemplo n.º 28
0
  /**
   * Called with a parameter "da" already verified and validated as new and possibly signed
   *
   * @param da
   * @param detected_sa
   * @param db
   * @param storeNAT
   * @return
   * @throws P2PDDSQLException
   */
  private static DirectoryAnnouncement_Answer _monitored_handleAnnouncement(
      DirectoryAnnouncement da,
      Address detected_sa,
      DBInterface db,
      boolean storeNAT,
      boolean TCP_not_UDP)
      throws P2PDDSQLException {

    if (DEBUG)
      System.out.println("DirectoryServer: _monitored_handleAnnouncement: Got announcement: " + da);
    if (da.address._addresses == null) {
      if (DEBUG)
        System.out.println(
            "DirectoryServer: _monitored_handleAnnouncement: Got empty announcement: "
                + da
                + " detected="
                + detected_sa);
    }

    String globalID = da.getGID();
    String globalIDhash = da.getGIDH();
    String instance = da.instance;

    // only use old NAT is current message is TCP
    if (TCP_not_UDP) {
      D_DirectoryEntry old_entry = DirectoryServerCache.getEntry(globalID, globalIDhash, instance);
      if (old_entry != null) {
        Address old_detected_NAT = old_entry.getNATAddress();
        if (detected_sa == null) detected_sa = old_detected_NAT;
        else {
          if (old_detected_NAT != null) {
            if (Address.sameDomain(detected_sa, old_detected_NAT)) {
              detected_sa = old_detected_NAT;
            } else {
              if (DEBUG)
                System.out.println(
                    "DirectoryServer: _monitored_handleAnnouncement: diff NATS: n="
                        + detected_sa
                        + " o="
                        + old_detected_NAT);
            }
          }
        }
      }
    }

    if (detected_sa != null)
      da.address._addresses = prependAddress(da.address._addresses, detected_sa);
    DirectoryServerCache.loadAndSetEntry(da, TCP_not_UDP);
    if (DEBUG)
      System.out.println(
          "DirectoryServer: _monitored_handleAnnouncement: loaded="
              + DirectoryServerCache.getEntry(globalID, globalIDhash, instance));

    // byte[] answer =
    return new DirectoryAnnouncement_Answer(Util.getString(detected_sa));
    // if (DEBUG) out.println("DS:_monitored_handleAnnouncement: sending answer:
    // "+Util.byteToHexDump(answer));
    // return answer;
  }
Exemplo n.º 29
0
 /**
  * Place rebels, fill hexes starting from closest available hex. Return true if all rebels placed,
  * false if we run out of planet hexes before all rebels are placed.
  *
  * @param rebels list of units to place
  * @return true iff all rebels placed
  */
 private boolean placeRebels(LinkedList<Unit> rebels, Util.FindHexesAround.Hextype type) {
   Hex center = null;
   Hex target = null;
   Hex prev_target = null;
   Util.FindHexesAround hex_finder = null;
   Point p = new Point(C.NEUTRAL, C.NEUTRAL);
   int p_idx = -1;
   int x = -1;
   int y = -1;
   while (!rebels.isEmpty()) {
     Unit unit = rebels.pop();
     if (unit.y != y || unit.x != x || unit.p_idx != p_idx) {
       y = unit.y;
       x = unit.x;
       p_idx = unit.p_idx;
       addMessage(
           new Message(
               "Rebellion on " + game.getPlanet(p_idx).name + " " + x + "," + y + "!",
               C.Msg.REBELLION,
               game.getYear(),
               game.getPlanet(p_idx)));
     }
     Hex hex_tmp = game.getHexFromPXY(unit.p_idx, unit.x, unit.y);
     if (!hex_tmp.equals(center)) {
       center = hex_tmp;
       hex_finder =
           new Util.FindHexesAround(center, C.NEUTRAL, type, game.getPlanet(p_idx).tile_set_type);
       prev_target = target;
       target = hex_finder.next();
     }
     while (target != null && Util.stackSize(target.getStack()) >= C.STACK_SIZE) {
       target = hex_finder.next();
     }
     prev_target = spot(prev_target, target);
     if (target == null) {
       return false;
     }
     if (unit.carrier == null) {
       if (unit.type_data.cargo > 0 && unit.cargo_list.size() > 0) {
         List<Unit> tmp = new LinkedList<>();
         tmp.addAll(unit.cargo_list);
         for (Unit u : tmp) {
           unit.disembark(u);
           center.addUnit(u);
         }
       }
     } else {
       Unit u = unit.carrier;
       u.disembark(unit);
     }
     center.getStack().remove(unit);
     game.changeOwnerOfUnit(p, unit);
     game.relocateUnit(false, unit.p_idx, target.getX(), target.getY(), unit);
     target.addUnit(unit);
     game.getUnits().add(unit);
     // Util.dP(" hex " + target.getX() + "," + target.getY());
   }
   spot(target, prev_target);
   return true;
 }
Exemplo n.º 30
0
  public static void main(String[] args) {
    // Here modifier is not permitted and only final is allowed
    Student[] lab2 = new Student[40]; // Create an array of 40 students
    int count = 0; // To store the number of students
    try { // Read file from current project directory
      // Students' number more than 40. If you want to test this case, uncomment next.
      lab2 = Util.readFile("src/More_than_40.txt", lab2);

      // Students' number less than 40. If you want to test this case, uncomment next.
      // lab2 = Util.readFile("src/Less_than_40.txt",lab2);

      // Students' number equals to 40. If you want to test this case, uncomment next.
      // lab2 = Util.readFile("src/Equals_to_40.txt",lab2);
    } catch (FixedException e) { // To handle number exceed exception
      e.printStackTrace();
    } catch (IOException e) { // To handle IO exception
      e.printStackTrace();
    }
    AnalyticModel analysis = new AnalyticModel();
    analysis.findLowest(lab2); // Find the lowest of 5 quizzes among 40 students
    analysis.findHighest(lab2); // Find the highest of 5 quizzes among 40 students
    analysis.findAvg(lab2); // Find the average of 5 quizzes among 40 students
    System.out.println("Stud\tQu1\tQu2\tQu3\tQu4\tQu5"); // Display grades information
    while (lab2[count] != null) {
      lab2[count].displayInfo(); // Display students information
      count++;
      if (count == 40) break;
    }
    analysis.displayGrades(); // Display analytic statistics
  }