Exemple #1
0
  public static void main(String[] args) {

    PersonDAO_MySQL person = new PersonDAO_MySQL();
    //        person.insertDB(new PersonModel(0, "jag", "ru"));
    //        person.deleteDB(2);
    //        person.updateDB(new PersonModel(3, "jag101", "ru"));
    //        System.out.println(person.selectDB());

    Utils utils = new Utils(person.selectDB());
    System.out.println("===== CSV =====");
    //        utils.printCSV();
    //        utils.saveCSV();

    System.out.println("===== XML =====");
    //        utils.printXML();
    //        utils.saveXML();

    System.out.println("===== JSON =====");
    //       utils.printJSON();
    //       utils.saveJSON();

    ArrayList<PersonModel> arrayListPerson = new ArrayList<PersonModel>();
    //        JSONParser Parser = new JSONParser();
    //        System.out.println(Parser.parse());

    //        CSVParser parser = new CSVParser();
    //        System.out.println(parser.parse());

    XMLParser parser = new XMLParser();
    System.out.println(parser.parse());
  }
  /** 得到下一个商品节点 */
  @Override
  public Node next() {
    if (hasNext()) {
      if (point == productList.size() - 1) {
        pageIndex++;
        map.put("pg", String.valueOf(pageIndex));
        map.put("ps", String.valueOf(pageSize));
        String url = URLBuilder.buildURL(map);
        String xml = SearchRequester.get(url);
        try {
          productList = XMLParser.getProductNodes(XMLParser.read(xml));
        } catch (MalformedURLException | DocumentException e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }

        //				productList = URLBuilder.getXML(verifyPoint, keyWord, media);
        point = 0;
        return productList.get(point);
      } else {
        point++;
        return productList.get(point);
      }

    } else {
      return null;
    }
  }
 /*
  * 	通过Map参数拼URL获取XML数据,再获取productList
  */
 public ProdIterator(Map<String, String> map, int maxIndex) {
   this.map = map;
   this.maxIndex = maxIndex;
   this.map.put("pg", String.valueOf(pageIndex));
   this.map.put("ps", String.valueOf(pageSize));
   String url = URLBuilder.buildURL(this.map);
   String xml = SearchRequester.get(url);
   logger.debug(url);
   try {
     Document doc = XMLParser.read(xml);
     productList = XMLParser.getProductNodes(doc);
     pageCount = Integer.valueOf(XMLParser.PageCount(doc));
     totalCount = Integer.valueOf(XMLParser.totalCount(doc));
     setTerm(XMLParser.term(doc));
     if (totalCount < maxIndex) {
       this.maxIndex = totalCount;
     }
     // logger.debug(" - [Iterator] - init the product List!");
   } catch (MalformedURLException | DocumentException e) {
     ByteArrayOutputStream buf = new ByteArrayOutputStream();
     e.printStackTrace(new PrintWriter(buf, true));
     String expMessage = buf.toString();
     logger.error(" - [LOG_EXCEPTION] - " + expMessage);
     //			 logger.error(expMessage);
     //			e.printStackTrace();
   }
 }
 @Test
 public void test() {
   try {
     parser.parse();
     Println.print(parser.getRatingScenarios());
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
  private void createListItem(
      LinearLayout list, final File game, final int index, final boolean isGame) {
    final View childview =
        parentActivity.getLayoutInflater().inflate(R.layout.app_list_item, null, false);

    XMLParser xmlParser = new XMLParser(game, index, mPrefs);
    xmlParser.setViewParent(parentActivity, childview, mCallback);
    orig_bg = childview.getBackground();

    childview
        .findViewById(R.id.childview)
        .setOnClickListener(
            new OnClickListener() {
              public void onClick(View view) {
                if (isGame) {
                  vib.vibrate(50);
                  mCallback.onGameSelected(game != null ? Uri.fromFile(game) : Uri.EMPTY);
                  vib.vibrate(250);
                } else {
                  vib.vibrate(50);
                  home_directory =
                      game.getAbsolutePath()
                          .substring(0, game.getAbsolutePath().lastIndexOf(File.separator))
                          .replace("/data", "");
                  if (!DataDirectoryBIOS()) {
                    MainActivity.showToastMessage(
                        getActivity(),
                        getActivity().getString(R.string.config_data, home_directory),
                        Toast.LENGTH_LONG);
                  }
                  mPrefs.edit().putString("home_directory", home_directory).commit();
                  mCallback.onFolderSelected(Uri.fromFile(new File(home_directory)));
                  JNIdc.config(home_directory);
                }
              }
            });

    childview
        .findViewById(R.id.childview)
        .setOnTouchListener(
            new OnTouchListener() {
              @SuppressWarnings("deprecation")
              public boolean onTouch(View view, MotionEvent arg1) {
                if (arg1.getActionMasked() == MotionEvent.ACTION_DOWN) {
                  view.setBackgroundColor(0xFF4F3FFF);
                } else if (arg1.getActionMasked() == MotionEvent.ACTION_CANCEL
                    || arg1.getActionMasked() == MotionEvent.ACTION_UP) {
                  view.setBackgroundDrawable(orig_bg);
                }
                return false;
              }
            });
    list.addView(childview);
    xmlParser.execute(game.getName());
  }
Exemple #6
0
 public static void load(
     Resolver loader,
     String file,
     SimpleDirectedGraph<GraphClass, Inclusion> graph,
     Vector problems) {
   ISGCIReader gcr = new ISGCIReader(graph, problems);
   XMLParser xml = new XMLParser(loader.openInputSource(file), gcr, loader.getEntityResolver());
   xml.parse();
   date = gcr.getDate();
   nodecount = gcr.getNodeCount();
   edgecount = gcr.getEdgeCount();
   relations = gcr.getRelations();
 }
  public static void main(String[] args) {

    AbstractParserFactory parserFactory = ParserFactoryProducer.getFactory("NYCFactory");
    XMLParser parser = parserFactory.getParserInstance("NYCORDER");
    String msg = "";
    msg = parser.parse();
    System.out.println(msg);

    System.out.println("************************************");

    parserFactory = ParserFactoryProducer.getFactory("LondonFactory");
    parser = parserFactory.getParserInstance("LondonFEEDBACK");
    msg = parser.parse();
    System.out.println(msg);
  }
  @Override
  protected void FetchConfig() {

    Document doc = XMLParser.Parser();
    NodeList nodes = doc.getElementsByTagName(TAG);
    Node gatewayNode = nodes.item(0);
    if (gatewayNode.getNodeType() == Node.ELEMENT_NODE) {
      Element eElement = (Element) gatewayNode;

      try {
        if (ValidateXMLDocument(eElement)) {
          num = Integer.valueOf(eElement.getAttribute(ATTNUM));
          typeOfgeneration =
              TypeOfGenerationEnum.valueOf(eElement.getAttribute(ATTTOG).toUpperCase());
          radio = Integer.parseInt(eElement.getAttribute(ATTRADIO));
          if (typeOfgeneration == TypeOfGenerationEnum.STATIC
              && ValidateXMLDocument(eElement, typeOfgeneration)) FetchStatic(eElement);
          if (typeOfgeneration == TypeOfGenerationEnum.FILE
              && ValidateXMLDocument(eElement, typeOfgeneration)) FetchFromFile(eElement);
        }
      } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
      }
    }
  }
Exemple #9
0
 /**
  * @param configPath
  * @param checkUserHome if true tries to check if the file ${user.home}/.pdfsam/config.xml exists
  *     and can be written, if not tries to check if the file APPLICATIOH_PATH/config.xml can be
  *     written, if not copies the APPLICATIOH_PATH/config.xml to ${user.home}/.pdfsam/config.xml
  * @throws Exception
  */
 public XMLConfig(String configPath, boolean checkUserHome) throws Exception {
   File configFile = new File(configPath, "config.xml");
   if (checkUserHome) {
     File defaultConfigFile = new File(defaultDirectory, "config.xml");
     if (!(defaultConfigFile.exists() && defaultConfigFile.canWrite())) {
       if (!configFile.exists()) {
         throw new ConfigurationException("Unable to find configuration file.");
       }
       if (!configFile.canWrite()) {
         File defaultDir = new File(defaultDirectory);
         if (defaultDir.mkdirs()) {
           log.info(
               "Copying config.xml from "
                   + configFile.getPath()
                   + " to "
                   + defaultConfigFile.getPath());
           FileUtility.copyFile(configFile, defaultConfigFile);
           configFile = defaultConfigFile;
         } else {
           throw new ConfigurationException("Unable to create " + defaultDirectory);
         }
       }
     } else {
       configFile = defaultConfigFile;
     }
   }
   xmlConfigFile = configFile;
   document = XMLParser.parseXmlFile(xmlConfigFile);
 }
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.flash_card_activity);

    // Initialize fields
    initialize();

    try {
      SAXParserFactory spf = SAXParserFactory.newInstance();
      SAXParser sp = spf.newSAXParser();
      XMLReader xr = sp.getXMLReader();
      myParser = new XMLParser();
      xr.setContentHandler(myParser);
      xr.parse(new InputSource(this.getResources().openRawResource(R.raw.words)));
    } catch (Exception e) {
      e.printStackTrace();
    } finally {
      words = myParser.getWordsList();
      // db = dbh.getWritableDatabase();
      // myWords = dbh.getMyWordsList();
      displayWord(words.get(index));
    }

    pbProgress.setMax(words.size());
  }
