/**
   * 批量删除指定名称的布局
   *
   * @param mapLayoutNames 布局名称
   */
  public static void deleteMapLayout(String[] mapLayoutNames) {
    try {
      String message = "";
      if (mapLayoutNames.length == 1) {
        message = CoreProperties.getString("String_LayoutDelete_Confirm");
        message =
            message
                + System.lineSeparator()
                + String.format(
                    CoreProperties.getString("String_LayoutDelete_Confirm_One"), mapLayoutNames[0]);
      } else {
        message = CoreProperties.getString("String_LayoutDelete_Confirm");
        message =
            message
                + System.lineSeparator()
                + String.format(
                    CoreProperties.getString("String_LayoutDelete_Confirm_Multi"),
                    mapLayoutNames.length);
      }
      if (!Objects.equals(message, "")
          && (JOptionPaneUtilties.showConfirmDialog(message) == JOptionPane.OK_OPTION)) {

        for (String mapLayoutName : mapLayoutNames) {
          Application.getActiveApplication().getWorkspace().getLayouts().remove(mapLayoutName);
        }
      }
    } catch (Exception ex) {
      Application.getActiveApplication().getOutput().output(ex);
    }
  }
 @Override
 public String toString() {
   StringBuilder builder = new StringBuilder();
   builder.append("TextClassifier [maxNumberAllowedTerms=");
   builder.append(maxNumberAllowedTerms);
   builder.append(", calculatedInteresstingIDFIndexForFilter=");
   builder.append(calculatedInteresstingIDFIndexForFilter);
   builder.append(", firstIDFIndexForTermInAllDocClasses=");
   builder.append(firstIDFIndexForTermInAllDocClasses);
   builder.append(", docClasses=");
   builder.append(docClasses.keySet());
   builder.append(", trainingFinished=");
   builder.append(trainingFinished);
   builder.append(", keepDetailsOfDocumentsInClasses=");
   builder.append(keepDetailsOfDocumentsInClasses);
   builder.append(",").append(System.lineSeparator());
   builder.append("docClassFrequencies=");
   builder.append(docClassFrequencyPerTerm);
   builder.append(",").append(System.lineSeparator());
   builder.append("termIDFs=");
   builder.append(docClassTermIDFs);
   builder.append(",").append(System.lineSeparator());
   builder.append("lastClassificationResult=");
   builder.append(lastClassificationResult);
   builder.append(", lastClassifiedBag=");
   builder.append(lastClassifiedBag);
   builder.append("]");
   return builder.toString();
 }
  @Override
  public String getCsvString(LocalDate date) {
    Status status = creationDate.isEqual(date) ? Status.Creation : Status.Editing;
    int articleCountForDate = 0;

    final StringBuilder articleStringsBuilder = new StringBuilder();
    for (ArticleOutput articleOutput : articleOutputList) {
      String articleCsvString = articleOutput.getCsvString(date);
      if (!articleCsvString.isEmpty()) {
        articleStringsBuilder.append(articleCsvString);
        articleCountForDate++;
      }
    }

    final StringBuilder csvStringBuilder = new StringBuilder();
    if (status.equals(Status.Creation)
        || (status.equals(Status.Editing) && articleCountForDate != 0)) {
      csvStringBuilder.append("ID,Platform,TLD,Status,Article Amount:");
      csvStringBuilder.append(System.lineSeparator());
      csvStringBuilder.append(id).append(",");
      csvStringBuilder.append(platform).append(",");
      csvStringBuilder.append(tld).append(",");
      csvStringBuilder.append(status).append(",");
      csvStringBuilder.append(articleCountForDate);
      csvStringBuilder.append(System.lineSeparator());
      csvStringBuilder.append(articleStringsBuilder.toString());
    }

    return csvStringBuilder.toString();
  }
  private void checkStates(final State[] ss) {
    boolean ok = false;
    for (int index = 0; index < ss.length; ++index) {
      final State s = ss[index];
      if (Objects.equals(s, this.state)) {
        ok = true;
        break;
      }
    }

    if (!ok) {
      this.text.setLength(0);
      this.text.append("Failed to call shader correctly.");
      this.text.append(System.lineSeparator());
      this.text.append("Expected one of shader states: ");
      for (int index = 0; index < ss.length; ++index) {
        final State s = ss[index];
        this.text.append(s);
        this.text.append(" ");
      }
      this.text.append(System.lineSeparator());
      this.text.append("Actual shader state:   ");
      this.text.append(this.state);
      this.text.append(System.lineSeparator());
      final String m = this.text.toString();
      this.text.setLength(0);
      throw new IllegalStateException(m);
    }
  }
