Example usage for java.util Properties loadFromXML

List of usage examples for java.util Properties loadFromXML

Introduction

In this page you can find the example usage for java.util Properties loadFromXML.

Prototype

public synchronized void loadFromXML(InputStream in) throws IOException, InvalidPropertiesFormatException 

Source Link

Document

Loads all of the properties represented by the XML document on the specified input stream into this properties table.

Usage

From source file:com.yifanlu.PSXperiaTool.PSXperiaTool.java

private void checkData(File dataDir) throws IllegalArgumentException, IOException {
    nextStep("Checking to make sure all files are there.");
    if (!mDataDir.exists())
        throw new FileNotFoundException("Cannot find data directory!");
    File filelist = new File(mDataDir, "/config/filelist.txt");
    if (!filelist.exists())
        throw new FileNotFoundException("Cannot find list to validate files!");
    InputStream fstream = new FileInputStream(filelist);
    BufferedReader reader = new BufferedReader(new InputStreamReader(fstream));
    String line;//from   w  w  w  .  j  a v a  2s .co  m
    while ((line = reader.readLine()) != null) {
        if (line.isEmpty())
            continue;
        File check = new File(mDataDir, line);
        if (!check.exists())
            throw new IllegalArgumentException("Cannot find required data file: " + line);
    }
    Properties config = new Properties();
    config.loadFromXML(new FileInputStream(new File(mDataDir, "/config/config.xml")));
    Logger.info("Using data from " + config.getProperty("game_name", "Unknown Game") + " "
            + config.getProperty("game_region") + " Version " + config.getProperty("game_version", "Unknown")
            + ", CRC32: " + config.getProperty("game_crc32", "Unknown"));
    Logger.debug("Done checking data.");
}

From source file:com.yifanlu.PSXperiaTool.Extractor.CrashBandicootExtractor.java

private void patchEmulator() throws IOException {
    Logger.info("Verifying the emulator binary.");
    Properties config = new Properties();
    config.loadFromXML(new FileInputStream(new File(mOutputDir, "/config/config.xml")));
    String emulatorName = config.getProperty("emulator_name", "libjava-activity.so");
    File origEmulator = new File(mOutputDir, "/lib/armeabi/" + emulatorName);
    String emulatorCRC32 = Long.toHexString(FileUtils.checksumCRC32(origEmulator));
    if (!emulatorCRC32.equalsIgnoreCase(config.getProperty("emulator_crc32")))
        throw new UnsupportedOperationException(
                "The emulator checksum is invalid. Cannot patch. CRC32: " + emulatorCRC32);
    File newEmulator = new File(mOutputDir, "/lib/armeabi/libjava-activity-patched.so");
    File emulatorPatch = new File(mOutputDir, "/config/" + config.getProperty("emulator_patch", ""));
    if (emulatorPatch.equals("")) {
        Logger.info("No patch needed.");
        FileUtils.moveFile(origEmulator, newEmulator);
    } else {//from  w  w  w.j  ava2  s.com
        Logger.info("Patching emulator.");
        newEmulator.createNewFile();
        JBPatch.bspatch(origEmulator, newEmulator, emulatorPatch);
        emulatorPatch.delete();
    }
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class.getResourceAsStream("/resources/libjava-activity-wrapper.so"), origEmulator);
}

From source file:ServiceController.java

@RequestMapping("/service")
public @ResponseBody Service service(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid,
        @RequestParam(value = "metricType", required = false, defaultValue = "") String name)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {

    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);

    // content-type is controlled in api_jsonrpc.php, so set it like this
    putMethod.setRequestHeader("Content-Type", "application/json-rpc");
    String request = setRequest("net.tcp.service", authentication, hostid);

    putMethod.setRequestBody(request); // put the json object as input stream into request body 

    return serviceResponse(hostid, putMethod, name);
}

From source file:eu.eidas.node.auth.metadata.EidasNodeMetadataGeneratorTest.java

private Properties loadContactProps(String source) {
    Properties props = new Properties();
    try {/*from   www .  java 2s . com*/
        InputStream stream = new ByteArrayInputStream(source.getBytes(Charset.forName("UTF-8")));
        props.loadFromXML(stream);
    } catch (Exception exc) {
        fail("cannot load properties " + exc);
    }
    return props;
}

