简体   繁体   English

我需要这段Java代码来发送目录中的所有XML文件,有没有一种方法可以遍历每个XML文件

[英]I need this piece of Java code to send all the XML files in the directory, is there a way to loop through each XML file

I have a piece of Java restassured code that that pulls top 5 ids from the DB and uses it in an XML file creating 5 XML files. 我有一段Java保证代码,该代码从数据库中提取前5个ID,并在创建5个XML文件的XML文件中使用它。

Then I am picking each xml file from this directory individually and sending it to a server but I need to send them all one by one. 然后,我从该目录中分别选择每个xml文件,并将其发送到服务器,但我需要将它们全部一一发送。

public class sendPlaylistAcknowledgment {

Properties prop = new Properties(); // creating prop object as global variable

@BeforeTest

public void getData() throws IOException{

    FileInputStream f = new FileInputStream("D:\\Tools\\Workspace\\BXF\\src\\files\\config.properties"); //creating f object
    prop.load(f); // to load the file object into prop file

    //In the code below we will use the config values set in .property file
}

@SuppressWarnings("unused")
@Test
public void postData() throws IOException{


    String postData = GenerateStringFromResource("C:\\Users\\shussain\\Desktop\\BXF_Msg\\PlaylistAck\\BXF_1501110072083.XML");
    //BaseURL

    RestAssured.baseURI= prop.getProperty("AISHOST"); //value populating from property methord above

    Response resp = given().log().all().
    header("Content-Type", "application/XML; charset=utf-8").
    body(postData).
    when().
    post("/bxfxml").
    then().assertThat().statusCode(200).and().contentType(ContentType.XML).
    extract().response();

    //to convert raw data to string

    XmlPath xmlResponse= reusableFunctions.rawToXML(resp);
    String responseString = resp.asString();
    System.out.println("XML response is - "+ responseString);

}
 public static String GenerateStringFromResource(String path) throws IOException{

     return new String(Files.readAllBytes(Paths.get(path)));
 }

}
//Below code pulls data from DB and creates the XML file
public List <String> getExternalId() throws ClassNotFoundException, SQLException, InvalidFileFormatException, IOException{

    FileInputStream file = new FileInputStream("D:\\Tools\\Workspace\\BXF\\src\\files\\config.properties");
    Properties prop = new Properties();
    prop.load(file);

    Wini ini = new Wini(new File(prop.getProperty("WOINI")));

    String userid = ini.fetch("ConnectionString", "User ID");
    String pwd = ini.fetch("ConnectionString", "Password");
    String dbName = ini.fetch("ConnectionString", "Initial Catalog");
    String connectionURL = "jdbc:sqlserver://localhost" + ";databaseName="+dbName + ";user=" +userid + ";password=" +pwd;


    Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

    Connection con = DriverManager.getConnection(connectionURL);
    System.out.println("Driver version: " + con.getMetaData().getDriverVersion());

    //retrieve data
    Statement st = con.createStatement();
    ResultSet rs = st.executeQuery(prop.getProperty("SELECT TOP 5 * FROM WO_INTERFACE_QUEUE WHERE ACTION_INFO = 'Playlist' ORDER BY CREATE_DATE DESC"));

    List <String> externalId = new ArrayList<String>();

    while (rs.next()) {
        externalId.add(rs.getString("INTERFACE_QUEUE_ID"));

        }

    return externalId;

}
   public void createBXFAckFXml(String id) {

          try {
             FileInputStream file = new FileInputStream("D:\\Tools\\Workspace\\BXF\\src\\files\\config.properties");
             Properties prop = new Properties();
             prop.load(file);

             DocumentBuilderFactory dbFactory =
             DocumentBuilderFactory.newInstance();
             DocumentBuilder dBuilder = 
                dbFactory.newDocumentBuilder();
             Document doc = dBuilder.newDocument();
             // root element
             Element rootElement = doc.createElement("BxfMessage");
             doc.appendChild(rootElement);

             // setting attribute to element
             rootElement.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
             rootElement.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
             rootElement.setAttribute("xmlns:xs", "http://www.w3.org/2001/XMLSchema");
             rootElement.setAttribute("id", "urn:uuid:427c5fb4-987c-4718-8ace-12fcb835df21");
             rootElement.setAttribute("dateTime", "2017-10-25T09:28:12.1074289-04:00");
             rootElement.setAttribute("messageType", "Acknowledgement");
             rootElement.setAttribute("origin", "ADC");
             rootElement.setAttribute("originType", "Automation System");
             rootElement.setAttribute("userName", "ADC_User");
             rootElement.setAttribute("destination", "WideOrbit");
             rootElement.setAttribute("originMessageId", id);
             rootElement.setAttribute("status", "OK");
             rootElement.setAttribute("ext:usage", "Application Acknowledgement");
             rootElement.setAttribute("xsi:schemaLocation", "http://smpte-ra.org/schemas/2021/2008/BXF bxfschema.xsd http://smpte-ra.org/schemas/2021/2008/BXF/Extension bxfschema-extension.xsd http://www.atsc.org/XMLSchemas/pmcp/2007/3.1 pmcp31.xsd");
             rootElement.setAttribute("xmlns:ext", "http://smpte-ra.org/schemas/2021/2008/BXF/Extension");
             rootElement.setAttribute("xmlns", "http://smpte-ra.org/schemas/2021/2008/BXF");

             // write the content into xml file
             TransformerFactory transformerFactory =
             TransformerFactory.newInstance();
             Transformer transformer =
             transformerFactory.newTransformer();
             DOMSource source = new DOMSource(doc);
             doc.setXmlStandalone(true);
             String filename = prop.getProperty("PLAYLISTACK_ENDPOINT")+ "BXF_"+System.currentTimeMillis()+".XML";
             StreamResult result =
             new StreamResult(new File(filename));
             transformer.transform(source, result);
             // Output to console for testing
             StreamResult consoleResult =
             new StreamResult(System.out);
             transformer.transform(source, consoleResult);
          } catch (Exception e) {
             e.printStackTrace();
          } 

On next run of xml file creating program you can change the extention of previously sent data to something else after that you can loop through the xml files and can send new data 在下一次运行xml文件创建程序时,您可以将以前发送的数据的范围更改为其他内容,之后可以遍历xml文件并可以发送新数据

   Files.newDirectoryStream(Paths.get("."),
        path -> path.toString().endsWith(".xml"))
        .forEach(data -> {
          // send you data here
      });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM