Пример #1
0
  public static <T extends Number> ArrayList<ArrayList<T>> solve(
      ArrayList<ArrayList<T>> a, ArrayList<ArrayList<T>> bVector, double eps, Class<T> type) {
    try {
      if (verifySingularity(a, eps)) {
        int size = a.size();
        ArrayList<ArrayList<T>> solution = new ArrayList<ArrayList<T>>();
        for (int i = 0; i < size; i++) {
          solution.add(new ArrayList<T>());
        }
        for (int i = size - 1; i >= 0; i--) {
          T sum = bVector.get(i).get(0);
          for (int j = i + 1; j < size; j++) {
            T value = a.get(i).get(j);
            T x = solution.get(j).get(0);
            sum = subsElements(sum, mulElements(value, x, type), type);
          }
          solution.get(i).add(divElements(sum, a.get(i).get(i), type, eps));
        }

        // this.checkSolution();
        return solution;
      } else {
        return null;
      }
    } catch (NullPointerException e) {
      Logger.getGlobal().log(Level.SEVERE, "something went wrong solving the sys!");
      e.printStackTrace();
      return null;
    } catch (IndexOutOfBoundsException e) {
      Logger.getGlobal().log(Level.SEVERE, "check your indexes!");
      e.printStackTrace();
      return null;
    }
  }
Пример #2
0
  public static <T extends Number> ArrayList<ArrayList<T>> multScalarWithMatrix(
      T scalar, ArrayList<ArrayList<T>> a, Class<T> type) {
    ArrayList<ArrayList<T>> result = new ArrayList<ArrayList<T>>();
    try {
      if (a == null) {
        throw new NullPointerException();
      }
      int rows = a.size();
      int columns = a.get(0).size();

      for (int i = 0; i < rows; i++) {
        ArrayList<T> row = new ArrayList<>();
        for (int j = 0; j < columns; j++) {
          T elem = mulElements(scalar, a.get(i).get(j), type);
          row.add(elem);
        }
        result.add(row);
      }
      return result;
    } catch (NullPointerException e) {
      Logger.getGlobal().log(Level.SEVERE, "cannot multiply null matrixes");
      e.printStackTrace();
      return null;
    } catch (IndexOutOfBoundsException e) {
      Logger.getGlobal().log(Level.SEVERE, "check your indexes when multiplying matrixes");
      e.printStackTrace();
      return null;
    }
  }
Пример #3
0
  public static <T extends Number> ArrayList<ArrayList<T>> mulMatrixes(
      ArrayList<ArrayList<T>> a, ArrayList<ArrayList<T>> b, Class<T> type) {
    ArrayList<ArrayList<T>> result = new ArrayList<ArrayList<T>>();
    try {
      if (a == null || b == null) {
        throw new NullPointerException();
      }
      int rows = a.size();
      int columns = b.get(0).size();
      int common = a.get(0).size();

      for (int i = 0; i < rows; i++) {
        ArrayList<T> row = new ArrayList<>();
        for (int j = 0; j < columns; j++) {
          T elem = getNeutralSumElem(type);
          for (int k = 0; k < common; k++) {
            elem = sumElements(elem, mulElements(a.get(i).get(k), b.get(k).get(j), type), type);
          }
          row.add(elem);
        }
        result.add(row);
      }
    } catch (NullPointerException e) {
      Logger.getGlobal().log(Level.SEVERE, "cannot multiply null matrixes");
      e.printStackTrace();
      return null;
    } catch (IndexOutOfBoundsException e) {
      Logger.getGlobal().log(Level.SEVERE, "check your indexes when multiplying matrixes");
      e.printStackTrace();
      return null;
    }
    return result;
  }