Exemple #5
1
    @Override
    public void run() {
      while (true) {
        if (istWindows()) aktuell = holeLaufwerkeWindows();
        else aktuell = holeLaufwerkeUnix();

        if (initial.size() != aktuell.size()) {
          if (!initial.containsAll(aktuell)) {
            neuesLaufwerk = holePathVonNeuemLaufwerk(initial, aktuell);
            textArea.append("Neues Laufwerk endeckt:  " + neuesLaufwerk + System.lineSeparator());
            this.initial = (ArrayList<Path>) aktuell.clone();
            neuesLaufwerkDialog();

          } else {
            this.initial = (ArrayList<Path>) aktuell.clone();
            textArea.append("Laufwerk wurde entfernt" + System.lineSeparator());
          }
        }

        try {
          Thread.sleep(5000);
        } catch (InterruptedException e) {
          System.out.println("Laufwerksprüfung wird abgebrochen");
        }
      }
    }
  /*
    Función que convierte un Map Java en un array asociativo JavaScript
    El Map de origen es arrayTraducciones
    El array de destino es:

      var palabras = new Array();
      palabras['ES'] = new Array('Nombre', 'Dirección', 'Fecha de nacimiento');
      palabras['EN'] = new Array('Name', 'Address', 'Date of birth');
      palabras['FR'] = new Array('Nom', 'Adresse', 'Date de naissnace');
  */
  private String datosJavaAJavaScript() {
    String texto = "";
    if (!arrayTraducciones.isEmpty()) {
      texto +=
          "// Este archivo JavaScript ha sido generado por un script Java" + System.lineSeparator();
      texto +=
          "// Es la traducción de un Map Java a un array asociativo JavaScript"
              + System.lineSeparator();
      texto += "var palabras = new Array();" + System.lineSeparator();
      for (Map.Entry<String, String[]> elemento : arrayTraducciones.entrySet()) {
        String clave = elemento.getKey();
        texto += "palabras['" + clave + "'] = new Array(";
        String[] valor = elemento.getValue();
        for (String dato : valor) {
          texto += "'" + dato + "', ";
        }
        texto =
            texto.substring(
                0,
                texto.length()
                    - 2); // al final del último elemento se eliminan el espacio y la coma
        texto += ");" + System.lineSeparator();
      }
    }
    return texto;
  }
 public String toString() {
   StringBuilder sb = new StringBuilder();
   sb.append(Integer.toString(books.size()));
   sb.append(System.lineSeparator());
   books.forEach((Book book) -> sb.append(book.toString() + System.lineSeparator()));
   return sb.toString();
 }
  /**
   * Add a file to the Lucene index (and generate a xref file)
   *
   * @param file The file to add
   * @param path The path to the file (from source root)
   * @throws java.io.IOException if an error occurs
   */
  private void addFile(File file, String path) throws IOException {
    try (InputStream in = new BufferedInputStream(new FileInputStream(file))) {
      FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, path);
      for (IndexChangedListener listener : listeners) {
        listener.fileAdd(path, fa.getClass().getSimpleName());
      }
      fa.setCtags(ctags);
      fa.setProject(Project.getProject(path));

      Document d;
      try {
        d = analyzerGuru.getDocument(file, in, path, fa);
      } catch (Exception e) {
        log.log(
            Level.INFO,
            "Skipped file ''{0}'' because the analyzer didn''t " + "understand it.",
            path);
        StringBuilder stack = new StringBuilder();
        for (StackTraceElement ste : e.getStackTrace()) {
          stack.append(ste.toString()).append(System.lineSeparator());
        }
        StringBuilder sstack = new StringBuilder();
        for (Throwable t : e.getSuppressed()) {
          for (StackTraceElement ste : t.getStackTrace()) {
            sstack.append(ste.toString()).append(System.lineSeparator());
          }
        }
        log.log(
            Level.FINE,
            "Exception from analyzer {0}: {1} {2}{3}{4}{5}{6}",
            new String[] {
              fa.getClass().getName(),
              e.toString(),
              System.lineSeparator(),
              stack.toString(),
              System.lineSeparator(),
              sstack.toString()
            });
        return;
      }

      writer.addDocument(d, fa);
      Genre g = fa.getFactory().getGenre();
      if (xrefDir != null && (g == Genre.PLAIN || g == Genre.XREFABLE)) {
        File xrefFile = new File(xrefDir, path);
        // If mkdirs() returns false, the failure is most likely
        // because the file already exists. But to check for the
        // file first and only add it if it doesn't exists would
        // only increase the file IO...
        if (!xrefFile.getParentFile().mkdirs()) {
          assert xrefFile.getParentFile().exists();
        }
        fa.writeXref(xrefDir, path);
      }
      setDirty();
      for (IndexChangedListener listener : listeners) {
        listener.fileAdded(path, fa.getClass().getSimpleName());
      }
    }
  }
  public static String getStringFromClob(Clob clob, int bufferSize) {

    if (clob == null) {
      return null;
    }

    StringBuilder string = new StringBuilder();

    BufferedReader bufferedReader = null;

    try {
      bufferedReader = new BufferedReader(clob.getCharacterStream());

      int charactersReadCount = 0;
      char[] buffer = new char[bufferSize];

      while ((charactersReadCount = bufferedReader.read(buffer)) > 0) {
        string.append(buffer, 0, charactersReadCount);
      }
    } catch (Exception e) {
      logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
    } finally {
      try {
        if (bufferedReader != null) {
          bufferedReader.close();
        }
      } catch (Exception e) {
        logger.error(e.toString() + System.lineSeparator() + StackTrace.getStringFromStackTrace(e));
      }
    }

    return string.toString();
  }
  /**
   * Test firl with multiple lines
   *
   * @throws CruiseControlException
   * @throws IOException
   */
  public final void testFileMultiline() throws CruiseControlException, IOException {
    final File inpFile = filesToDelete.add(this);
    final File outFile = filesToDelete.add(this);
    final WriterBuilder writerObj = new WriterBuilder();
    final DataBuffer buff = new DataBuffer();

    // <writer file="..." />
    writerObj.setFile(outFile.getAbsolutePath());
    // <file/>
    final WriterBuilder.File f = newFile(writerObj);
    f.setFile(inpFile.getAbsolutePath());
    // Write message to the file
    buff.add(
        "1st line"
            + System.lineSeparator()
            + System.lineSeparator()
            + System.lineSeparator()
            + "2nd line"
            + System.lineSeparator()
            + "3rd line"
            + System.lineSeparator(),
        inpFile);

    writerObj.validate();
    writerObj.build(buildMap, buildProgress);
    // Assert. The output file is in Latin2 encoding
    assertReaders(buff.getChars(), new InputStreamReader(new FileInputStream(outFile)));
  }
  @Override
  public void writeArtifactContent(BufferedWriter bufferedWriter) throws IOException {
    CapitalizationTypes encapsulationCapitalization = getOptions().getCapitalization();
    String getterPrefix = getOptions().getGetterPrefix();
    String setterPrefix = getOptions().getSetterPrefix();

    setCurrentIndent(1);

    for (SchemaField schemaField : this.getSchema().getFields()) {
      bufferedWriter
          .append(getIndent())
          .append(schemaField.getType())
          .append(" ")
          .append(capitalizeName(getterPrefix, schemaField.getName(), encapsulationCapitalization))
          .append("();")
          .append(System.lineSeparator());
      if (!_isReadOnly) {
        bufferedWriter
            .append(getIndent())
            .append("void ")
            .append(
                capitalizeName(setterPrefix, schemaField.getName(), encapsulationCapitalization))
            .append("(")
            .append(schemaField.getType())
            .append(" ")
            .append(schemaField.getName())
            .append(");")
            .append(System.lineSeparator());
      }
    }
  }
  @Test
  public void testInteropolateDependencies() throws Exception {
    final Model model =
        TestUtils.resolveModelResource(RESOURCE_BASE, "infinispan-bom-8.2.0.Final.pom");

    Project project = new Project(model);
    PropertyInterpolator pi = new PropertyInterpolator(project.getModel().getProperties(), project);

    String nonInterp = "", interp = "";
    for (Dependency d : project.getManagedDependencies()) {
      nonInterp +=
          (d.getGroupId().equals("${project.groupId}") ? project.getGroupId() : d.getGroupId())
              + ":"
              + (d.getArtifactId().equals("${project.artifactId}")
                  ? project.getArtifactId()
                  : d.getArtifactId())
              + System.lineSeparator();

      interp +=
          pi.interp(
                  d.getGroupId().equals("${project.groupId}")
                      ? project.getGroupId()
                      : d.getGroupId())
              + ":"
              + pi.interp(
                  d.getArtifactId().equals("${project.artifactId}")
                      ? project.getArtifactId()
                      : d.getArtifactId())
              + System.lineSeparator();
    }
    assertTrue(nonInterp.contains("${"));
    assertFalse(interp.contains("${"));
  }
  @Test
  public void testPrintAMethodWithGeneric() throws Exception {
    final Launcher launcher = new Launcher();
    final Factory factory = launcher.getFactory();
    factory.getEnvironment().setAutoImports(true);
    final SpoonCompiler compiler = launcher.createCompiler();
    compiler.addInputSource(new File("./src/test/java/spoon/test/prettyprinter/testclasses/"));
    compiler.build();

    final CtClass<?> aClass = (CtClass<?>) factory.Type().get(AClass.class);
    final String expected =
        "public List<? extends ArrayList> aMethodWithGeneric() {"
            + System.lineSeparator()
            + "    return new ArrayList<>();"
            + System.lineSeparator()
            + "}";
    assertEquals(expected, aClass.getMethodsByName("aMethodWithGeneric").get(0).toString());

    final CtConstructorCall<?> constructorCall =
        aClass.getElements(new TypeFilter<CtConstructorCall<?>>(CtConstructorCall.class)).get(0);
    final CtTypeReference<?> ctTypeReference =
        constructorCall.getType().getActualTypeArguments().get(0);
    assertTrue(ctTypeReference instanceof CtImplicitTypeReference);
    assertEquals("Object", ctTypeReference.getSimpleName());
  }