From source file:HostController.java

@RequestMapping("/hosts")
public @ResponseBody Host host(
        @RequestParam(value = "authentication", required = false, defaultValue = "") String authentication)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {

    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    // content-type is controlled in api_jsonrpc.php, so set it like this
    putMethod.setRequestHeader("Content-Type", "application/json-rpc");
    // create json object for apiinfo.version 
    JSONParser parser = new JSONParser();
    JSONObject jsonObj = new JSONObject();
    JSONArray list = new JSONArray();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "host.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    String loginResponse = "";

    try {/*from  w ww  .j a  v  a  2  s.  c om*/
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response

        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            JSONObject objret = new JSONObject();

            objret.put("hostid", tobj.get("hostid"));
            objret.put("hostName", tobj.get("host"));

            list.add(objret);
        }
        return new Host(list);

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return new Host(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:com.yifanlu.PSXperiaTool.Extractor.CrashBandicootExtractor.java

private void processConfig() throws IOException, UnsupportedOperationException {
    long crc32 = ZpakCreate.getCRC32(mApkFile);
    String crcString = Long.toHexString(crc32).toUpperCase();
    InputStream inConfig = null;//from w ww .  j  a va 2 s.c o m
    if ((inConfig = PSXperiaTool.class
            .getResourceAsStream("/resources/patches/" + crcString + "/config.xml")) == null) {
        throw new FileNotFoundException("Cannot find config for this APK (CRC32: " + crcString + ")");
    }
    Properties config = new Properties();
    config.loadFromXML(inConfig);
    inConfig.close();
    Logger.info("Identified " + config.getProperty("game_name", "Unknown Game") + " "
            + config.getProperty("game_region") + " Version " + config.getProperty("game_version", "Unknown")
            + ", CRC32: " + config.getProperty("game_crc32", "Unknown"));
    if (config.getProperty("valid", "yes").equals("no"))
        throw new UnsupportedOperationException("This APK is not supported.");
    Logger.verbose("Copying config files.");
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/config.xml"),
            new File(mOutputDir, "/config/config.xml"));
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/filelist.txt"),
            new File(mOutputDir, "/config/filelist.txt"));
    FileUtils.copyInputStreamToFile(
            PSXperiaTool.class
                    .getResourceAsStream("/resources/patches/" + crcString + "/stringReplacements.txt"),
            new File(mOutputDir, "/config/stringReplacements.txt"));
    String emulatorPatch = config.getProperty("emulator_patch", "");
    String gamePatch = config.getProperty("iso_patch", "");
    if (!gamePatch.equals("")) {
        FileUtils.copyInputStreamToFile(
                PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/" + gamePatch),
                new File(mOutputDir, "/config/game-patch.bin"));
    }
    if (!emulatorPatch.equals("")) {
        FileUtils.copyInputStreamToFile(
                PSXperiaTool.class.getResourceAsStream("/resources/patches/" + crcString + "/" + emulatorPatch),
                new File(mOutputDir, "/config/" + emulatorPatch));
    }
}

From source file:org.opentestsystem.shared.test.standalone.LoadTestPackageRunner.java

