コード例 #1
0
ファイル: Chemkin.java プロジェクト: ecintron/RMG-Java
  // ## operation checkChemkinMessage()
  public void checkChemkinMessage() {
    // #[ operation checkChemkinMessage()
    try {
      String dir = System.getProperty("RMG.workingDirectory");
      String filename = "chemkin/chem.message";
      FileReader fr = new FileReader(filename);
      BufferedReader br = new BufferedReader(fr);

      String line = br.readLine().trim();
      if (line.startsWith("NO ERRORS FOUND ON INPUT")) {
        return;
      } else if (line.startsWith("WARNING...THERE IS AN ERROR IN THE LINKING FILE")) {
        System.out.println("Error in chemkin linking to reactor!");
        System.exit(0);
      } else {
        System.out.println("Unknown message in chem.message!");
        System.exit(0);
      }
    } catch (Exception e) {
      System.out.println("Can't read chem.message!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    // #]
  }
コード例 #2
0
ファイル: Chemkin.java プロジェクト: ecintron/RMG-Java
  // ## operation runReactor()
  public void runReactor() {
    // #[ operation runReactor()
    // run reactor
    String dir = System.getProperty("RMG.workingDirectory");

    try {
      // system call for reactor
      String[] command = {dir + "/software/reactorModel/reactor.exe"};
      File runningDir = new File("chemkin");
      Process reactor = Runtime.getRuntime().exec(command, null, runningDir);
      InputStream ips = reactor.getInputStream();
      InputStreamReader is = new InputStreamReader(ips);
      BufferedReader br = new BufferedReader(is);
      String line = null;
      while ((line = br.readLine()) != null) {
        // System.out.println(line);
      }
      int exitValue = reactor.waitFor();
    } catch (Exception e) {
      System.out.println("Error in running reactor!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    // #]
  }
コード例 #3
0
  /** ** Main entery point for debugging/testing */
  public static void main(String argv[]) {
    RTConfig.setCommandLineArgs(argv);
    Print.setAllOutputToStdout(true);
    Print.setEncoding(ENCODING_UTF8);
    String accountID = RTConfig.getString(ARG_ACCOUNT, "demo");
    GoogleGeocodeV2 gn = new GoogleGeocodeV2("google", null, null);

    /* reverse geocode */
    if (RTConfig.hasProperty(ARG_REVGEOCODE)) {
      GeoPoint gp = new GeoPoint(RTConfig.getString(ARG_REVGEOCODE, null));
      if (!gp.isValid()) {
        Print.logInfo("Invalid GeoPoint specified");
        System.exit(1);
      }
      Print.logInfo("Reverse-Geocoding GeoPoint: " + gp);
      Print.sysPrintln(
          "RevGeocode = " + gn.getReverseGeocode(gp, null /*localeStr*/, false /*cache*/));
      // Note: Even though the values are printed in UTF-8 character encoding, the
      // characters may not appear to be property displayed if the console display
      // does not support UTF-8.
      System.exit(0);
    }

    /* no options */
    Print.sysPrintln("No options specified");
    System.exit(1);
  }
コード例 #4
0
ファイル: ObjectXml.java プロジェクト: pouncilt/vps-avs
 private ClassLoaderStrategy getClassLoaderStrategy(String fullyQualifiedClassName)
     throws Exception {
   try {
     // Get just the package name
     StringBuffer sb = new StringBuffer(fullyQualifiedClassName);
     sb.delete(sb.lastIndexOf("."), sb.length());
     currentPackage = sb.toString();
     // Retrieve the Java classpath from the system properties
     String cp = System.getProperty("java.class.path");
     String sepChar = System.getProperty("path.separator");
     String[] paths = StringUtils.pieceList(cp, sepChar.charAt(0));
     ClassLoaderStrategy cl =
         ClassLoaderUtil.getClassLoader(ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {});
     // Iterate through paths until class with the specified name is found
     String classpath = StringUtils.replaceChar(currentPackage, '.', File.separatorChar);
     for (int i = 0; i < paths.length; i++) {
       Class[] classes = cl.getClasses(paths[i] + File.separatorChar + classpath, currentPackage);
       for (int j = 0; j < classes.length; j++) {
         if (classes[j].getName().equals(fullyQualifiedClassName)) {
           return ClassLoaderUtil.getClassLoader(
               ClassLoaderUtil.FILE_SYSTEM_CLASS_LOADER, new String[] {paths[i]});
         }
       }
     }
     throw new Exception("Class could not be found.");
   } catch (Exception e) {
     System.err.println("Exception creating class loader strategy.");
     System.err.println(e.getMessage());
     throw e;
   }
 }
コード例 #5
0
  @Override
  public VPackage parse() {

    logger.debug("Starting parsing package: " + xmlFile.getAbsolutePath());

    long startParsing = System.currentTimeMillis();

    try {
      Document document = getDocument();
      Element root = document.getDocumentElement();

      _package = new VPackage(xmlFile);

      Node name = root.getElementsByTagName(EL_NAME).item(0);
      _package.setName(name.getTextContent());
      Node descr = root.getElementsByTagName(EL_DESCRIPTION).item(0);
      _package.setDescription(descr.getTextContent());

      NodeList list = root.getElementsByTagName(EL_CLASS);

      boolean initPainters = false;
      for (int i = 0; i < list.getLength(); i++) {
        PackageClass pc = parseClass((Element) list.item(i));
        if (pc.getPainterName() != null) {
          initPainters = true;
        }
      }

      if (initPainters) {
        _package.initPainters();
      }

      logger.info(
          "Parsing the package '{}' finished in {}ms.\n",
          _package.getName(),
          (System.currentTimeMillis() - startParsing));
    } catch (Exception e) {
      collector.collectDiagnostic(e.getMessage(), true);
      if (RuntimeProperties.isLogDebugEnabled()) {
        e.printStackTrace();
      }
    }

    try {
      checkProblems("Error parsing package file " + xmlFile.getName());
    } catch (Exception e) {
      return null;
    }

    return _package;
  }
コード例 #6
0
 protected void check() {
   if (map == null) {
     Connection connection = null;
     Statement statement = null;
     ResultSet results = null;
     try {
       connection = dataSource.getConnection();
       statement = connection.createStatement();
       long start = System.currentTimeMillis();
       String s = getFindSql(identifier);
       if (log.isTraceEnabled()) {
         log.trace("About to execute " + s + " because ", new Exception());
       }
       results = statement.executeQuery(s);
       ResultSetMetaData meta = results.getMetaData();
       map = new HashMap<String, String>();
       if (results.next()) {
         for (int i = 1; i <= meta.getColumnCount(); i++) {
           String value = org.mmbase.util.Casting.toString(results.getString(i));
           map.put(meta.getColumnName(i).toLowerCase(), value);
         }
       }
       long duration = (System.currentTimeMillis() - start);
       if (duration > 500) {
         log.warn("Executed " + s + " in " + duration + " ms");
       } else if (duration > 100) {
         log.debug("Executed " + s + " in " + duration + " ms");
       } else {
         log.trace("Executed " + s + " in " + duration + " ms");
       }
     } catch (Exception e) {
       throw new RuntimeException(e.getMessage(), e);
     } finally {
       if (results != null)
         try {
           results.close();
         } catch (Exception e) {
         }
       if (statement != null)
         try {
           statement.close();
         } catch (Exception e) {
         }
       if (connection != null)
         try {
           connection.close();
         } catch (Exception e) {
         }
     }
   }
 }
コード例 #7
0
ファイル: XMLUtil.java プロジェクト: tpso-src/thirdparty
  private static SAXParserFactory createFastSAXParserFactory()
      throws ParserConfigurationException, SAXException {
    if (fastParserFactoryClass == null) {
      try {
        fastParserFactoryClass =
            Class.forName("org.apache.crimson.jaxp.SAXParserFactoryImpl"); // NOI18N
      } catch (Exception ex) {
        useFastSAXParserFactory = false;
        if (System.getProperty("java.version").startsWith("1.4")) { // NOI18N
          ErrorManager.getDefault().notify(ErrorManager.INFORMATIONAL, ex);
        }
      }
    }
    if (fastParserFactoryClass != null) {
      try {
        SAXParserFactory factory = (SAXParserFactory) fastParserFactoryClass.newInstance();

        return factory;
      } catch (Exception ex) {
        useFastSAXParserFactory = false;
        throw new ParserConfigurationException(ex.getMessage());
      }
    }

    return SAXParserFactory.newInstance();
  }
コード例 #8
0
  public static List<GenerationTarget> getTargets() {
    if (m_targets != null) {
      return m_targets;
    }

    m_targets = new ArrayList<GenerationTarget>();

    URL location = getClassLocation();

    if (location == null) return m_targets;

    if (location.getProtocol().equals("file")) {
      String encoded = location.getFile();
      File classFileLocation = null;
      try {
        String decoded = URLDecoder.decode(encoded, "UTF-8"); // important
        classFileLocation = new File(decoded);

      } catch (UnsupportedEncodingException ex) {
        ex.printStackTrace();
      } // end try
      if (classFileLocation != null) {
        File root = classFileLocation;
        String classname = GenerationTarget.class.getName();
        int levels = countNbChars(classname, '.');

        // iterate to the root
        for (int i = 0; i < levels; i++) {
          root = root.getParentFile();
        } // end while

        scanFolder(classFileLocation.getParentFile(), root, m_targets);
      }
    } else if (location.getProtocol().equals("jar")) {
      String jarname = location.toExternalForm();
      int index = jarname.indexOf(".jar!");
      if (index > -1) jarname = jarname.substring(0, index + 4);
      index = jarname.indexOf("jar:");
      if (index > -1) {
        jarname = jarname.substring(4);
      }
      index = jarname.indexOf("file:/");
      if (index > -1) {
        jarname = jarname.substring(6);
      }
      index = jarname.indexOf("file:");
      if (index > -1) {
        jarname = jarname.substring(5);
      }
      scanJar(new File(jarname), new File(System.getProperty("java.io.tmpdir")), m_targets);
    }

    return m_targets;
  }
コード例 #9
0
  /**
   * @param args 1. rddl description file name (can be directory), in RDDL format, with complete
   *     path 2. (optional) port number 3. (optional) random seed
   */
  public static void main(String[] args) {

    // StateViz state_viz = new GenericScreenDisplay(true);
    StateViz state_viz = new NullScreenDisplay(false);

    ArrayList<RDDL> rddls = new ArrayList<RDDL>();
    int port = PORT_NUMBER;
    if (args.length < 1) {
      System.out.println(
          "usage: rddlfilename (optional) portnumber random-seed state-viz-class-name");
      System.out.println("\nexample 1: Server rddlfilename");
      System.out.println("example 2: Server rddlfilename 2323");
      System.out.println("example 3: Server rddlfilename 2323 0 rddl.viz.GenericScreenDisplay");
      System.exit(1);
    }

    try {
      // Load RDDL files
      RDDL rddl = new RDDL();
      File f = new File(args[0]);
      if (f.isDirectory()) {
        for (File f2 : f.listFiles())
          if (f2.getName().endsWith(".rddl")) {
            System.out.println("Loading: " + f2);
            rddl.addOtherRDDL(parser.parse(f2));
          }
      } else rddl.addOtherRDDL(parser.parse(f));

      if (args.length > 1) {
        port = Integer.valueOf(args[1]);
      }
      ServerSocket socket1 = new ServerSocket(port);
      if (args.length > 2) {
        Server.rand = new Random(Integer.valueOf(args[2]));
      } else {
        Server.rand = new Random(DEFAULT_SEED);
      }
      if (args.length > 3) {
        state_viz = (StateViz) Class.forName(args[3]).newInstance();
      }
      System.out.println("RDDL Server Initialized");
      while (true) {
        Socket connection = socket1.accept();
        Runnable runnable = new Server(connection, ++ID, rddl, state_viz);
        Thread thread = new Thread(runnable);
        thread.start();
      }
    } catch (Exception e) {
      // TODO Auto-generated catch block
      System.out.println(e);
      e.printStackTrace();
    }
  }
コード例 #10
0
ファイル: Chemkin.java プロジェクト: ecintron/RMG-Java
  public static void writeChemkinInputFile(ReactionSystem rs) {
    // #[ operation writeChemkinInputFile(ReactionModel,SystemSnapshot)

    StringBuilder result = new StringBuilder();
    result.append(writeChemkinHeader());
    result.append(writeChemkinElement());
    double start = System.currentTimeMillis();
    result.append(writeChemkinSpecies(rs.reactionModel, rs.initialStatus));
    result.append(writeChemkinThermo(rs.reactionModel));
    Global.chemkinThermo = Global.chemkinThermo + (System.currentTimeMillis() - start) / 1000 / 60;
    start = System.currentTimeMillis();
    result.append(writeChemkinPdepReactions(rs));
    Global.chemkinReaction =
        Global.chemkinReaction + (System.currentTimeMillis() - start) / 1000 / 60;

    String dir = System.getProperty("RMG.workingDirectory");
    if (!dir.endsWith("/")) dir += "/";
    dir += "software/reactorModel/";
    String file = "chemkin/chem.inp";

    try {
      FileWriter fw = new FileWriter(file);
      fw.write(result.toString());
      fw.close();
    } catch (Exception e) {
      System.out.println("Error in writing chemkin input file chem.inp!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    // #]
  }
コード例 #11
0
ファイル: Test.java プロジェクト: mallampatisuresh/Glassfish
 public static void main(String args[]) {
   // is there anything to do?
   if (args.length == 0) {
     printUsage();
     System.exit(1);
   }
   if (args.length > 1) {
     if (args[1].equals("yes")) {
       fStdOut = true;
     }
   }
   new Test(args[0]);
 }
コード例 #12
0
ファイル: JaxpTest.java プロジェクト: rath/libxml2-java
  @Test
  public void parseRootElementWithFile() throws Exception {
    String xml =
        "<?xml version=\"1.0\"?><html><head /><body><p>Good morning</p><p>How are you?</p></body></html>";
    File f = new File(System.getProperty("java.io.tmpdir"), "test.xml");
    Utils.writeFile(f, xml);
    f.deleteOnExit();

    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc = builder.parse(f);
    Element root = doc.getDocumentElement();
    Assert.assertEquals("html", root.getNodeName());
  }
コード例 #13
0
ファイル: Chemkin.java プロジェクト: ecintron/RMG-Java
  // ## operation writeChemkinInputFile(ReactionModel,SystemSnapshot)
  public static void writeChemkinInputFile(
      final ReactionModel p_reactionModel, SystemSnapshot p_beginStatus) {
    // #[ operation writeChemkinInputFile(ReactionModel,SystemSnapshot)

    StringBuilder result = new StringBuilder();
    result.append(writeChemkinHeader());
    result.append(writeChemkinElement());
    double start = System.currentTimeMillis();
    result.append(writeChemkinSpecies(p_reactionModel, p_beginStatus));
    result.append(writeChemkinThermo(p_reactionModel));
    Global.chemkinThermo = Global.chemkinThermo + (System.currentTimeMillis() - start) / 1000 / 60;
    start = System.currentTimeMillis();
    result.append(
        writeChemkinPdepReactions(
            p_reactionModel, p_beginStatus)); // 10/26/07 gmagoon: changed to pass p_beginStatus
    // result.append(writeChemkinPdepReactions(p_reactionModel));
    Global.chemkinReaction =
        Global.chemkinReaction + (System.currentTimeMillis() - start) / 1000 / 60;

    String dir = System.getProperty("RMG.workingDirectory");
    if (!dir.endsWith("/")) dir += "/";
    dir += "software/reactorModel/";
    String file = "chemkin/chem.inp";

    try {
      FileWriter fw = new FileWriter(file);
      fw.write(result.toString());
      fw.close();
    } catch (Exception e) {
      System.out.println("Error in writing chemkin input file chem.inp!");
      System.out.println(e.getMessage());
      System.exit(0);
    }

    if (PDepRateConstant.getMode() == Mode.CHEBYSHEV
        || PDepRateConstant.getMode() == Mode.PDEPARRHENIUS
        || PDepRateConstant.getMode() == Mode.RATE) {
      StringBuilder gridOfRateCoeffs = new StringBuilder();
      gridOfRateCoeffs.append(writeGridOfRateCoeffs(p_reactionModel));
      String newFile = "chemkin/tableOfRateCoeffs.txt";
      try {
        FileWriter fw = new FileWriter(newFile);
        fw.write(gridOfRateCoeffs.toString());
        fw.close();
      } catch (Exception e) {
        System.out.println("Error in writing tableOfRateCoeffs.txt");
        System.out.println(e.getMessage());
        System.exit(0);
      }
    }

    // #]
  }
コード例 #14
0
 public String toString() {
   String endl = System.getProperty("line.separator");
   String str = "";
   if (numRunningJobs != -1) {
     str += "running jobs: " + numRunningJobs + endl;
   }
   if (numWaitingJobs != -1) {
     str += "waiting jobs: " + numWaitingJobs + endl;
   }
   if (usedProcessors != -1) {
     str += "used processors: " + usedProcessors + endl;
   }
   return str;
 }
コード例 #15
0
 /**
  * Parses mathml from the input into a DOM document. Split out so that subclass can call.
  *
  * @param params Parameters including MathML
  * @param result Blank result object
  * @param start Request start time (milliseconds since epoch)
  * @return Document or null if failed (in which case should return result)
  */
 protected Document parseMathml(MathsEpsParams params, MathsEpsReturn result, long start)
     throws Exception {
   try {
     Document mathml = parseMathml(params.getMathml());
     if (SHOWPERFORMANCE) {
       System.err.println("Parse DOM: " + (System.currentTimeMillis() - start));
     }
     return mathml;
   } catch (SAXParseException e) {
     int line = e.getLineNumber(), col = e.getColumnNumber();
     result.setError("MathML parse error at " + line + ":" + col + " - " + e.getMessage());
     return null;
   }
 }
コード例 #16
0
 static ArrayList<PVAR_INST_DEF> processXMLAction(DOMParser p, InputSource isrc, State state)
     throws Exception {
   try {
     // showInputSource(isrc); System.exit(1); // TODO
     p.parse(isrc);
     Element e = p.getDocument().getDocumentElement();
     if (SHOW_XML) {
       System.out.println("Received action msg:");
       printXMLNode(e);
     }
     if (!e.getNodeName().equals(ACTIONS)) {
       System.out.println("ERROR: NO ACTIONS NODE");
       System.exit(1);
       return null;
     }
     NodeList nl = e.getElementsByTagName(ACTION);
     //			System.out.println(nl);
     if (nl != null) { // && nl.getLength() > 0) { // TODO: Scott
       ArrayList<PVAR_INST_DEF> ds = new ArrayList<PVAR_INST_DEF>();
       for (int i = 0; i < nl.getLength(); i++) {
         Element el = (Element) nl.item(i);
         String name = getTextValue(el, ACTION_NAME).get(0);
         ArrayList<String> args = getTextValue(el, ACTION_ARG);
         ArrayList<LCONST> lcArgs = new ArrayList<LCONST>();
         for (String arg : args) {
           if (arg.startsWith("@")) lcArgs.add(new RDDL.ENUM_VAL(arg));
           else lcArgs.add(new RDDL.OBJECT_VAL(arg));
         }
         String pvalue = getTextValue(el, ACTION_VALUE).get(0);
         Object value = getValue(name, pvalue, state);
         PVAR_INST_DEF d = new PVAR_INST_DEF(name, value, lcArgs);
         ds.add(d);
       }
       return ds;
     } else return new ArrayList<PVAR_INST_DEF>(); // FYI: May be unreachable. -Scott
     // } else { // TODO: Removed by Scott, NOOP should not be handled differently
     //	nl = e.getElementsByTagName(NOOP);
     //	if ( nl != null && nl.getLength() > 0) {
     //		ArrayList<PVAR_INST_DEF> ds = new ArrayList<PVAR_INST_DEF>();
     //		return ds;
     //	}
     // }
   } catch (Exception e) {
     // TODO Auto-generated catch block
     System.out.println("FATAL SERVER ERROR:\n" + e);
     // t.printStackTrace();
     throw e;
     // System.exit(1);
   }
 }
コード例 #17
0
  public void saveGlyphFile(OutputStream a_output) {
    try {
      Transformer transformer = getTransformer();
      Document document = m_glyph.makeDocument();
      DOMSource source = new DOMSource(document);
      StreamResult result = new StreamResult(a_output);
      transformer.transform(source, result);
    } catch (ParserConfigurationException | TransformerException e) {
      e.printStackTrace();
    }

    m_savedTime = System.currentTimeMillis();
    m_modifiedTime = m_savedTime;
  }
コード例 #18
0
ファイル: ConfigManager.java プロジェクト: baraujo75/mojarra
    private boolean streamIsZeroLengthOrEmpty(InputStream is) throws IOException {
      boolean isZeroLengthOrEmpty = (0 == is.available());
      final int size = 1024;
      byte[] b = new byte[size];
      String s;
      while (!isZeroLengthOrEmpty && -1 != is.read(b, 0, size)) {
        s = (new String(b)).trim();
        isZeroLengthOrEmpty = 0 == s.length();
        b[0] = 0;
        for (int i = 1; i < size; i += i) {
          System.arraycopy(b, 0, b, i, ((size - i) < i) ? (size - i) : i);
        }
      }

      return isZeroLengthOrEmpty;
    }
コード例 #19
0
ファイル: AMLtoPNML.java プロジェクト: CaoAo/BeehiveZ
  /**
   * EPML2PNML
   *
   * @param args String[]
   */
  private static void EPML2PNML(String[] args) {
    if (args.length != 2) {
      System.out.println("���ṩEPML�ļ�·����PNML���Ŀ¼!");
      System.exit(-1);
    }
    epmlImport epml = new epmlImport();
    // load the single epml file
    String filename = args[0];
    try {
      EPCResult epcRes = (EPCResult) epml.importFile(new FileInputStream(filename));
      // convert all epc models to pnml files
      ArrayList<ConfigurableEPC> alEPCs = epcRes.getAllEPCs();
      PnmlExport export = new PnmlExport();
      for (ConfigurableEPC epc : alEPCs) {
        String id = epc.getIdentifier();
        if (id.equals("1An_klol")
            || id.equals("1An_l1y8")
            || id.equals("1Ex_dzq9")
            || id.equals("1Ex_e6dx")
            || id.equals("1Ku_9soy")
            || id.equals("1Ku_a4cg")
            || id.equals("1Or_lojl")
            || id.equals("1Pr_d1ur")
            || id.equals("1Pr_djki")
            || id.equals("1Pr_dkfa")
            || id.equals("1Pr_dl73")
            || id.equals("1Ve_musj")
            || id.equals("1Ve_mvwz")) continue;
        // save pnml files to the same folder
        File outFile = new File(args[1] + "/" + id + ".pnml");
        if (outFile.exists()) continue;
        FileOutputStream fos = new FileOutputStream(outFile);
        PetriNet petri = AMLtoPNML.convert(epc);
        try {
          export.export(new ProvidedObject("PetriNet", new Object[] {petri}), fos);
        } catch (Exception ex1) {
          ex1.printStackTrace(System.out);
        }
      }
    } catch (IOException ex) {
      ex.printStackTrace(System.out);
    }

    System.out.println("EPML Conversion Done");
  }
コード例 #20
0
  // El string debe estar em formato json
  public boolean updateRegistry(String dataJson) {
    try {
      // Crea objeto json con string por parametro
      JSONObject json = new JSONObject(dataJson);
      // Obtiene el array de Registos
      JSONArray arr = json.getJSONArray("Registry");
      // Recorre el array
      for (int i = 0; i < arr.length(); i++) {
        // Obtiene los datos idSensor y value
        int idSensor = arr.getJSONObject(i).getInt("idSensor");

        int value = arr.getJSONObject(i).getInt("value");
        // Recorre la configuracion de registro
        for (RegistryConf reg : registryConf) {

          // Se fija si el registro corresponde a esta configuracion
          if (reg.getIdSensor() == idSensor) {

            // Checkea el criterio para guardar, o no en la BD
            // Checkea tambien si el valor es igual al anterior
            if (reg.getSaveTypeString() == "ONCHANGE" && lastRead.get(idSensor) != value) {
              // Actualizo la ultima lectura y guardo en la BD
              lastRead.put(idSensor, value);
              saveRegistry(idSensor, value);

            } else if (reg.getSaveTypeString() == "ONTIME") {
              // Variables auxiliares, para checkear tiempo
              Long auxLong = System.currentTimeMillis() / 1000;
              int now = auxLong.intValue();
              int timeToSave = lastRead.get(idSensor) + reg.getValue();
              // Checkea si ya es tiempo para guerdar un nuevo registro
              if (now >= timeToSave) {
                // Actualizo el ultimo guardado
                lastRead.put(idSensor, now);
                saveRegistry(idSensor, value);
              }
            }
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
    return false;
  }
コード例 #21
0
  /**
   * Carica un file XML e ne restituisce un riferimento per DOM
   *
   * @param path - path to xml file
   * @return reference to xml document
   */
  private static Document loadDocument(String path) {
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(false);
    try {
      DocumentBuilder db = dbf.newDocumentBuilder();
      Document d = db.parse(new File(path));
      return d;

    } catch (ParserConfigurationException ex) {
      ex.printStackTrace();
      System.exit(10);
    } catch (SAXException sxe) {
      sxe.printStackTrace();
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
    return null;
  }
コード例 #22
0
ファイル: JaxpTest.java プロジェクト: rath/libxml2-java
  @Test
  public void testgetAttributesWithNamedNodeMap() throws Exception {
    //		builderFactory = DocumentBuilderFactory.newInstance();
    builderFactory.setNamespaceAware(true);

    File f = new File(System.getProperty("user.dir"), "src/test/resources/sample-springbeans.xml");
    DocumentBuilder builder = builderFactory.newDocumentBuilder();
    Document doc = builder.parse(f);
    Element root = doc.getDocumentElement();
    //		System.out.println("* current impl:  " + doc.getClass().getName());

    // id, class
    Map<String, String> actualMap = new HashMap<String, String>();

    NodeList list = root.getChildNodes();
    for (int i = 0; i < list.getLength(); i++) {
      Node node = list.item(i);
      if (node instanceof Element) {
        Element elem = (Element) node;
        if (elem.getTagName().equals("beans:bean")) {
          //					System.out.println("bean[" + elem.getAttribute("id") + "]");
          NamedNodeMap map = elem.getAttributes();
          String valueId = null;
          String valueClass = null;
          for (int x = 0; x < map.getLength(); x++) {
            Node attr = map.item(x);
            if (attr.getNodeName().equals("id")) valueId = attr.getNodeValue();
            if (attr.getNodeName().equals("class")) valueClass = attr.getNodeValue();
          }
          if (valueId != null && valueClass != null) actualMap.put(valueId, valueClass);
        }
      }
    }

    Map<String, String> expected = new HashMap<String, String>();
    expected.put("authenticationManager", "org.springframework.security.providers.ProviderManager");
    expected.put(
        "daoAuthenticationProvider",
        "org.springframework.security.providers.dao.DaoAuthenticationProvider");
    expected.put(
        "loggerListener", "org.springframework.security.event.authentication.LoggerListener");
    Assert.assertEquals("Attributes with NamedNodeMap", expected, actualMap);
  }
コード例 #23
0
ファイル: MainEditor.java プロジェクト: sohamm17/MainEditor
 /** Initialize the GUI */
 private void initGUI() {
   counts theApp_new_counts = new counts();
   String sysPath =
       System.getProperty("user.home") + File.separator + "SRSCKT" + File.separator + "pkg";
   File sysDir = new File(sysPath);
   // if our system folder doesn't exist it creates it
   if (!sysDir.exists()) sysDir.mkdirs();
   String[] SysPkgs = sysDir.list();
   for (String x : SysPkgs) {
     System.out.println(x);
     package_cls defaultPkgs =
         new package_cls(
             x, theApp_new_counts, 1); // sysCall is 1 as System Packages will be installed
   }
   connections theApp_new_connections = new connections();
   this.setFrame(theApp_new_counts, theApp_new_connections);
   this.setPath(null);
   this.setSaved(false); // default false
 }
コード例 #24
0
ファイル: TDTEngine.java プロジェクト: max90727/fosstrak
  /**
   * TDTEngine - constructor for a new Tag Data Translation engine
   *
   * @param confdir the string value of the path to a configuration directory consisting of two
   *     subdirectories, <code>schemes</code> and <code>auxiliary</code>.
   *     <p>When the class TDTEngine is constructed, the path to a local directory must be
   *     specified, by passing it as a single string parameter to the constructor method (without
   *     any trailing slash or file separator). e.g. <code>
   *     <pre>TDTEngine engine = new TDTEngine("/opt/TDT");</pre></code>
   *     <p>The specified directory must contain two subdirectories named auxiliary and schemes. The
   *     Tag Data Translation definition files for the various coding schemes should be located
   *     inside the subdirectory called <code>schemes</code>. Any auxiliary lookup files (such as
   *     <code>ManagerTranslation.xml</code>) should be located inside the subdirectory called
   *     <code>auxiliary</code>.
   *     <p>Files within the schemes directory ending in <code>.xml</code> are read in and
   *     unmarshalled using <a href = "http://www.castor.org">Castor</a>.
   */
  public TDTEngine(String confdir)
      throws FileNotFoundException, MarshalException, ValidationException, TDTException {
    xmldir = confdir;

    long t = System.currentTimeMillis();
    File[] dir =
        new java.io.File(confdir + File.separator + "schemes").listFiles(new XMLFilenameFilter());
    // java.util.Arrays.sort(dir); // Sort it
    if (dir == null) throw new TDTException("Cannot find schemes in " + confdir);
    Unmarshaller unmar = new Unmarshaller();
    for (File f : dir) {
      EpcTagDataTranslation tdt =
          (EpcTagDataTranslation) unmar.unmarshal(EpcTagDataTranslation.class, new FileReader(f));

      initFromTDT(tdt);
    }

    // need to populate the hashmap gs1cpi from the ManagerTranslation.xml table in auxiliary.
    // Unmarshaller unmar = new Unmarshaller();
    GEPC64Table cpilookup =
        (GEPC64Table)
            unmar.unmarshal(
                GEPC64Table.class,
                new FileReader(
                    confdir
                        + File.separator
                        + "auxiliary"
                        + File.separator
                        + "ManagerTranslation.xml"));
    for (Enumeration e = cpilookup.enumerateEntry(); e.hasMoreElements(); ) {
      Entry entry = (Entry) e.nextElement();
      String comp = entry.getCompanyPrefix();
      String indx = Integer.toString(entry.getIndex());
      gs1cpi.put(indx, comp);
      gs1cpi.put(comp, indx);
    }

    // System.out.println("Loaded schemas in " +
    //		   (System.currentTimeMillis() - t)
    //		   + " millisecs");

  }
コード例 #25
0
ファイル: Utils.java プロジェクト: Rafarel/DeathChests
  public static boolean saveTombstones(List<Tombstone> deathChests, String chestsPath) {
    long timestamp = System.currentTimeMillis();
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();

      // Create the writer
      Document xmlDoc = builder.newDocument();

      Element rootNode = xmlDoc.createElement("deathchestList");
      //	        String pluginName = Settings.getPluginName();
      String version = Settings.getVersion();
      rootNode.setAttribute("version", version);
      xmlDoc.appendChild(rootNode);

      for (Tombstone tombstone : deathChests) {
        rootNode.appendChild(
            tombstone.createXmlNode(
                xmlDoc.createElement(Utils.DEATHCHEST_XML_TAG), xmlDoc, timestamp));
      }

      // Put the XML file into domSource
      DOMSource domSource = new DOMSource(xmlDoc);

      // PrintStream will be responsible for writing
      // the text data to the file
      PrintStream ps = new PrintStream(chestsPath);
      StreamResult fileWriter = new StreamResult(ps);

      TransformerFactory transformerFactory = TransformerFactory.newInstance();
      Transformer transformer = transformerFactory.newTransformer();

      // Finally save the file
      transformer.transform(domSource, fileWriter);

      return true;
    } catch (ParserConfigurationException | TransformerException | FileNotFoundException ex) {
      System.err.println("Error while writing deathchest data:");
      ex.printStackTrace();
    }
    return false;
  }
コード例 #26
0
  @Override
  public MathsEpsReturn getEps(MathsEpsParams params) {
    long start = System.currentTimeMillis();
    MathsEpsReturn result = new MathsEpsReturn();
    result.setOk(false);
    result.setEps(EMPTY);
    result.setError("");

    try {
      // Parse XML
      Document mathml = parseMathml(params, result, start);
      if (mathml == null) {
        return result;
      }
      return getEps(params, mathml, result, start);
    } catch (Throwable t) {
      result.setError("MathML unexpected error - " + t.getMessage());
      t.printStackTrace();
      return result;
    }
  }
コード例 #27
0
ファイル: Utils.java プロジェクト: Rafarel/DeathChests
  public static List<Tombstone> loadTombstone(String chestsPath, DeathChests plugin) {
    LinkedList<Tombstone> deathChests = new LinkedList<>();
    try {
      DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
      DocumentBuilder builder = factory.newDocumentBuilder();

      // Start the parser
      Document doc = builder.parse(new File(chestsPath));

      Element rootElement = doc.getDocumentElement();

      String version = rootElement.getAttribute("version");
      if (!Settings.getVersion().equals(version)) {
        System.out.println(
            "The version of the Deathchests-File changed. There are possible errors at loading them. (Probably not if your updated it)");
      }

      long timestamp = System.currentTimeMillis();

      NodeList list = rootElement.getChildNodes();
      int length = list.getLength();
      for (int i = 0; i < length; i++) {
        try {
          Node node = list.item(i);
          String name = node.getNodeName();
          if (name.equalsIgnoreCase(Utils.DEATHCHEST_XML_TAG)) {
            deathChests.add(new Tombstone((Element) node, timestamp, plugin));
          }
        } catch (XMLParseException ex) {
          System.err.println("Corrupted deathchest! Skipping this one!");
          ex.printStackTrace();
        }
      }
    } catch (IOException | ParserConfigurationException | SAXException ex) {
      System.err.println("Error while loading deathchest data:");
      ex.printStackTrace();
    }
    return deathChests;
  }
コード例 #28
0
ファイル: Test.java プロジェクト: mallampatisuresh/Glassfish
  public Test(String arg) {
    if (arg.equals("all")) {
      boolean all = false;
      all = performTest("delete");
      all = performTest("extract") && all;
      all = performTest("clone") && all;
      all = performTest("insert") && all;
      all = performTest("surround") && all;
      all = performTest("insert2") && all;
      all = performTest("delete2") && all;
      if (all) {
        System.out.println("Done.");

      } else {
        System.out.println("*** ONE OR MORE TESTS FAILED! ***");
        System.exit(1);
      }

    } else {
      performTest(arg);
    }
  }
コード例 #29
0
ファイル: Chemkin.java プロジェクト: ecintron/RMG-Java
  // ## operation Chemkin(double,double,String)
  public Chemkin(double p_rtol, double p_atol, String p_reactorType) {
    // #[ operation Chemkin(double,double,String)
    if (p_rtol < 0 || p_atol < 0)
      throw new InvalidChemkinParameterException("Negative rtol or atol!");
    if (p_reactorType == null) throw new NullPointerException();

    String dir = System.getProperty("RMG.workingDirectory");

    // create the documentTypesDefinitions
    File docFile = new File("chemkin/documentTypeDefinitions");
    docFile.mkdir();
    copyFiles(
        dir + "/software/reactorModel/documentTypeDefinitions/reactorInput.dtd",
        "chemkin/documentTypeDefinitions/reactorInput.dtd");
    copyFiles(
        dir + "/software/reactorModel/documentTypeDefinitions/reactorOutput.dtd",
        "chemkin/documentTypeDefinitions/reactorOutput.dtd");

    rtol = p_rtol;
    atol = p_atol;
    reactorType = p_reactorType;
  }
コード例 #30
0
ファイル: AMLtoPNML.java プロジェクト: CaoAo/BeehiveZ
  private static void AML2PNML(String[] args) {
    if (args.length != 3) {
      System.out.println("���ṩAML����Ŀ¼��PNML���Ŀ¼�Լ��ֵ��ļ�!");
      System.exit(-1);
    }
    System.out.println("����Ŀ¼��" + args[0]);
    System.out.println("���Ŀ¼��" + args[1]);
    System.out.println("�ֵ��ļ���" + args[2]);
    // load the dict
    AMLtoPNML.loadDict(args[2]);
    File srcDir = new File(args[0]);
    File[] lstAML = srcDir.listFiles();
    PnmlExport export = new PnmlExport();
    for (int i = 0; i < lstAML.length; i++) {
      if (lstAML[i].isDirectory()) {
        continue;
      }
      System.out.print(lstAML[i].getName() + "==>");
      try {
        FileInputStream fis = new FileInputStream(lstAML[i]);
        int idx = lstAML[i].getName().indexOf(".xml");
        File outFile = new File(args[1] + "/" + lstAML[i].getName().substring(0, idx) + ".pnml");
        FileOutputStream fos = new FileOutputStream(outFile);
        EPCResult epcRes = (EPCResult) AMLtoPNML.importFile(fis);
        ConfigurableEPC epc = epcRes.getMainEPC();
        PetriNet petri = AMLtoPNML.convert(epc);
        export.export(new ProvidedObject("PetriNet", new Object[] {petri}), fos);
        System.out.println(outFile.getName());
      } catch (FileNotFoundException ex) {
        ex.printStackTrace(System.out);
      } catch (IOException ioe) {
        ioe.printStackTrace(System.out);
      } catch (Exception e) {
        e.printStackTrace(System.out);
      }
    }

    System.out.println("Conversion Done");
  }