Exemple #14
0
 public String getMap() {
   StringBuilder builder = new StringBuilder();
   builder.append("+");
   for (int i = 0; i < size; i++) {
     builder.append("---");
   }
   builder.append("+");
   for (int y = 0; y < size; y++) {
     builder.append(System.lineSeparator());
     builder.append("|");
     for (int x = 0; x < size; x++) {
       if (x == posX && y == posY) {
         builder.append("(#)");
       } else if (Math.abs(x - posX) < 2 && Math.abs(y - posY) < 2
           || poiMap[x][y].getType().equals(PoiType.EXPLORED)) {
         builder.append(" " + poiMap[x][y].getSymbol() + " ");
       } else {
         builder.append(" ? ");
       }
     }
     builder.append("|");
   }
   builder.append(System.lineSeparator());
   builder.append("+");
   for (int i = 0; i < size; i++) {
     builder.append("---");
   }
   builder.append("+");
   return builder.toString();
 }
  private void printStandingsForResultCategory(
      Collection<Entry<UltimateRunDefinition, ExtendedResult>> allOfResultCategory,
      String resultCategory,
      StringBuilder sb) {
    sb.append("======= Standings for ")
        .append(resultCategory)
        .append(" =======")
        .append(System.lineSeparator());

    final HashRelation<TCS, String> tcse2input = new HashRelation<>();
    for (final Entry<UltimateRunDefinition, ExtendedResult> result : allOfResultCategory) {
      final UltimateRunDefinition urd = result.getKey();
      final TCS tcs = new TCS(urd.getToolchain(), urd.getSettings());
      tcse2input.addPair(tcs, urd.getInputFileNames());
    }

    // sort by TCS strings
    final TreeMap<String, Integer> tcs2amount = new TreeMap<>();
    for (final TCS tcs : tcse2input.getDomain()) {
      final Set<String> inputFiles = tcse2input.getImage(tcs);
      final String tcsString = String.valueOf(tcs);
      tcs2amount.put(tcsString, inputFiles.size());
    }

    for (final Entry<String, Integer> entry : tcs2amount.entrySet()) {
      sb.append(entry.getValue());
      sb.append(" times ");
      sb.append(resultCategory);
      sb.append(" with the ");
      sb.append(entry.getKey());
      sb.append(" toolchain/settings pair.");
      sb.append(System.lineSeparator());
    }
  }
  private String getSerialization(Vector<StatElement> elements) {
    StringBuilder builder = new StringBuilder();
    DecimalFormat df = new DecimalFormat("#.0000");

    builder.append("\"Creature Amount\"");
    builder.append(";");
    builder.append("\"Average Life\"");
    builder.append(";");
    builder.append("\"Average Max Life\"");
    builder.append(";");
    builder.append("\"Average Energy\"");
    builder.append(";");
    builder.append("\"Average Max Energy\"");
    builder.append(";");
    builder.append("\"Average Speed\"");
    builder.append(";");
    builder.append("\"Average Vision Range\"");
    builder.append(";");
    builder.append("\"Average Mating Energy Needed\"");
    builder.append(";");
    builder.append("\"Average Breed Length\"");
    builder.append(";");
    builder.append("\"Average Breed Progress Speed\"");
    builder.append(";");
    builder.append("\"Gender Ratio\"");
    builder.append(";");
    builder.append("\"Pregnancy Ratio\"");
    builder.append(System.lineSeparator());

    for (StatElement element : elements) {
      builder.append(element.getCreatureAmount());
      builder.append(";");
      builder.append(df.format(element.getAverageLife()));
      builder.append(";");
      builder.append(df.format(element.getAverageMaxLife()));
      builder.append(";");
      builder.append(df.format(element.getAverageEnergy()));
      builder.append(";");
      builder.append(df.format(element.getAverageMaxEnergy()));
      builder.append(";");
      builder.append(df.format(element.getAverageSpeed()));
      builder.append(";");
      builder.append(df.format(element.getAverageVisionRange()));
      builder.append(";");
      builder.append(df.format(element.getAverageMatingEnergyNeeded()));
      builder.append(";");
      builder.append(df.format(element.getAverageBreedLength()));
      builder.append(";");
      builder.append(df.format(element.getAverageBreedProgressSpeed()));
      builder.append(";");
      builder.append(df.format(element.getGenderRatio()));
      builder.append(";");
      builder.append(df.format(element.getPregnancyRatio()));
      builder.append(System.lineSeparator());
    }

    return builder.toString();
  }
  /**
   * Sets the new depth of the current Used keys value
   *
   * @param accountId
   * @param newValue
   * @throws CantExecuteDatabaseOperationException
   */
  public void setNewCurrentUsedKeyValue(int accountId, int newValue)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_TABLE_NAME);

    /** I will check to see if I already have a value for this account so i can updated it. */
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_ACCOUNT_ID_COLUMN_NAME,
        String.valueOf(accountId),
        DatabaseFilterType.EQUAL);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    DatabaseTableRecord record = null;
    try {
      if (databaseTable.getRecords().size() == 0) {
        // I will insert the new value
        record = databaseTable.getEmptyRecord();
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_ACCOUNT_ID_COLUMN_NAME,
            accountId);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_GENERATED_KEYS_COLUMN_NAME,
            0);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_USED_KEYS_COLUMN_NAME,
            newValue);

        databaseTable.insertRecord(record);
      } else {
        // I will update the existing value
        record = databaseTable.getRecords().get(0);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_USED_KEYS_COLUMN_NAME,
            newValue);
        databaseTable.updateRecord(record);
      }
    } catch (CantInsertRecordException | CantUpdateRecordException e) {
      StringBuilder outputMessage =
          new StringBuilder(
              "There was an error inserting or updating the key depth value in the database.");
      outputMessage.append(System.lineSeparator());
      outputMessage.append("The record is:");
      outputMessage.append(System.lineSeparator());
      outputMessage.append(XMLParser.parseObject(record));

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "database issue");
    }
  }