private void main_(String[] args) {
    // Bridge the JUL logging into SLF4J
    SLF4JBridgeHandler.removeHandlersForRootLogger(); // (since SLF4J 1.6.5)
    SLF4JBridgeHandler.install();/*from w w w . j  av a  2 s  .co  m*/
    MDC.put("interestingThreadId", "main");

    // Parse arguments
    Options options = new Options();
    options.addOption("h", OPTION_NAME_HELP, false, "Print this message");
    options.addOption("p", OPTION_NAME_CONTEXT_CONFIG, true,
            "URL of Spring context-configuration file that defines the test to run");
    options.addOption("c", OPTION_NAME_CONTEXT_PROPERTIES, true,
            "URL of a file defining properties for the test");
    options.addOption("d", OPTION_NAME_SPRING_PROFILES, true,
            "Names of active Spring profiles, separated by spaces");
    CommandLineParser cliParser = new GnuParser();
    CommandLine cli = null;
    try {
        cli = cliParser.parse(options, args);
    } catch (ParseException e) {
        _logger.error("Unable to parse command line parameters", e);
        System.exit(1);
    }

    if (cli.hasOption(OPTION_NAME_HELP)) {
        new HelpFormatter().printHelp("java -jar shared-test.jar", options);
        System.exit(0);
    }

    String contextConfigUrl = cli.getOptionValue(OPTION_NAME_CONTEXT_CONFIG, OPTION_DEFAULT_CONTEXT_CONFIG);
    String contextPropertiesUrl = cli.getOptionValue(OPTION_NAME_CONTEXT_PROPERTIES,
            OPTION_DEFAULT_CONTEXT_PROPERTIES);
    String springProfilesString = cli.getOptionValue(OPTION_NAME_SPRING_PROFILES,
            OPTION_DEFAULT_SPRING_PROFILES);

    // Configure the Spring context
    GenericXmlApplicationContext context = new GenericXmlApplicationContext();
    if (!StringUtils.isEmpty(springProfilesString)) {
        String[] springProfiles = springProfilesString.split(" ");
        context.getEnvironment().setActiveProfiles(springProfiles);
    }
    if (!StringUtils.isEmpty(contextPropertiesUrl)) {
        Properties p = new Properties();
        try {
            p.loadFromXML(new URL(contextPropertiesUrl).openStream());
        } catch (InvalidPropertiesFormatException e) {
            MDC.put("close", "true");
            _logger.error("Error parsing properties file {}", contextPropertiesUrl, e);
            System.exit(1);
        } catch (MalformedURLException e) {
            MDC.put("close", "true");
            _logger.error("Illegal URL for properties file {}", contextPropertiesUrl, e);
            System.exit(1);
        } catch (IOException e) {
            MDC.put("close", "true");
            _logger.error("IO error reading properties file {}", contextPropertiesUrl, e);
            System.exit(1);
        }
        context.getEnvironment().getPropertySources().addFirst(new PropertiesPropertySource("cmdline", p));
    }
    context.load(contextConfigUrl);
    context.refresh();
    setApplicationContext(context);

    // Get the lifecycle resources
    _lifecycleResources = new LifecycleResourceCombiner();
    _lifecycleResources.setApplicationContext(context);

    // Start lifecycle resources
    try {
        _lifecycleResources.startupBeforeDependencies();
        _lifecycleResources.startupAfterDependencies();
    } catch (Exception e) {
        MDC.put("close", "true");
        _logger.error("Error starting lifecycle resources", e);
        System.exit(1);
    }

    // Get the first-person users
    _users = new HashMap<>();
    for (@SuppressWarnings("rawtypes")
    Entry<String, FirstPersonInteractiveUser> entry_i : context.getBeansOfType(FirstPersonInteractiveUser.class)
            .entrySet()) {
        _users.put(entry_i.getKey(), entry_i.getValue());
    }

    // Start first-person scripts
    for (FirstPersonInteractiveUser<?, ?> user_i : _users.values()) {
        user_i.startScript();
    }

    // Wait for conclusion
    for (FirstPersonInteractiveUser<?, ?> user_i : _users.values()) {
        try {
            user_i.join();
        } catch (InterruptedException e) {
            _logger.error("Interrupted running test");
        }
    }

    // Expand any "chorus" users to get the actual users
    int i = 0;
    List<FirstPersonInteractiveUser<?, ?>> allUsers = new ArrayList<>(_users.values());
    while (i < allUsers.size()) {
        FirstPersonInteractiveUser<?, ?> user_i = allUsers.get(i);
        if (user_i instanceof Chorus) {
            allUsers.remove(i);
            for (FirstPersonInteractiveUser<?, ?> user_j : ((Chorus<?, ?>) user_i)) {
                allUsers.add(user_j);
            }
        } else {
            i++;
        }
    }

    // Log summary interaction statistics
    TimingRecordSummarizer summarizer = new TimingRecordSummarizerImpl();
    for (FirstPersonInteractiveUser<?, ?> user_i : allUsers) {
        for (InteractionContext<?> context_j : user_i.getInteractionContexts()) {
            for (InteractionTimingRecord record_k : context_j.getTimingRecordHistory()) {
                summarizer.addObservation(record_k);
            }
        }
    }
    _logger.info("Latency summary:\r\n\r\n" + summarizer.getSummaryAsString());

    // Shut down lifecycle resources
    try {
        _lifecycleResources.shutdownBeforeDependencies();
        _lifecycleResources.shutdownAfterDependencies();
    } catch (Exception e) {
        MDC.put("close", "true");
        _logger.error("Error stopping lifecycle resources", e);
        System.exit(1);
    }
    MDC.put("close", "true");
    System.exit(0);
}