Exemple #11
0
  public static void main(String[] args) throws Exception {
    // convert BEAST 2 XML to BEAST JSON file
    XMLParser parser = new XMLParser();
    BEASTInterface beastObject = parser.parseFile(new File(args[0]));

    String JSONFile = args[0].replace(".xml", ".json");
    PrintStream out;
    if (JSONFile.endsWith(".json")) {
      out = new PrintStream(new File(JSONFile));
    } else {
      out = System.out;
    }

    JSONProducer writer = new JSONProducer();
    String JSON = writer.toJSON(beastObject);
    out.println(JSON);
    out.close();
  }
  private void populateLookup(String xml) {
    try {
      Document doc = XMLParser.getDomElement(xml);
      NodeList nl = doc.getElementsByTagName("glyph");
      SVGPath path;
      for (int i = 0; i < nl.getLength(); i++) {
        String index = XMLParser.getAttribute((Element) nl.item(i), "unicode");
        String strPath = XMLParser.getAttribute((Element) nl.item(i), "d");

        if (strPath != null && strPath.equals("") != true && index != null && index.length() > 3) {
          index = index.substring(3);
          path = new SVGPath(index, strPath);
          index = path.getID();
          _SymbolDefinitions.put(index, path);
        }
      }
    } catch (Exception exc) {
      Log.e("SymbolSVGTable", exc.getMessage(), exc);
    }
  }