public abstract class SqlEmitter {
  protected String openCreate = "CREATE Table %s (id Integer,";
  protected String closeCreate = ");";
  protected String openRelation = "CREATE Table %s_%s_relationship (";
  protected String idColumn = "%s integer";
  protected String dateColumn = "%s Date";
  protected String stringColumn = "%s Varchar(50)";
  protected String relIdColumn = "%s_id integer";
  protected String insertUiFormStr =
      "insert into Ui_Form values(%s, %s, %s, %s, %s, %s, %s );" + System.lineSeparator();
  protected String insertUiFormLinkStr =
      "insert into Ui_Form_Link values(%s, %s, %s, %b);" + System.lineSeparator();

  public abstract String emit(
      String appName, String tableName, String[] column, String[] relationship, int orderBy);

  protected void setVal(StringBuffer sb, String name) {
    if (name.contains("id")) {
      sb.append(String.format(idColumn, name));
    } else if (name.contains("date")) {
      sb.append(String.format(dateColumn, name));
    } else {
      sb.append(String.format(stringColumn, name));
    }
  }

  protected void insertUiFormLink(
      StringBuffer sb, String tableName, String relName, String logicalName, boolean multiselect) {
    if (!Main.tableNameLookup.containsKey(relName)) {
      Main.tableNameLookup.put(relName, Main.tableNameLookup.size() + 1);
    }
    int tabId = Main.tableNameLookup.get(tableName);
    int relId = Main.tableNameLookup.get(relName);
    sb.append(
        String.format(insertUiFormLinkStr, tabId, relId, "'" + logicalName + "'", multiselect));
  }