From source file:org.geolatte.maprenderer.sld.graphics.ExternalGraphicsRepository.java

private Properties readGraphicsIndex(InputStream graphicsIndexFile) throws IOException {
    Properties index = new Properties();
    index.loadFromXML(graphicsIndexFile);
    return index;
}

From source file:GraphController.java

@RequestMapping("/graphs")
public @ResponseBody Graph graph(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {
    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    JSONParser parser = new JSONParser();
    HttpClient client = new HttpClient();

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);
    putMethod.setRequestHeader("Content-Type", "application/json-rpc"); // content-type is controlled in api_jsonrpc.php, so set it like this

    // create json object for apiinfo.version 
    JSONObject jsonObj = new JSONObject();
    JSONArray list = new JSONArray();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "graph.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostids", hostid);
    params.put("sortfield", "name");
    jsonObj.put("params", params);
    jsonObj.put("auth", authentication);// todo
    jsonObj.put("id", new Integer(1));

    putMethod.setRequestBody(jsonObj.toString()); // put the json object as input stream into request body 

    String loginResponse = "";

    try {/*ww  w. j  av  a 2  s.c o m*/
        client.executeMethod(putMethod); // send to request to the zabbix api

        loginResponse = putMethod.getResponseBodyAsString(); // read the result of the response
        Object obj = parser.parse(loginResponse);
        JSONObject obj2 = (JSONObject) obj;
        String jsonrpc = (String) obj2.get("jsonrpc");
        JSONArray array = (JSONArray) obj2.get("result");

        //         System.out.println(array);
        for (int i = 0; i < array.size(); i++) {
            JSONObject tobj = (JSONObject) array.get(i);

            JSONObject objret = new JSONObject();

            objret.put("graphId", tobj.get("graphid"));
            objret.put("graphName", tobj.get("name"));

            String type = (String) tobj.get("graphtype");

            if (type.equals("0")) {
                objret.put("graphType", "normal");
            } else if (type.equals("1")) {
                objret.put("graphType", "stacked");
            } else if (type.equals("2")) {
                objret.put("graphType", "pie");
            } else if (type.equals("3")) {
                objret.put("graphType", "exploded");
            }

            list.add(objret);

        }

        return new Graph(list);

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        pe.printStackTrace();
    }
    return new Graph(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:NetworkController.java

@RequestMapping("/network")
public @ResponseBody Network network(
        @RequestParam(value = "authentication", required = false, defaultValue = "Error") String authentication,
        @RequestParam(value = "hostid", required = false, defaultValue = "") String hostid,
        @RequestParam(value = "metricType", required = false, defaultValue = "") String name)
        throws FileNotFoundException, UnsupportedEncodingException, IOException {

    Properties props = new Properties();
    FileInputStream fis = new FileInputStream("properties.xml");
    //loading properites from properties file
    props.loadFromXML(fis);

    String server_ip = props.getProperty("server_ip");
    String ZABBIX_API_URL = "http://" + server_ip + "/api_jsonrpc.php"; // 1.2.3.4 is your zabbix_server_ip

    PutMethod putMethod = new PutMethod(ZABBIX_API_URL);

    // content-type is controlled in api_jsonrpc.php, so set it like this
    putMethod.setRequestHeader("Content-Type", "application/json-rpc");

    String request = "";

    if (name.equals("latency"))
        request = setRequest("icmppingsec", authentication, hostid);
    else if (name.equals("packetloss"))
        request = setRequest("icmppingloss", authentication, hostid);
    else/*ww  w .j  a  va 2 s .co  m*/
        request = setRequest("net", authentication, hostid);

    putMethod.setRequestBody(request); // put the json object as input stream into request body 

    return networkResponse(hostid, putMethod, name);
}