Exemple #13
0
 @Override
 public State next(char c, ParserData data, XMLParser xmlparser) {
   State result = INVALID_END;
   if (c != '>') {
     result = CLOSE_TAG;
   }
   if (c == '>') {
     result = START;
   }
   xmlparser.onCloseTag(data);
   return result;
 }
Exemple #14
0
 @Override
 public State next(char c, ParserData data, XMLParser xmlparser) {
   State result = INVALID_END;
   if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) {
     data.text = data.getText() + c;
     result = NODE;
   }
   if (c == '<') {
     result = ON_TEXT;
     xmlparser.onText(data);
   }
   return result;
 }
Exemple #15
0
 @Override
 public State next(char c, ParserData data, XMLParser xmlparser) {
   State result = INVALID_END;
   if (c == '>') {
     result = NODE;
     data.setAttributes(data.attributeName, data.attributeValue);
     xmlparser.onOpenTag(data);
   }
   if (c == ' ') {
     result = TAG_NAME;
   }
   return result;
 }
Exemple #16
0
 public static void xml(Score paramScore, String paramString) {
   try {
     PrintWriter localPrintWriter = new PrintWriter(new FileWriter(paramString));
     System.out.println("--------------------- Writing XML File -----------------------");
     String str = XMLParser.scoreToXMLString(paramScore);
     localPrintWriter.print(str);
     localPrintWriter.close();
     System.out.println(
         "XML file '" + paramString + "' written from score '" + paramScore.getTitle() + "'");
     System.out.println("-------------------------------------------------------------");
   } catch (IOException localIOException) {
     System.err.println(localIOException);
   }
 }
    protected String doInBackground(String... params) {
      Log.i(TAG, "doInBackground");
      String respuesta = null;

      try {
        TelephonyManager telephonyManager =
            (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String IMEI = telephonyManager.getDeviceId();
        String IMSI = telephonyManager.getSimSerialNumber();
        String consulta;
        if (phone.getText().toString().equals("2")) {
          consulta = URLs.RESOURCE;
        } else consulta = SoapRequestMovistar.getResource(IMEI, IMSI, phone.getText().toString());

        ArrayList<String> retorno = XMLParser.getReturnCode(consulta);

        code = Integer.valueOf(retorno.get(0));

        if (code == 0) {
          respuesta = consulta;
          Log.i(TAG, retorno.get(1));
        } else respuesta = retorno.get(1);
        return respuesta;

      } catch (HttpHostConnectException e2) {
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (HttpResponseException e3) {
        e3.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (ParseException p) {
        p.printStackTrace();
        errorMessage = "Error en la recepción de los datos. Por favor reintente";
        return null;
      } catch (SocketTimeoutException s1) {
        s1.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (ConnectTimeoutException et) {
        et.printStackTrace();
        errorMessage = "Se agotó el tiempo de espera. Por favor reintente";
        return null;
      } catch (Exception e1) {
        e1.printStackTrace();
        errorMessage = "Ha ocurrido un error con la respuesta del servidor.";
        return null;
      }
    }
 public boolean reSet() {
   this.pageIndex = 1;
   this.point = -1;
   this.map.put("pg", String.valueOf(pageIndex));
   this.map.put("ps", String.valueOf(pageSize));
   String url = URLBuilder.buildURL(this.map);
   String xml = SearchRequester.get(url);
   try {
     Document doc = XMLParser.read(xml);
     productList = XMLParser.getProductNodes(doc);
     pageCount = Integer.valueOf(XMLParser.PageCount(doc));
     totalCount = Integer.valueOf(XMLParser.totalCount(doc));
     // logger.debug(" - [Iterator] - reSet the product List!");
     return true;
   } catch (MalformedURLException | DocumentException e) {
     // TODO Auto-generated catch block
     ByteArrayOutputStream baos = new ByteArrayOutputStream();
     e.printStackTrace(new PrintStream(baos));
     String exception = baos.toString();
     logger.error(" - [LOG_EXCEPTION] - " + exception);
     e.printStackTrace();
     return false;
   }
 }
Exemple #19
0
 @Override
 public State next(char c, ParserData data, XMLParser xmlparser) {
   State result = INVALID_END;
   if (Character.isLetter(c)) {
     data.tag = data.getTag() + c;
     result = OPEN_TAG;
   }
   if (c == ' ') {
     result = TAG_NAME;
   }
   if (c == '>') {
     xmlparser.onOpenTag(data);
     result = NODE;
   }
   return result;
 }
Exemple #20
0
 @Override
 public State next(char c, ParserData data, XMLParser xmlparser) {
   State result = INVALID_END;
   if (Character.isLetterOrDigit(c) || Character.isWhitespace(c)) {
     data.attributeName = data.getAttributeName() + c;
     result = TAG_NAME;
   }
   if (c == '=') {
     result = ATTR_NAME;
   }
   if (c == '>') {
     xmlparser.onOpenTag(data);
     result = NODE;
   }
   if (c == '/') {
     result = CLOSE_TAG;
   }
   return result;
 }
    @Override
    protected ArrayList<MapMarker> doInBackground(String... params) {
      ArrayList<MapMarker> respuesta;

      try {
        TelephonyManager telephonyManager =
            (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        String IMEI = telephonyManager.getDeviceId();
        String IMSI = telephonyManager.getSimSerialNumber();

        String output = SoapRequestMovistar.getMapMarkers(IMEI, IMSI, comuna, region);
        // String output = dummy();
        if (output != null) respuesta = XMLParser.getMapMarkers(output);
        else respuesta = null;

      } catch (Exception e) {
        e.printStackTrace();
        respuesta = null;
      }
      return respuesta;
    }
  @Override
  protected void FetchConfig() {
    Document doc = XMLParser.Parser();
    NodeList nodes = doc.getElementsByTagName(TAG);
    Node routerNode = nodes.item(0);
    if (routerNode.getNodeType() == Node.ELEMENT_NODE) {
      Element eElement = (Element) routerNode;

      try {
        if (ValidateXMLDocument(eElement)) {

          _mode = ChannelMode.valueOf(eElement.getAttribute(ATTMODE));
          if (_mode == ChannelMode.Partially) FetchPartially(eElement);
          else if (_mode == ChannelMode.All) FetchALL();
        }
      } catch (Exception e) {
        System.err.println(e.getMessage());
        e.printStackTrace();
      }
    }
  }
    @Override
    protected String doInBackground(String... params) {
      TelephonyManager telephonyManager =
          (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
      String IMEI = telephonyManager.getDeviceId();
      String IMSI = telephonyManager.getSimSerialNumber();
      try {
        String query = SoapRequestMovistar.getButtonBlock(IMEI, IMSI);
        // String query = URLs.BLOQUEO;
        ArrayList<Boton> response = XMLParser.getButtons(query);

        for (Boton b : response) {
          if (b.isActualizacion()) actualizar = b;
          else {
            bloqueo.setBloqueo(b.getId(), b.isEnabled(), b.getName());
          }
          ok = true;
        }
        return "BLOQUEO OK";
      } catch (SAXException e) {
        e.printStackTrace();
        return "Error al leer el xml";
      } catch (ParserConfigurationException e) {
        e.printStackTrace();
        return "Error al leer el xml";
      } catch (XPathExpressionException e) {
        e.printStackTrace();
        return "Error al leer el xml";
      } catch (IOException e) {
        e.printStackTrace();
        return "Se agotó el tiempo de espera con el servidor. Compruebe su conexión a internet y reinicie la aplicación";
      } catch (Exception e) {
        e.printStackTrace();
        return "Error no controlado:\n" + e.getMessage();
      }
    }
Exemple #24
0
  public static void main(String[] args) {
    List<Revision> revisions = new ArrayList<Revision>();
    List<TestDocument> documents = new ArrayList<TestDocument>();
    List<TestDocument> allDocuments = new ArrayList<TestDocument>();

    // read in the train and test data
    System.out.println("reading in train data!");
    XMLParser parser = new XMLParser();
    File dir = new File(TRAIN_DIR + USER);
    for (File file : dir.listFiles()) {
      // System.err.println(file);
      Revision revision = parser.parseRevision(file);
      if (revision != null) revisions.add(revision);
    }

    System.out.println("reading in test data!");

    List<String> documentsToUse = null;
    try {
      documentsToUse = QueryGetter.getNMostRecentlyEditedPageIds(USER, 50);
    } catch (Exception e) {
      e.printStackTrace();
    }

    dir = new File(TEST_DIR);
    for (File file : dir.listFiles()) {
      String name = file.getName();
      int dash = name.indexOf("-");
      int dot = name.indexOf(".");
      String id = name.substring(0, dash);
      if (!name.substring(dash + 1, dot).equals(USER) || documentsToUse.indexOf(id) == -1) continue;

      TestDocument document = parser.parseDocument(file);
      if (document.paragraphs.size() == 0) continue;
      // if (document.paragraphs.size() < 10) continue;
      document.id = id;
      // if (documentsToUse.indexOf(id) < 25 && documents.size() < 10)
      if (documentsToUse.indexOf(id) < 10)
        // if (documents.size() < 10)
        documents.add(document);

      allDocuments.add(document);
    }

    // prepare test data
    System.out.println("calculating scores!");
    for (TestDocument document : allDocuments) calculateScores(document, revisions);

    // train + test using leave-one-out cross-validation
    System.out.println("testing!");
    MultinomialNaiveBayes classifier = new MultinomialNaiveBayes();
    for (TestDocument testDocument : documents) {
      List<Revision> trainRevisions = new ArrayList<Revision>(revisions);
      for (Revision revision : revisions) {
        if (revision.pageId.equals(testDocument.id)) trainRevisions.remove(revision);
      }

      List<TestDocument> trainDocuments = new ArrayList<TestDocument>();
      for (TestDocument document : allDocuments) {
        if (document.equals(testDocument)) continue;

        TestDocument newDocument = new TestDocument();
        for (int i = 0; i < document.paragraphs.size(); i++) {
          if (document.scores.get(i) == 0) {
            newDocument.paragraphs.add(document.paragraphs.get(i));
            newDocument.scores.add(document.scores.get(i));
          }
        }
        trainDocuments.add(newDocument);
      }

      // classifier.countDocumentWords = true;
      classifier.calculateProbabilities(trainRevisions, trainDocuments);
      List<MultinomialNaiveBayes.Pair> predictions = classifier.mostLikelyParagraphs(testDocument);

      Set<String> revisedParagraphs = new HashSet<String>();
      for (int i = 0; i < testDocument.paragraphs.size(); i++) {
        if (testDocument.scores.get(i) > 0) revisedParagraphs.add(testDocument.paragraphs.get(i));
      }
      System.out.println("size: " + revisedParagraphs.size());

      System.out.println("num paragraphs: " + predictions.size());
      int rank = -1;
      boolean done = false;
      for (int i = 0; i < predictions.size(); i++) {
        // System.out.println("~~~PREDICTION" + i + "~~~\n");
        // System.out.println(predictions.get(i).paragraph);
        // System.out.println("score: " + predictions.get(i).score);
        if (revisedParagraphs.contains(predictions.get(i).paragraph)) {
          rank = i;
          done = true;
        }
        if (done) break;
      }
      System.out.println("rank: " + rank);
      // System.out.println("PREDICTED:\n" + predictions.get(0).paragraph);
      // System.out.println("ACTUAL:\n" + actual);
    }
  }
Exemple #25
0
 public XMLConfig() throws Exception {
   xmlConfigFile = new File("config.xml");
   document = XMLParser.parseXmlFile(xmlConfigFile);
 }
Exemple #26
0
 /**
  * It saves any changes on the xml file
  *
  * @throws Exception
  * @see org.pdfsam.guiclient.utils.xml.XMLParser#writeXmlFile(Document, File)
  */
 public void saveXMLfile() throws Exception {
   XMLParser.writeXmlFile(document, xmlConfigFile);
 }
Exemple #27
0
 @Override
 public State next(char c, ParserData data, XMLParser xmlparser) {
   xmlparser.onEnd(data);
   return INVALID_END;
 }