  // insert into ui_form values (22, 'ldapuser_citizenship', 19, 'Ldapuser Citizenship', '', 'Rule',
  // 1);
  protected void insertUiForm(
      StringBuffer sb, String tableName, String nameColumn, int orderBy, String type) {
    if (!Main.tableNameLookup.containsKey(tableName)) {
      Main.tableNameLookup.put(tableName, Main.tableNameLookup.size() + 1);
    }
    int tabId = Main.tableNameLookup.get(tableName);
    sb.append(
        String.format(
            insertUiFormStr,
            tabId,
            "'" + tableName + "'",
            orderBy,
            "'" + Util.getDisplayName(tableName).trim() + "'",
            "''",
            "'" + type + "'",
            "1"));
  }
}
 @Override
 public String toString() {
   StringBuilder str = new StringBuilder("joints [" + System.lineSeparator());
   for (MD5JointData joint : joints) {
     str.append(joint).append(System.lineSeparator());
   }
   str.append("]").append(System.lineSeparator());
   return str.toString();
 }
  /**
   * Updates the Key detailed table for this account and key, with the passed addres
   *
   * @param hierarchyAccountId
   * @param ecKey
   * @param cryptoAddress
   * @param blockchainNetworkType
   */
  public void updateKeyDetailedStatsWithNewAddress(
      int hierarchyAccountId,
      ECKey ecKey,
      CryptoAddress cryptoAddress,
      BlockchainNetworkType blockchainNetworkType)
      throws CantExecuteDatabaseOperationException, UnexpectedResultReturnedFromDatabaseException {
    /** If we are not allowed to save detailed information then we will exit */
    if (!VaultKeyMaintenanceParameters.STORE_DETAILED_KEY_INFORMATION) return;

    DatabaseTable databaseTable =
        database.getTable(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_TABLE_NAME);
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_ACCOUNT_ID_COLUMN_NAME,
        String.valueOf(hierarchyAccountId),
        DatabaseFilterType.EQUAL);
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_PUBLIC_KEY_COLUMN_NAME,
        ecKey.getPublicKeyAsHex(),
        DatabaseFilterType.EQUAL);

    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    if (databaseTable.getRecords().size() == 0) {
      StringBuilder output = new StringBuilder("The key " + ecKey.toString());
      output.append(System.lineSeparator());
      output.append("which generated the address " + cryptoAddress.getAddress());
      output.append(System.lineSeparator());
      output.append("is not a key derived from the vault.");

      throw new UnexpectedResultReturnedFromDatabaseException(
          null, output.toString(), "Vault derivation miss match");
    }

    DatabaseTableRecord record = databaseTable.getRecords().get(0);
    record.setStringValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_DETAIL_ADDRESS_COLUMN_NAME,
        cryptoAddress.getAddress());
    record.setStringValue(
        AssetsOverBitcoinCryptoVaultDatabaseConstants
            .KEY_MAINTENANCE_DETAIL_BLOCKCHAIN_NETWORK_TYPE_COLUMN_NAME,
        blockchainNetworkType.getCode());
    try {
      databaseTable.updateRecord(record);
    } catch (CantUpdateRecordException e) {
      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          "error updating record",
          "database issue");
    }
  }
  /**
   * Sets the new value of how many keys have been generated by the Key Maintainer
   *
   * @param accountId the account id
   * @param value the amount of keys generated. This value accumulates to the one that existed.
   * @throws CantExecuteDatabaseOperationException
   */
  public void setGeneratedKeysValue(int accountId, int value)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_TABLE_NAME);

    /**
     * first I see if we already have records for this account by setting a filter and getting the
     * values
     */
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_ACCOUNT_ID_COLUMN_NAME,
        String.valueOf(accountId),
        DatabaseFilterType.EQUAL);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }

    /** I will insert or update the record */
    DatabaseTableRecord record = null;
    try {
      if (databaseTable.getRecords().size() == 0) {
        // insert
        record = databaseTable.getEmptyRecord();
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_ACCOUNT_ID_COLUMN_NAME,
            accountId);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_GENERATED_KEYS_COLUMN_NAME,
            value);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.KEY_MAINTENANCE_USED_KEYS_COLUMN_NAME, 0);
        databaseTable.insertRecord(record);
      } else {
        // update
        record = databaseTable.getRecords().get(0);
        record.setIntegerValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .KEY_MAINTENANCE_GENERATED_KEYS_COLUMN_NAME,
            value);
        databaseTable.updateRecord(record);
      }
    } catch (CantInsertRecordException | CantUpdateRecordException e) {
      StringBuilder outputMessage =
          new StringBuilder("There was an error inserting or updating the following table: ");
      outputMessage.append(databaseTable.getTableName());
      outputMessage.append(System.lineSeparator());
      outputMessage.append("The record is:");
      outputMessage.append(System.lineSeparator());
      outputMessage.append(XMLParser.parseObject(record));
    }
  }
  /**
   * Sets the active network type that the Bitcoin Network will need to listen too. Network types
   * are MainNet, TestNet and RegTest
   *
   * @param blockchainNetworkType
   * @throws CantExecuteDatabaseOperationException
   */
  public void setActiveNetworkType(BlockchainNetworkType blockchainNetworkType)
      throws CantExecuteDatabaseOperationException {
    DatabaseTable databaseTable =
        getDatabaseTable(AssetsOverBitcoinCryptoVaultDatabaseConstants.ACTIVE_NETWORKS_TABLE_NAME);

    /** I will check to see if I already have a value for this account so i can updated it. */
    databaseTable.addStringFilter(
        AssetsOverBitcoinCryptoVaultDatabaseConstants.ACTIVE_NETWORKS_NETWORKTYPE_COLUMN_NAME,
        blockchainNetworkType.getCode(),
        DatabaseFilterType.EQUAL);
    try {
      databaseTable.loadToMemory();
    } catch (CantLoadTableToMemoryException e) {
      throwLoadToMemoryException(e, databaseTable.getTableName());
    }
    DatabaseTableRecord record = null;
    String date = new SimpleDateFormat("yyyyMMdd_HHmmss").format(Calendar.getInstance().getTime());
    try {
      if (databaseTable.getRecords().size() == 0) {
        // I will insert the new value
        record = databaseTable.getEmptyRecord();
        record.setStringValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants.ACTIVE_NETWORKS_NETWORKTYPE_COLUMN_NAME,
            blockchainNetworkType.getCode());
        record.setStringValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .ACTIVE_NETWORKS_ACTIVATION_DATE_COLUMN_NAME,
            date);
        databaseTable.insertRecord(record);
      } else {
        // I will update the existing value
        record = databaseTable.getRecords().get(0);
        record.setStringValue(
            AssetsOverBitcoinCryptoVaultDatabaseConstants
                .ACTIVE_NETWORKS_ACTIVATION_DATE_COLUMN_NAME,
            date);
        databaseTable.updateRecord(record);
      }
    } catch (CantInsertRecordException | CantUpdateRecordException e) {
      StringBuilder outputMessage =
          new StringBuilder(
              "There was an error inserting or updating the network type in the database.");
      outputMessage.append(System.lineSeparator());
      outputMessage.append("The record is:");
      outputMessage.append(System.lineSeparator());
      outputMessage.append(XMLParser.parseObject(record));

      throw new CantExecuteDatabaseOperationException(
          CantExecuteDatabaseOperationException.DEFAULT_MESSAGE,
          e,
          outputMessage.toString(),
          "database issue");
    }
  }
 /**
  * Set the text content from a XML node.
  *
  * @param t inner text element of XML <msg></msg> element.
  */
 public void xmltext(final Text t) {
   /* if trim is required, split the text and trim each line */
   if (trim) {
     final String[] lines = t.getText().split(System.lineSeparator());
     for (String s : lines) {
       this.append(s.trim() + System.lineSeparator());
     }
   } else {
     this.append(t.getText());
   }
 }