Пример #4
0
  public static <T extends Number> ArrayList<ArrayList<T>> subMatrixes(
      ArrayList<ArrayList<T>> a, ArrayList<ArrayList<T>> b, Class<T> type) {
    try {
      ArrayList<ArrayList<T>> result = new ArrayList<ArrayList<T>>();
      if (a.size() != b.size() && a.get(0).size() != b.get(0).size()) {
        throw new IllegalArgumentException();
      }

      for (int i = 0; i < a.size(); i++) {
        ArrayList<T> resultRow = new ArrayList<T>();
        ArrayList<T> aRow = a.get(i);
        ArrayList<T> bRow = b.get(i);
        for (int j = 0; j < a.get(0).size(); j++) {
          resultRow.add(subsElements(aRow.get(j), bRow.get(j), type));
        }
        result.add(resultRow);
      }
      return result;
    } catch (NullPointerException e) {
      Logger.getGlobal().log(Level.SEVERE, "cannot extract from null matrix!");
      e.printStackTrace();
      return null;
    } catch (IllegalArgumentException e) {
      Logger.getGlobal().log(Level.SEVERE, "matrixes have different sizes!");
      e.printStackTrace();
      return null;
    } catch (IndexOutOfBoundsException e) {
      Logger.getGlobal().log(Level.SEVERE, "check indexes!");
      e.printStackTrace();
      return null;
    }
  }
Пример #5
0
  @Override
  public int print(Graphics g, PageFormat pf, int pageIndex) throws PrinterException {
    System.out.println("PageFormat: width=" + pf.getWidth() + ", height=" + pf.getHeight());
    Logger.getGlobal().log(Level.INFO, "PageFormat {0}", pf);
    System.out.println("pageIndex " + pageIndex);
    Logger.getGlobal().log(Level.INFO, "pageIndex {0}", pageIndex);

    if (pageIndex == 0) {
      Graphics2D g2d = (Graphics2D) g;
      Font font = g2d.getFont();
      g2d.setFont(font.deriveFont((float) fontSize));

      g2d.translate(pf.getImageableX(), pf.getImageableY());
      g2d.setColor(Color.black);
      int step = g2d.getFont().getSize();
      step += step / 4;
      double y = paddingTop + g2d.getFont().getSize();
      for (String s : printStringList) {
        Logger.getGlobal().log(Level.INFO, "printStringList: {0}", s);
        g2d.drawString(s, (float) paddingLeft, (float) y);
        y += step;
      }

      // g2d.fillRect(0, 0, 200, 200);
      return Printable.PAGE_EXISTS;

    } else {
      return Printable.NO_SUCH_PAGE;
    }
  }
