コード例 #1
1
ファイル: HuffmanTree.java プロジェクト: zdavatz/elexis
 /**
  * Construct a frequency table from an InputStream. This will create a temporary file to copy the
  * InputStream in.
  *
  * @param source the Input Stream
  * @return an InputStream which is a copy of the source Stream, provided to re-Read the same Bytes
  *     for the actual compression process.
  */
 public InputStream constructTable(InputStream source, boolean copy) {
   freq = new int[TABLESIZE];
   try {
     File file = null;
     FileOutputStream fos = null;
     if (copy == true) {
       file = File.createTempFile("huf", "tmp");
       file.deleteOnExit();
       fos = new FileOutputStream(file);
     }
     while (source.available() != 0) {
       int c = source.read();
       freq[c]++;
       if (copy) fos.write(c);
     }
     source.close();
     if (copy) {
       fos.close();
       return new FileInputStream(file);
     }
     return null;
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
コード例 #2
0
ファイル: Script.java プロジェクト: hilotec/elexis-3-core
 /**
  * Execute a script that is part of the call
  *
  * @param call e.g. scriptname(a="foo",b="bar")
  * @param objects some Objects to cinvert in the script
  * @return the result of the interpreter
  * @throws ElexisException if no such scruiopt was found or an error occurred
  */
 public static Object executeScript(String call, PersistentObject... objects)
     throws ElexisException {
   call = call.trim();
   String name = call;
   String params = null;
   int x = name.indexOf('(');
   if (x != -1) {
     name = call.substring(0, x);
     params = call.substring(x + 1, call.length() - 1);
   }
   Query<Script> qbe = new Query<Script>(Script.class);
   qbe.add("ID", Query.EQUALS, PREFIX + name);
   List<Script> found = qbe.execute();
   if (found.size() == 0) {
     throw new ElexisException(
         Script.class,
         "A Script with this name was not found " + name,
         ElexisException.EE_NOT_FOUND);
   }
   Script script = found.get(0);
   try {
     return script.execute(params, objects);
   } catch (Exception e) {
     ExHandler.handle(e);
     throw new ElexisException(
         Script.class,
         "Error while executing " + name + ": " + e.getMessage(),
         ElexisException.EE_UNEXPECTED_RESPONSE);
   }
 }
コード例 #3
0
 protected PersistentObject doCreateTemplate(Class<? extends PersistentObject> typ) {
   try {
     return (PersistentObject) typ.newInstance();
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
コード例 #4
0
ファイル: HuffmanTree.java プロジェクト: zdavatz/elexis
 /**
  * Reloads a frequency table as saved by saveTable
  *
  * @return the table
  */
 public static int[] loadTable(InputStream in) {
   try {
     int l = in.read();
     l |= (in.read() << 8);
     byte[] tbl = new byte[l];
     for (int i = 0; i < tbl.length; i++) {
       tbl[i] = (byte) in.read();
     }
     return expandTable(tbl);
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
コード例 #5
0
ファイル: HuffmanTree.java プロジェクト: zdavatz/elexis
 /**
  * Creates a compacted form of the actual frequency table and saves it into an OutputStream.
  *
  * @return true on success
  */
 public boolean saveTable(OutputStream out) {
   byte[] tbl = compactTable(freq);
   try {
     short l = (short) tbl.length;
     out.write(l & 0xff);
     out.write(l >> 8);
     for (int i = 0; i < tbl.length; i++) {
       out.write(tbl[i]);
     }
     return true;
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return false;
   }
 }
コード例 #6
0
ファイル: HuffmanTree.java プロジェクト: zdavatz/elexis
 /** constructs a frequency table from a file */
 public static int[] constructTable(RandomAccessFile file) {
   int[] ret = new int[TABLESIZE];
   try {
     file.seek(0L);
     long l = file.length();
     for (long i = 0; i < l; i++) {
       int c = file.read();
       ret[c]++;
     }
     return ret;
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
コード例 #7
0
ファイル: Note.java プロジェクト: jsigle/elexis-base
 /**
  * Create a new Note with text content
  *
  * @param parent the parent note or null if this is a top level note
  * @param title a Title for this note
  * @param text the text content of this note
  */
 public Note(Note parent, String title, String text) {
   create(null);
   set(
       new String[] {FLD_TITLE, FLD_DATE, FLD_MIMETYPE},
       title,
       new TimeTool().toString(TimeTool.DATE_GER),
       "text/plain"); //$NON-NLS-1$
   try {
     setContent(text.getBytes("utf-8")); // $NON-NLS-1$
   } catch (UnsupportedEncodingException e) {
     ExHandler.handle(e);
     // should never happen
   }
   if (parent != null) {
     set(FLD_PARENT, parent.getId());
   }
 }
コード例 #8
0
  public boolean importExcel(final String file, final IProgressMonitor moni) {
    ExcelWrapper exw = new ExcelWrapper();
    exw.load(file, 0);
    // Please keep in sync with doc/import.textile !!
    List<String> row = exw.getRow(exw.getFirstRow()); // we load the first
    // row to figure out
    // whether we know
    // the format
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA1"); // $NON-NLS-1$
      for (String field : row) {
        digest.update(field.getBytes("iso-8859-1")); // $NON-NLS-1$
      }
      byte[] dg = digest.digest();
      String vgl = BinConverter.bytesToHexStr(dg);
      log.info(
          Messages.KontaktImporterBlatt_Importing
              + " SHA1 war "
              + vgl
              + //$NON-NLS-1$
              "\nFirst row was: "
              + row); //$NON-NLS-1$

      if (vgl.equals(PRESET_RUSSI)) {
        return Presets.importRussi(exw, bKeepID, moni);
      } else if (vgl.equals(PRESET_UNIVERSAL)) {
        return Presets.importUniversal(exw, bKeepID, moni);
      } else if (vgl.equals(PRESET_HERTEL)) {
        return Presets.importHertel(exw, bKeepID, moni);
      } else {
        SWTHelper.showError(
            Messages.KontaktImporterBlatt_DatatypeErrorHeading,
            Messages.KontaktImporterBlatt_DatatypeErrorText,
            Messages.KontaktImporterBlatt_DatatypeErrorExplanation
                + " SHA1 was "
                + vgl); //$NON-NLS-1$
      }
    } catch (Exception ex) {
      ExHandler.handle(ex);
    }

    return false;
  }
コード例 #9
0
  /**
   * Create an object of a derived class given a pseudo de-serialization code, e.g. <code>
   * ch.elexis.artikel_ch.data.Medikament::ca8bb5c27bdd67d5f011821</code>. If the object can not be
   * created by the core, all plug-ins contributing a {@link #PersistentObjectFactory()} are
   * queried.
   *
   * @param code the storeToString as shown in the above example
   * @param dbConnection the db connection used by the created PersistenObject, if not defined
   *     default is used
   * @return the de-serialized object, or <code>null</code>
   */
  public PersistentObject createFromString(String code, DBConnection dbConnection) {
    if (code == null) {
      return null;
    }

    String[] ci = code.split(StringConstants.DOUBLECOLON);
    if (ci.length != 2) return null;

    PersistentObject ret = null;
    // try to resolve factory from cache
    PersistentObjectFactory persistentObjectFactory = poFactoryCache.get(ci[0]);
    if (persistentObjectFactory != null) {
      ret = persistentObjectFactory.createFromString(code);
      ret.setDBConnection(dbConnection);
      return ret;
    }

    try {
      Class clazz = Class.forName(ci[0]);
      Method load = clazz.getMethod("load", new Class[] {String.class});
      ret = (PersistentObject) (load.invoke(null, new Object[] {ci[1]}));
      ret.setDBConnection(dbConnection);
      return ret;
    } catch (ClassNotFoundException ex) {
      List<PersistentObjectFactory> contributedFactories =
          Extensions.getClasses(ExtensionPointConstantsData.PERSISTENT_REFERENCE, CLASS);
      for (PersistentObjectFactory po : contributedFactories) {
        ret = po.createFromString(code);
        if (ret != null) {
          // found a responsible factory, cache it
          poFactoryCache.put(ci[0], po);
          ret.setDBConnection(dbConnection);
          return ret;
        }
      }
    } catch (Exception ex) {
      ExHandler.handle(ex);
      return ret;
    }
    return ret;
  }
コード例 #10
0
ファイル: FileTool.java プロジェクト: zdavatz/elexis
 /**
  * TODO: Kommentar
  *
  * @param file
  * @return
  */
 public static byte[] checksum(File file) {
   MD5Digest md5 = new MD5Digest();
   try {
     FileInputStream in = new FileInputStream(file);
     byte[] arr = new byte[65535];
     int num;
     do {
       num = in.read(arr);
       if (num == -1) {
         break;
       }
       md5.update(arr, 0, num);
     } while (num == arr.length);
     byte[] ret = new byte[16];
     md5.doFinal(ret, 0);
     return ret;
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
コード例 #11
0
ファイル: FileTool.java プロジェクト: rgwch/elexis-3-core
 /**
  * Generate the md5 checksum
  *
  * @param file
  * @return
  * @since 3.0.0 this has been replaced by a java internal method to move away from bouncycastle
  *     dependency
  */
 public static byte[] checksum(File file) {
   try {
     MessageDigest md5 = MessageDigest.getInstance("MD5");
     FileInputStream in = new FileInputStream(file);
     byte[] arr = new byte[65535];
     int num;
     do {
       num = in.read(arr);
       if (num == -1) {
         break;
       }
       md5.update(arr, 0, num);
     } while (num == arr.length);
     in.close();
     byte[] ret = new byte[16];
     md5.digest(ret, 0, 16);
     return ret;
   } catch (Exception ex) {
     ExHandler.handle(ex);
     return null;
   }
 }
コード例 #12
0
 public void doExport(String filename, List<Termin> termine) {
   try {
     CSVWriter csv = new CSVWriter(new FileWriter(filename));
     String[] header =
         new String[] {
           "UUID",
           "Bereich",
           "Typ",
           "Datum",
           "Startzeit",
           "Dauer",
           "Grund",
           "Patient-UUID-oder-Name"
         };
     String[] fields =
         new String[] {
           "ID",
           Termin.FLD_BEREICH,
           Termin.FLD_TERMINTYP,
           Termin.FLD_TAG,
           Termin.FLD_BEGINN,
           Termin.FLD_DAUER,
           Termin.FLD_GRUND,
           Termin.FLD_PATIENT
         };
     csv.writeNext(header);
     for (Termin t : termine) {
       String[] line = new String[fields.length];
       t.get(fields, line);
       csv.writeNext(line);
     }
     csv.close();
     SWTHelper.showInfo(
         "Termine exportiert", "Der Export nach " + filename + " ist abgeschlossen");
   } catch (Exception ex) {
     ExHandler.handle(ex);
     SWTHelper.showError("Fehler", ex.getMessage());
   }
 }
コード例 #13
0
ファイル: Script.java プロジェクト: hilotec/elexis-3-core
  /**
   * @param name
   * @return
   * @throws ElexisException if the script interpreter can not successfully be loaded or is not
   *     available.
   */
  private static Interpreter getInterpreter(String name) throws ElexisException {
    if (name == null) name = INTERPRETER_BEANSHELL;

    List<IConfigurationElement> scripters =
        Extensions.getExtensions(ExtensionPointConstantsData.SCRIPTING);
    for (IConfigurationElement scripter : scripters) {
      if (scripter.getAttribute("name").equals(name)) {
        try {
          return (Interpreter) scripter.createExecutableExtension("class");
        } catch (CoreException e) {
          ExHandler.handle(e);
          throw new ElexisException(
              Script.class,
              "Could not load intepreter " + e.getMessage(),
              ElexisException.EE_NOT_SUPPORTED);
        }
      }
    }
    throw new ElexisException(
        Script.class,
        name + " interpreter plug-in not available",
        ElexisException.EE_NOT_SUPPORTED);
  }
コード例 #14
0
ファイル: FileTool.java プロジェクト: zdavatz/elexis
  /**
   * Kopiert Datei
   *
   * <p>src nach
   *
   * <p>dest .
   *
   * @param src Quelldatei
   * @param dest Zieldatei
   * @param if_exists <br>
   *     <li>REPLACE_IF_EXISTS
   *     <li>BACKUP_IF_EXISTS
   *     <li>FAIL_IF_EXISTS
   * @return
   */
  public static boolean copyFile(File src, File dest, int if_exists) {
    if (src.canRead() == false) {
      log.log(
          MessageFormat.format(
              Messages.getString("FileTool.cantReadSource"), src.getAbsolutePath()),
          Log.ERRORS); // $NON-NLS-1$
      return false;
    }
    if (dest.exists()) {
      String pname = dest.getAbsolutePath();
      if (pname.equalsIgnoreCase(src.getAbsolutePath())) {
        return true;
      }
      switch (if_exists) {
        case REPLACE_IF_EXISTS:
          if (dest.delete() == false) {
            log.log(
                MessageFormat.format(
                    Messages.getString("FileTool.cantDeleteTarget"), dest.getAbsolutePath()),
                Log.ERRORS); // $NON-NLS-1$
            return false;
          }
          break;
        case BACKUP_IF_EXISTS:
          File bak = new File(pname + ".bak");
          if (bak.exists() == true) {
            if (bak.delete() == false) {
              log.log(
                  MessageFormat.format(
                      Messages.getString("FileTool.backupExists"), bak.getAbsolutePath()),
                  Log.ERRORS); // $NON-NLS-1$
              return false;
            }
          }
          if (dest.renameTo(bak) == false) {
            log.log(
                MessageFormat.format(
                    Messages.getString("FileTool.cantRenameTarget"), bak.getAbsolutePath()),
                Log.ERRORS); // $NON-NLS-1$
            return false;
          }
          dest = new File(pname);
          break;
        case FAIL_IF_EXISTS:
          log.log(
              MessageFormat.format(
                  Messages.getString("FileTool.targetExists"), dest.getAbsolutePath()),
              Log.ERRORS); // $NON-NLS-1$
          return false;
        default:
          log.log(
              MessageFormat.format(
                  Messages.getString("FileTool.badCopyMode"), src.getAbsolutePath(), if_exists),
              Log.ERRORS); // $NON-NLS-1$
          return false;
      }
    }

    // Copy data
    BufferedOutputStream bos = null;
    BufferedInputStream bis = null;
    try {
      if (dest.createNewFile() == false) {
        log.log(
            MessageFormat.format(
                Messages.getString("FileTool.couldnotcreate"), dest.getAbsolutePath()),
            Log.ERRORS); // $NON-NLS-1$
        return false;
      }
      if (dest.canWrite() == false) {
        log.log(
            MessageFormat.format(
                Messages.getString("FileTool.cantWriteTarget"), dest.getAbsolutePath()),
            Log.ERRORS); // $NON-NLS-1$
        return false;
      }

      bos = new BufferedOutputStream(new FileOutputStream(dest));
      bis = new BufferedInputStream(new FileInputStream(src));
      byte[] buffer = new byte[131072];
      while (true) {
        int r = bis.read(buffer);
        if (r == -1) {
          break;
        }
        bos.write(buffer, 0, r);
      }
    } catch (IOException ex) {
      ExHandler.handle(ex);
      log.log(
          MessageFormat.format(
              Messages.getString("FileTool.cantCopy"), dest.getAbsolutePath(), ex.getMessage()),
          Log.ERRORS); // $NON-NLS-1$
      return false;
    } finally {
      try {
        if (bis != null) {
          bis.close();
        }
        if (bos != null) {
          bos.close();
        }
      } catch (IOException e) {
        log.log(e.getMessage(), Log.WARNINGS);
      }
    }
    return true;
  }
コード例 #15
0
  /** Print the bill(s) */
  public Result<Rechnung> doOutput(
      final TYPE type, final Collection<Rechnung> rnn, Properties props) {
    IWorkbenchPage rnPage;
    final Result<Rechnung> result = new Result<Rechnung>(); // =new
    // Result<Rechnung>(Log.ERRORS,99,"Not
    // yet implemented",null,true);
    rnPage = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
    IProgressService progressService = PlatformUI.getWorkbench().getProgressService();
    final Result<Rechnung> res = new Result<Rechnung>();

    try {
      final RnPrintView rnp = (RnPrintView) rnPage.showView(RnPrintView.ID);
      progressService.runInUI(
          PlatformUI.getWorkbench().getProgressService(),
          new IRunnableWithProgress() {
            public void run(final IProgressMonitor monitor) {
              monitor.beginTask("Drucke Rechnungen", rnn.size() * 10);
              int errors = 0;
              for (Rechnung rn : rnn) {
                try {
                  result.add(rnp.doPrint(rn));
                  monitor.worked(10);
                  if (!result.isOK()) {
                    String errms = "Rechnung " + rn.getNr() + "konnte nicht gedruckt werden";
                    res.add(Result.SEVERITY.ERROR, 1, errms, rn, true);
                    errors++;
                    continue;
                  }
                  int status_vorher = rn.getStatus();
                  if ((status_vorher == RnStatus.OFFEN)
                      || (status_vorher == RnStatus.MAHNUNG_1)
                      || (status_vorher == RnStatus.MAHNUNG_2)
                      || (status_vorher == RnStatus.MAHNUNG_3)) {
                    rn.setStatus(status_vorher + 1);
                  }
                  rn.addTrace(
                      Rechnung.OUTPUT,
                      getDescription() + ": " + RnStatus.getStatusText(rn.getStatus()));
                } catch (Exception ex) {
                  SWTHelper.showError(
                      "Fehler beim Drucken der Rechnung " + rn.getRnId(), ex.getMessage());
                  errors++;
                }
              }
              monitor.done();
              if (errors == 0) {
                SWTHelper.showInfo("OK", "OK");
              } else {
                SWTHelper.showError("Fehler", "Fehler");
              }
            }
          },
          null);

      rnPage.hideView(rnp);

    } catch (Exception ex) {
      ExHandler.handle(ex);
      res.add(Result.SEVERITY.ERROR, 2, ex.getMessage(), null, true);
      ErrorDialog.openError(null, "Exception", "Exception", ResultAdapter.getResultAsStatus(res));
      return res;
    }
    if (!result.isOK()) {
      ResultAdapter.displayResult(result, "Fehler beim Rechnungsdruck");
    }
    return result;
  }
コード例 #16
0
  /**
   * Import a medicament from one row of the BAG-Medi file
   *
   * @param row
   *     <pre>
   * 		row[0] = ID,bzw Name
   * 		row[1] = Generikum
   * 		row[2] = Pharmacode
   * 	 	row[3] = BAG-Dossier
   * 		row[4] = Swissmedic-Nr
   * 		row[5] = Swissmedic-Liste
   * 	 	row[6]
   * 		row[7] = Namen
   * 		row[8] = EK-Preis
   *      row[9] = VK-Preis
   *      row[10]= Limitatio (Y/N)
   *      row[11]= LimitatioPts
   *      row[12]= Gruppe (optional)
   *      row[13]= Substance (optional)
   * </pre>
   *
   * @return
   */
  public static boolean importUpdate(final String[] row) throws ElexisException {
    String pharmacode = "0";
    BAGMedi imp = null;
    // Kein Pharmacode, dann nach Name suchen
    if (StringTool.isNothing(row[2].trim())) {
      String mid = qbe.findSingle(Artikel.FLD_NAME, "=", row[7]);
      if (mid != null) {
        imp = BAGMedi.load(mid);
      }
    } else {
      try {
        // strip leading zeroes
        int pcode = Integer.parseInt(row[2].trim());
        pharmacode = Integer.toString(pcode);

      } catch (Exception ex) {
        ExHandler.handle(ex);
        log.log(Level.WARNING, "Pharmacode falsch: " + row[2]);
      }

      qbe.clear(true);
      qbe.add(Artikel.FLD_SUB_ID, "=", pharmacode);
      qbe.or();
      qbe.add(Artikel.FLD_SUB_ID, Query.EQUALS, row[2].trim());
      List<Artikel> lArt = qbe.execute();
      if (lArt == null) {
        throw new ElexisException(
            BAGMediImporter.class,
            "Article list was null while scanning for " + pharmacode,
            ElexisException.EE_UNEXPECTED_RESPONSE,
            true);
      }
      if (lArt.size() > 1) {
        // Duplikate entfernen, genau einen gültigen und existierenden Artikel behalten
        Iterator<Artikel> it = lArt.iterator();
        boolean hasValid = false;
        Artikel res = null;
        while (it.hasNext()) {
          Artikel ax = it.next();
          if (hasValid || (!ax.isValid())) {
            if (res == null) {
              res = ax;
            }
            it.remove();
          } else {
            hasValid = true;
          }
        }
        if (!hasValid) {
          if (res != null) {
            if (res.isDeleted()) {
              res.undelete();
              lArt.add(res);
            }
          }
        }
      }
      imp = lArt.size() > 0 ? BAGMedi.load(lArt.get(0).getId()) : null;
    }
    if (imp == null || (!imp.isValid())) {
      imp = new BAGMedi(row[7], pharmacode);

      String sql =
          new StringBuilder()
              .append("INSERT INTO ")
              .append(BAGMedi.EXTTABLE)
              .append(" (ID) VALUES (")
              .append(imp.getWrappedId())
              .append(");")
              .toString();
      PersistentObject.getConnection().exec(sql);

    } else {

      String sql =
          new StringBuilder()
              .append("SELECT ID FROM ")
              .append(BAGMedi.EXTTABLE)
              .append(" WHERE ID=")
              .append(imp.getWrappedId())
              .toString();
      String extid = PersistentObject.getConnection().queryString(sql);
      if (extid == null) {
        sql =
            new StringBuilder()
                .append("INSERT INTO ")
                .append(BAGMedi.EXTTABLE)
                .append(" (ID) VALUES (")
                .append(imp.getWrappedId())
                .append(");")
                .toString();
        PersistentObject.getConnection().exec(sql);
      }
    }
    imp.update(row);
    return true;
  }