Exemple #24
0
 /** Warns the user when a workaround is being used to dodge the bug */
 public Optional<String> getWarningMessage() {
   StringBuilder sb = new StringBuilder();
   sb.append("Workaround flag ").append(workAround);
   sb.append(" for bug ").append(bugUrl);
   sb.append(" found. ");
   sb.append(System.lineSeparator());
   sb.append("This will result in degraded performance!");
   sb.append(System.lineSeparator());
   sb.append("Upgrading is preferred, see ").append(JVM_RECOMMENDATIONS);
   sb.append(" for current recommendations.");
   return Optional.of(sb.toString());
 }
    @Override
    protected String doInBackground() throws Exception {
      long start = System.currentTimeMillis();

      System.out.println("absolutePath=" + file.getAbsolutePath());
      System.out.println("Path=" + file.getPath());
      System.out.println("Parent=" + file.getParent());
      System.out.println("Name=" + file.getName());

      StringBuilder content = new StringBuilder();
      CircularLimitedQueue<String> lastRows = new CircularLimitedQueue<>(this.nbLastRowsPrinted);

      try (BufferedReader reader = new BufferedReader(new FileReader(file.getAbsolutePath()))) {
        String line;
        while ((line = reader.readLine()) != null) {
          String row = line.trim();
          if ("".equals(row)) {
            continue;
          }
          if (this.nbTotalRows < this.nbFirstRowsPrinted) {
            content.append(row).append(System.lineSeparator());
          } else {
            lastRows.add(row);
          }
          this.nbTotalRows++;
        }

        if (this.nbTotalRows > this.nbFirstRowsPrinted) {
          if (this.nbTotalRows > this.nbFirstRowsPrinted + this.nbLastRowsPrinted) {
            content
                .append("... ")
                .append(this.nbTotalRows - this.nbFirstRowsPrinted - this.nbLastRowsPrinted)
                .append(" hidden rows ...")
                .append(System.lineSeparator());
          }

          boolean addSeparator = false;
          for (String row : lastRows) {
            if (addSeparator) {
              content.append(System.lineSeparator());
            }
            addSeparator = true;
            content.append(row);
          }
        }

      } catch (FileNotFoundException e) {
        throw new FileNotFoundException("file not found " + file.getAbsolutePath());
      }

      System.out.println("open in " + (System.currentTimeMillis() - start) + " milliseconds");
      return content.toString();
    }