Пример #6
0
  /** Sets up the file logging for debugging purposes. */
  private static void setUpLogger() {
    try {
      LogManager.getLogManager().reset();
      logger.setUseParentHandlers(false);

      // Log file
      FileHandler loggingFileHandler = new FileHandler("./log" + playerNumber + ".log");
      loggingFileHandler.setLevel(Level.ALL);

      // Console logging
      ConsoleHandler loggingConsoleHandler = new ConsoleHandler();
      loggingConsoleHandler.setLevel(Level.OFF);

      // Remove old handlers
      Handler[] handlers = Logger.getGlobal().getHandlers();

      for (Handler handler : handlers) {
        Logger.getGlobal().removeHandler(handler);
      }

      // Add logging handlers
      logger.addHandler(loggingFileHandler);
      logger.addHandler(loggingConsoleHandler);

      System.setProperty(
          "java.util.logging.SimpleFormatter.format",
          "%1$tb %1$td, %1$tY %1$tl:%1$tM:%1$tS %1$Tp %2$s %4$s: %5$s%n");
      SimpleFormatter simpleFormatter = new SimpleFormatter();
      loggingFileHandler.setFormatter(simpleFormatter);

      logger.setLevel(Level.ALL);
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
  /**
   * Log the <tt>joker<tt> beans in the application context.
   *
   * @param ctx Spring application context if available - may be null.
   */
  protected static void showBeans(ApplicationContext ctx) {
    if (ctx != null) {
      Logger logger = Logger.getGlobal();
      logger.info("Let's check our beans were found by Spring Boot:");
      String[] beanNames = ctx.getBeanDefinitionNames();
      Arrays.sort(beanNames);

      for (String beanName : beanNames) {
        if (beanName.indexOf("oke") != -1) logger.info(beanName);
      }
    } else {
      Logger.getGlobal().info("Application starting.");
    }
  }
 static {
   try {
     KNOWN_PUNCTUATION_CHARACTERS = SQLiteBridgeDesktop.getInstance().getPunctuationCharacters();
   } catch (SQLException e) {
     Logger.getGlobal()
         .log(Level.SEVERE, "Unable to retrieve punctuation characters from database!", e);
   } catch (Exception e) {
     Logger.getGlobal()
         .log(
             Level.SEVERE,
             "Unexpected exception while retrieving punctuation characters from database!",
             e);
   }
 }
Пример #9
0
 /** Wie kann man das gleiche erreichen, ohne ein `if`-Statement zu verwenden? */
 @Test
 public void frage() {
   Logger logger = Logger.getGlobal();
   if (logger.isLoggable(Level.INFO)) {
     logger.info(ermittleKomplizierteNachricht());
   }
 }
Пример #10
0
  @Override
  public void savePurchase(final Purchase purchase) {
    PurchaseEntity entity;
    ModelMapper mapper = new ModelMapper();
    entity = mapper.map(purchase, PurchaseEntity.class);

    // TODO: remove CustomerEntity Depenency
    CustomerEntity ce =
        mapper.map(cdl.getCustomerById(purchase.getCustomer().getId()), CustomerEntity.class);
    entity.setCustomerid(ce);

    List<PurchaseitemEntity> list = new LinkedList<PurchaseitemEntity>();
    for (PurchaseItem pi : purchase.getPurchaseItems()) {
      PurchaseitemEntity e = mapper.map(pi, PurchaseitemEntity.class);
      // ProductEntity pe = new ProductEntity(pi.getProductid());
      // e.setProductid(pe);
      e.setProductno(pi.getProductNo());
      e.setPurchaseid(entity);
      list.add(e);
    }

    entity.setPurchaseitemCollection(list);

    try {
      this.pfl.create(entity);
    } catch (Exception ex) {
      Logger.getGlobal().log(Level.WARNING, ex.toString());
    }
  }
  private void testDigitalAssetMetadataVault()
      throws CantCreateDigitalAssetFileException, CantGetDigitalAssetFromLocalStorageException {
    Logger LOG = Logger.getGlobal();
    LOG.info("MAP_TEST_DAMVault");
    DigitalAsset digitalAsset = new DigitalAsset();
    digitalAsset.setGenesisAmount(100000);
    digitalAsset.setDescription("TestAsset");
    digitalAsset.setName("testName");
    digitalAsset.setPublicKey(new ECCKeyPair().getPublicKey());
    LOG.info("MAP_DigitalAsset:" + digitalAsset);
    List<Resource> resources = new ArrayList<>();
    digitalAsset.setResources(resources);

    digitalAsset.setIdentityAssetIssuer(null);
    DigitalAssetContract digitalAssetContract = new DigitalAssetContract();
    digitalAsset.setContract(digitalAssetContract);
    LOG.info("MAP_DigitalAsset2:" + digitalAsset);
    DigitalAssetMetadata dam = new DigitalAssetMetadata(digitalAsset);
    dam.setGenesisTransaction("testGenesisTX");
    this.digitalAssetIssuingVault.persistDigitalAssetMetadataInLocalStorage(dam, "testId");
    LOG.info(
        "DAM from vault:\n"
            + this.digitalAssetIssuingVault
                .getDigitalAssetMetadataFromLocalStorage("testGenesisTX")
                .toString());
  }
Пример #12
0
  private void start() {
    long start = System.currentTimeMillis();
    Path pDir =
        Paths.get(
            System.getProperty("user.home"),
            ".saas",
            "app",
            "db",
            "org.ubo.accountbook.SyntheticAccount"); // SyntheticAccount AccountPost
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    for (File f : pDir.toFile().listFiles()) {
      if (f.isDirectory()) {
        continue;
      }

      try {
        cacheList.add(
            CacheData.createCacheData(
                "org.ubo.accountbook.SyntheticAccount",
                Long.parseLong(f.getName()),
                Files.readAllBytes(f.toPath())));
      } catch (NumberFormatException | IOException e) {
        Logger.getGlobal().log(Level.SEVERE, null, e);
      }
    }

    System.out.println(">>>>>>>>>> " + cacheList.toArray()[0]);
    System.out.println("Time: " + (System.currentTimeMillis() - start));
  }
Пример #13
0
  private void buildJSImagesList() {
    String str = "var tinyMCEImageList = new Array(\n";
    Path dir = Paths.get(System.getProperty("user.home"), ".saas", "app", "ui", "img", "www");
    boolean isFirst = true;
    for (File f : dir.toFile().listFiles()) {
      if (f.isDirectory()) {
        continue;
      }

      String s = "[\"" + f.getName() + "\", \"img/www/" + f.getName() + "\"]";
      if (isFirst) {
        str += s;
        isFirst = false;
      } else {
        str += ",\n" + s;
      }
    }

    str += "\n);";

    Path f =
        Paths.get(System.getProperty("user.home"), ".saas", "app", "ui", "js", "image_list.js");
    try {
      Files.write(f, str.getBytes());
    } catch (IOException ex) {
      Logger.getGlobal().log(Level.WARNING, str, ex);
      JSMediator.alert(getSession(), ex.toString());
    }
  }
Пример #14
0
  private void printDoc() {
    try {
      PrintService printService = null;
      PrintService[] printServices = PrintServiceLookup.lookupPrintServices(null, null);
      for (PrintService ps : printServices) {
        if (ps.getName().equals(printerName)) {
          printService = ps;
          break;
        }
      }

      if (printService == null) {
        return;
      }

      PrinterJob job = PrinterJob.getPrinterJob();
      job.setPrintService(printService);
      CustomPaper customPaper = new CustomPaper(pageWidth, pageHeight);
      customPaper.setPrintArea(printAreaTop, printAreaLeft, printAreaWidth, printAreaHeight);

      PageFormat pf = job.defaultPage();
      pf.setPaper(customPaper);
      job.defaultPage(pf);
      job.setPrintable(this, pf);
      job.print();

    } catch (PrinterException | HeadlessException e) {
      System.err.println(e);
      Logger.getGlobal().log(Level.SEVERE, null, e);
    }
  }
Пример #15
0
  @Override
  public Result printReceiptMoneyOut(Path receiptsFile) {
    try {
      PosReceipt posReceipt = PosReceipt.getFromJSON(receiptsFile);

      List<String> lines =
          Files.readAllLines(
              rootPath.resolve(Paths.get("templates", "receipt_money_out.txt")),
              Charset.defaultCharset());

      String receipt = "";
      for (String line : lines) {
        line = line.replaceAll("\\{cash\\}", "" + posReceipt.getCash());
        line = line.replaceAll("\\{fiscal\\}", getFiscalString(posReceipt));

        receipt += line + "\r\n";
      }

      printStringList = Arrays.asList(receipt.split("\r\n"));
      printDoc();
      return Result.newEmptySuccess();

    } catch (Exception e) {
      Logger.getGlobal().log(Level.WARNING, null, e);
      return Result.newResultError(e.toString());
    }
  }
 public String editar() {
   try {
     servicoLicitante.validarLicitante(licitante);
     servicoLicitante.atualizar(licitante);
     return "/restrito/licitantes/licitante.xhtml";
   } catch (ExcecoesLicita el) {
     JsfUtil.addErrorMessage(el.getMessage());
     Logger.getGlobal().log(Level.WARNING, el.getMessage());
   } catch (RollbackException re) {
     JsfUtil.addErrorMessage("CNPJ já Existe.");
     Logger.getGlobal().log(Level.WARNING, re.getMessage());
   } catch (Exception e) {
     JsfUtil.addErrorMessage("Erro inesperado ocorreu!");
     Logger.getGlobal().log(Level.SEVERE, e.getMessage());
   }
   return null;
 }
 public void remover() {
   try {
     servicoLicitante.remover(licitante);
   } catch (Exception e) {
     JsfUtil.addErrorMessage("Erro inesperado ocorreu!");
     Logger.getGlobal().log(Level.SEVERE, e.getMessage());
   }
 }
Пример #18
0
 /**
  * Constructor.
  *
  * @param name The name of the reader we should listen to.
  */
 public TerminalReader(String name) {
   this.listenersTerminal = new ArrayList<>();
   this.terminalName = name;
   this.logger = Logger.getGlobal();
   this.thread = new Thread(this);
   this.thread.setName("TerminalReader");
   this.thread.start();
   terminalFactory = TerminalFactory.getDefault();
 }
Пример #19
0
  /** Estimates the initial land used per food type, and the yield. */
  public void estimateInitialYield() {
    double income = 0.;
    double production = 0.;
    double land = 0.;
    for (EnumFood crop : EnumFood.values()) {
      land += landCrop[crop.ordinal()][0];
      production += cropProduction[crop.ordinal()][0];
      income += cropIncome[crop.ordinal()][0];
    }

    // If the total land is > 0 then this function has already been called.
    //
    if (land == 0.) {
      if (income == 0. && production == 0.) {
        Logger.getGlobal()
            .log(Level.INFO, "Territory {0} has no production or income. Faking it.", getName());

        // Assume they're getting $100 per acre.  Terrible guess, but it's just a
        // default for empty rows.
        //
        income = landTotal[0] / 10.; // $100 per acre / 1000.;
        double p = 1. / EnumFood.SIZE;
        for (int i = 0; i < EnumFood.SIZE; i += 1) cropIncome[i][0] = income * p;
      }

      if (production == 0.) {
        for (EnumFood crop : EnumFood.values()) {
          if (production == 0.) {
            // The current version of the CSV file doesn't have any production values.
            // Use the income values (if available) to estimate land per crop.
            //

            // Estimate production from the yield.
            //
            cropProduction[crop.ordinal()][0] =
                (cropIncome[crop.ordinal()][0] / income) * landTotal[0];
            production += cropProduction[crop.ordinal()][0];
          }
        }
      }

      for (EnumFood crop : EnumFood.values()) {
        cropYield[crop.ordinal()] = cropProduction[crop.ordinal()][0] / landTotal[0];

        // Use the crop production to estimate land per crop.
        //
        double p = cropProduction[crop.ordinal()][0] / production;

        // This is an initial naive estimate.  Per Joel there will eventually be a multiplier
        // applied that gives a more realistic estimate.
        //
        landCrop[crop.ordinal()][0] = landTotal[0] * p /* * multiplier[food] */;

        land += landCrop[crop.ordinal()][0];
      }
    }
  }
 public String reset() {
   if (this.installed) {
     try {
       throw new EJBException("Desinstalação não foi implementada!");
     } catch (EJBException e) {
       Logger.getGlobal().fine(e.getMessage());
     }
   }
   return "setup";
 }
Пример #21
0
 protected void updateCookie(HttpServletRequest request, HttpServletResponse response) {
   Cookie[] cookies = request.getCookies();
   for (Cookie cookie : cookies) {
     if (cookie.getName() != null && cookie.getName().equals("Token")) {
       Logger.getGlobal().info("Token cookie value is: " + cookie.getValue());
       if (userService.isUserSessionByToken(cookie.getValue())) {
         this.makeCookie(cookie.getValue(), response);
       }
     }
   }
 }
 /**
  * A convenience getter that will check whether or not the given character has a corresponding
  * {@link PunctuationCharacter} object. Contrary to {@link #getPunctChar(String)}, no {@link
  * NoSuchElementException} will be thrown.
  *
  * @param character a <code>String</code> of length 1 containing the character to check.
  * @return <code>true</code> if there is a corresponding punctuation character object; <code>false
  *     </code> otherwise.
  * @throws IllegalArgumentException if the parameter <code>String</code> was no of length 1.
  */
 public static boolean isPunctuationCharacter(String character)
     throws IllegalArgumentException, NoSuchElementException {
   try {
     return getPunctChar(character) != null;
   } catch (IllegalArgumentException e) {
     Logger.getGlobal()
         .log(Level.WARNING, "Exception while checking for punctuation character!", e);
   } catch (NoSuchElementException e) {
     // Simply not a (supported) currencyCharacter.
   }
   return false;
 }
 public String setup() {
   checkInstallation();
   if (!this.installed) {
     try {
       facade.create(Comprador.createCompradorBB());
     } catch (EJBException e) {
       Logger.getGlobal().fine(e.getMessage());
     }
     try {
       facade.create(Comprador.createCompradorBEC());
     } catch (EJBException e) {
       Logger.getGlobal().fine(e.getMessage());
     }
     try {
       facade.create(Comprador.createCompradorComprasNet());
     } catch (EJBException e) {
       Logger.getGlobal().fine(e.getMessage());
     }
   }
   checkInstallation();
   return "setup";
 }
Пример #24
0
public class AgeCalculator {
  private static Logger logger = Logger.getGlobal();
  private static Properties bodProperties = new Properties();

  static {
    logger.info("プロパティファイルの読み込みを開始します");
    InputStream bodstream = PathUtil.class.getResourceAsStream("/bod.properties");
    try {
      logger.info("生年月日プロパティの読み込み中");
      bodProperties.load(bodstream);
      bodstream.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  /**
   * 年齢を簡単な方法で計算する.
   *
   * <p>出典 : http://itpro.nikkeibp.co.jp/article/Watcher/20070822/280097/ <cite>
   * 生年月日から年齢を計算する簡単な計算式というのがあるそうです<br>
   * (今日の日付-誕生日)/10000の小数点以下切捨て。</cite>
   *
   * @param key
   * @param yyyymmdd
   * @return
   */
  public static int calcAge(String key, String yyyymmdd) {
    logger.info("年齢計算を開始します key=" + key + " 素材年月日=" + yyyymmdd);
    int dob = getDateOfBirth(key);
    int base = Integer.parseInt(yyyymmdd);
    return (base - dob) / 10000;
  }

  /**
   * 年齢を簡単な方法で計算し、2桁の文字列として返却する。
   *
   * @param key
   * @param yyyymmdd
   * @return 2桁でフォーマットされた年齢("08"等)
   */
  public static String calcAgeAsFormattedString(String key, String yyyymmdd) {
    int age = calcAge(key, yyyymmdd);
    DecimalFormat formatter = new DecimalFormat("00");
    return formatter.format(age);
  }

  public static int getDateOfBirth(String key) {
    return Integer.parseInt(bodProperties.getProperty(key));
  }
}
Пример #25
0
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    ServletInputStream is = request.getInputStream();
    int len;
    byte b[] = new byte[8096];
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    while ((len = is.read(b)) > 0) {
      baos.write(Arrays.copyOf(b, len));
    }

    StringTokenizer tokenizer = new StringTokenizer(new String(baos.toByteArray()), "\r\n");
    String user = "", marker = "";
    int index = 0;
    while (tokenizer.hasMoreTokens()) {
      String s = tokenizer.nextToken();
      if (s.indexOf("name=\"frame_") != -1) {
        user = s.split(";")[1];
        user = user.split("=")[1];
        user = user.replaceAll("\"", "");
        user = user.split("_")[1];
        break;
      }

      if (index == 0) {
        marker = s;
      }
    }

    Path pCheck = Paths.get(System.getProperty("user.dir"), "app", "frames", user);
    if (!pCheck.toFile().exists()) {
      return;
    }

    byte[] data = baos.toByteArray();
    byte[] image = null;
    for (int i = 0; i < data.length - 4; i++) {
      if (data[i] == 13 && data[i + 1] == 10 && data[i + 2] == 13 && data[i + 3] == 10) {
        image = Arrays.copyOfRange(data, i + 4, data.length - (marker.getBytes().length + 6));
        break;
      }
    }

    Path p = Paths.get("frames", user, "frame.jpg");
    Files.write(rootPath.resolve(p), image);
    Logger.getGlobal().log(Level.INFO, "Write frame {0}", p);
  }
Пример #26
0
  public void saveNewEvent(String eventType, String eventSource) throws CantSaveEventException {
    try {
      this.database = openDatabase();
      DatabaseTable databaseTable =
          this.database.getTable(
              AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TABLE_NAME);
      DatabaseTableRecord eventRecord = databaseTable.getEmptyRecord();
      UUID eventRecordID = UUID.randomUUID();
      long unixTime = System.currentTimeMillis();
      Logger LOG = Logger.getGlobal();
      LOG.info("ASSET DAO:\nUUID:" + eventRecordID + "\n" + unixTime);
      eventRecord.setUUIDValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_ID_COLUMN_NAME,
          eventRecordID);
      eventRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_EVENT_COLUMN_NAME,
          eventType);
      eventRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_SOURCE_COLUMN_NAME,
          eventSource);
      eventRecord.setStringValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_STATUS_COLUMN_NAME,
          EventStatus.PENDING.getCode());
      eventRecord.setLongValue(
          AssetReceptionDatabaseConstants.ASSET_RECEPTION_EVENTS_RECORDED_TIMESTAMP_COLUMN_NAME,
          unixTime);
      databaseTable.insertRecord(eventRecord);
      LOG.info(
          "record:"
              + eventRecord.getStringValue(
                  AssetReceptionDatabaseConstants
                      .ASSET_RECEPTION_EVENTS_RECORDED_TABLE_FIRST_KEY_COLUMN));

    } catch (CantExecuteDatabaseOperationException exception) {

      throw new CantSaveEventException(
          exception, "Saving new event.", "Cannot open or find the Asset Reception database");
    } catch (CantInsertRecordException exception) {

      throw new CantSaveEventException(
          exception, "Saving new event.", "Cannot insert a record in Asset Reception database");
    } catch (Exception exception) {

      throw new CantSaveEventException(
          FermatException.wrapException(exception), "Saving new event.", "Unexpected exception");
    }
  }
 public MapPane(int w, int h, Group tileMap) {
   Logger.getGlobal().setLevel(Level.ALL);
   this.tileMap = tileMap;
   tileMap.setFocusTraversable(true);
   this.addEventHandler(KeyEvent.KEY_PRESSED, new KeyPressedListener(this));
   this.addEventHandler(KeyEvent.KEY_RELEASED, new KeyReleasedListener(this));
   this.addEventHandler(MouseEvent.MOUSE_PRESSED, new MousePressedListener(this));
   this.addEventHandler(ScrollEvent.SCROLL, new MouseWheelListener(this));
   this.setFocusTraversable(true);
   this.requestFocus();
   try {
     initTiles();
     initMap();
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Пример #28
0
  private void createDefaultSetting(Path pSettings) {
    try {
      JSONObject jsonConf = new JSONObject();
      jsonConf.put("paddingLeft", 0);
      jsonConf.put("paddingTop", 0);
      jsonConf.put("fontSize", 8);
      jsonConf.put("printAreaTop", 0);
      jsonConf.put("printAreaLeft", 0);
      jsonConf.put("printAreaWidth", 80);
      jsonConf.put("printAreaHeight", 160);
      jsonConf.put("pageWidth", 80);
      jsonConf.put("pageHeight", 160);
      jsonConf.put("printerName", "");
      Files.write(pSettings.resolve("settings.json"), jsonConf.toString().getBytes());

    } catch (JSONException | IOException e) {
      Logger.getGlobal().log(Level.SEVERE, null, e);
    }
  }
  private void testIssueSingleAsset() throws CantIssueDigitalAssetsException {
    Logger LOG = Logger.getGlobal();
    LOG.info("MAP_TEST_SINGLE");
    DigitalAsset digitalAsset = new DigitalAsset();
    digitalAsset.setGenesisAmount(100000);
    digitalAsset.setDescription("TestAsset");
    digitalAsset.setName("testName");
    digitalAsset.setPublicKey(new ECCKeyPair().getPublicKey());
    LOG.info("MAP_DigitalAsset:" + digitalAsset);
    List<Resource> resources = new ArrayList<>();
    digitalAsset.setResources(resources);

    digitalAsset.setIdentityAssetIssuer(null);
    DigitalAssetContract digitalAssetContract = new DigitalAssetContract();
    digitalAsset.setContract(digitalAssetContract);
    LOG.info("MAP_DigitalAsset2:" + digitalAsset);

    this.issueAssets(
        digitalAsset, 1, new ECCKeyPair().getPublicKey(), BlockchainNetworkType.REG_TEST);
  }
Пример #30
0
  public static <T extends Number> ArrayList<ArrayList<T>> getTranspose(
      ArrayList<ArrayList<T>> a, Class<T> type) {
    try {
      int rows = a.size();
      int columns = a.get(0).size();

      ArrayList<ArrayList<T>> transpose = new ArrayList<ArrayList<T>>();
      for (int i = 0; i < columns; i++) {
        ArrayList<T> row = new ArrayList<>();
        for (int j = 0; j < rows; j++) {
          row.add(a.get(j).get(i));
        }
        transpose.add(row);
      }
      return transpose;
    } catch (NullPointerException e) {
      Logger.getGlobal().log(Level.SEVERE, "cannot transpose null matrix!");
      e.printStackTrace();
      return null;
    }
  }