Exemple #26
0
 @Test
 public void callParamConstructor() throws Exception {
   CtClass<Object> aClass = factory.Class().get(AClass.class);
   CtConstructor<Object> constructor = aClass.getConstructors().iterator().next();
   assertEquals(
       "{"
           + System.lineSeparator()
           + "    enclosingInstance.super();"
           + System.lineSeparator()
           + "}",
       constructor.getBody().toString());
 }
Exemple #27
0
  @Override
  public void log(CooLogLevel level, String message, Throwable cause) {
    try {
      message = CooLoggerUtil.creMessageString(level, message);
      out.write(message.getBytes());

      if (addLineSeparator && !message.endsWith(System.lineSeparator())) {
        out.write(System.lineSeparator().getBytes());
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
 private static String handleThrowable(Throwable throwable) {
   StringBuilder comment = new StringBuilder();
   if (throwable instanceof Misuse)
     if (throwable instanceof UnsupportedVersionError) comment.append(throwable.getMessage());
     else
       comment
           .append("A fatal error occurred in ")
           .append(Loader.instance().activeModContainer().getName())
           .append(" due to misuse. Do NOT report this error.");
   else if (throwable instanceof ClassNotFoundException)
     if (throwable.getMessage() != null
         && throwable.getMessage().startsWith("net.minecraft.client"))
       comment
           .append("A mod tried to load clientside classes on the server.")
           .append(System.lineSeparator())
           .append(
               "This may happen due to programming errors or due to installing clientside mods such as minimaps on the server.");
     else
       comment.append(
           "A mod tried to load an unexisting class. This may occur if you're missing one of the mods' dependencies, or if an attempt at bytecode manipulation failed.");
   else if (throwable instanceof NoClassDefFoundError)
     if (throwable.getMessage() != null
         && throwable.getMessage().startsWith("net/minecraft/client"))
       comment
           .append("A mod tried to load clientside classes on the server.")
           .append(System.lineSeparator())
           .append(
               "This may happen due to programming errors or due to installing clientside mods such as minimaps on the server.");
     else
       comment.append(
           "A mod tried to load an unexisting class. This may occur if you're missing one of the mod's dependencies.");
   else if (throwable instanceof RuntimeException
       && throwable.getMessage() != null
       && throwable
           .getMessage()
           .matches("Attempted to load class .* for invalid side (SERVER|CLIENT)")) {
     if (FMLLaunchHandler.side().isClient())
       comment.append("A mod tried to load clientside classes on the server.");
     else comment.append("A mod tried to load serverside classes on the client.");
     comment
         .append(System.lineSeparator())
         .append(
             "This may happen due to programming errors or due to installing clientside mods such as minimaps on the server.");
   }
   if (comment.length() > 0)
     comment
         .append(System.lineSeparator())
         .append("Disclaimer: This is an automated report. It may be inaccurate.");
   return comment.toString();
 }
  private void createFile2() throws Exception {
    BufferedWriter bw;
    String content;

    file2 = new File("file2");
    file2.createNewFile();
    content = "this is file2 used for testing" + System.lineSeparator();
    content += "testing testing 1 2 3" + System.lineSeparator();
    content += "	???	" + System.lineSeparator() + System.lineSeparator();

    bw = new BufferedWriter(new FileWriter(file2));
    bw.write(content);
    bw.close();
  }
  /**
   * Prints a list of module name, version, path to the given file, to be used by the runtime
   * launcher, because passing it as an argument/environment would easily exceed the OS size limits.
   */
  private void writeModuleInfoFile(File tmpFile, ILaunchConfiguration configuration)
      throws IOException, CoreException {
    FileWriter writer = new FileWriter(tmpFile);
    IJavaProject javaProject = getJavaProject(configuration);
    IProject project = javaProject.getProject();
    Context context = getProjectTypeChecker(project).getContext();

    RepositoryManager provider = context.getRepositoryManager();
    Set<Module> modulesToAdd = context.getModules().getListOfModules();
    boolean seenDefault = false;
    for (Module module : modulesToAdd) {
      String name = module.getNameAsString();
      if (JDKUtils.isJDKModule(name) || JDKUtils.isOracleJDKModule(name)) {
        continue;
      }
      if (module.isDefault()) seenDefault = true;
      IPath modulePath = getModuleArchive(provider, module);
      if (modulePath != null && modulePath.toFile().exists()) {
        String path = modulePath.toOSString();
        System.err.println(
            "Adding module: " + module.getNameAsString() + "/" + module.getVersion() + ": " + path);
        // print module name + NL (+ version + NL)? + path + NL
        writer.append(module.getNameAsString());
        writer.append(System.lineSeparator());
        if (!module.isDefault()) {
          writer.append(module.getVersion());
          writer.append(System.lineSeparator());
        }
        writer.append(path);
        writer.append(System.lineSeparator());
      }
    }
    // for some reason the default module can be missing from the list of modules
    if (!seenDefault) {
      IPath modulesFolder = getCeylonModulesOutputFolder(project).getLocation();
      IPath defaultCar = modulesFolder.append("default").append("default.car");
      if (defaultCar.toFile().exists()) {
        String path = defaultCar.toOSString();
        Module module = context.getModules().getDefaultModule();
        System.err.println("Adding default module: " + module.getNameAsString() + ": " + path);
        // print module name + NL + path + NL
        writer.append(module.getNameAsString());
        writer.append(System.lineSeparator());
        writer.append(path);
        writer.append(System.lineSeparator());
      }
    }
    writer.flush();
    writer.close();
  }