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.smartitengineering.util.bean.PropertiesLocator.java

/**
 * Return suffix for default resource file.
 * @return Suffix for the classpath default resource
 *//*from   ww  w.  java2s .  c om*/
protected InputStream attemptToLoadResource(Properties props, Resource resource) {
    InputStream is = null;
    try {
        is = resource.getInputStream();
        if (resource.getFilename().endsWith(".xml")) {
            props.loadFromXML(is);
        } else {
            if (this.fileEncoding != null) {
                loadFromReader(props, new InputStreamReader(is, this.fileEncoding));
            } else {
                props.load(is);
            }
        }
    } catch (Exception ex) {
    }
    return is;
}

From source file:MemoryController.java

@RequestMapping("/memory")
public @ResponseBody Memory memory(
        @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

    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();
    jsonObj.put("jsonrpc", "2.0");
    jsonObj.put("method", "item.get");
    JSONObject params = new JSONObject();
    params.put("output", "extend");
    params.put("hostid", hostid);
    JSONObject search = new JSONObject();
    search.put("key_", "memory");
    params.put("search", search);
    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 

    PutMethod putMethod2 = new PutMethod(ZABBIX_API_URL);
    putMethod2.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 jsonObj2 = new JSONObject();
    jsonObj2.put("jsonrpc", "2.0");
    jsonObj2.put("method", "item.get");
    JSONObject params2 = new JSONObject();
    params2.put("output", "extend");
    params2.put("hostid", hostid);
    JSONObject search2 = new JSONObject();
    search2.put("key_", "swap");
    params2.put("search", search2);
    params2.put("sortfield", "name");
    jsonObj2.put("params", params2);
    jsonObj2.put("auth", authentication);// todo
    jsonObj2.put("id", new Integer(1));

    putMethod2.setRequestBody(jsonObj2.toString());

    String loginResponse = "";
    String loginResponse2 = "";
    String memory = "";
    String clock = "";
    String metricType = "";

    try {/*from 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");

        client.executeMethod(putMethod2); // send to request to the zabbix api

        loginResponse2 = putMethod2.getResponseBodyAsString(); // read the result of the response

        Object obj3 = parser.parse(loginResponse2);
        JSONObject obj4 = (JSONObject) obj3;
        String jsonrpc2 = (String) obj4.get("jsonrpc");
        JSONArray array2 = (JSONArray) obj4.get("result");

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

            //         lastValue = getLastValue(tobj);
            //         lastClock = getLastClock(tobj);
            if (!tobj.get("hostid").equals(hostid))
                continue;
            if (name.equals("totalMemory") && tobj.get("name").equals("Total memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Total Memeory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("cachedMemory") && tobj.get("name").equals("Cached memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Cached Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("freeMemory") && tobj.get("name").equals("Free memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Free Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("bufferedMemory") && tobj.get("name").equals("Buffers memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Buffered Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else if (name.equals("sharedMemory") && tobj.get("name").equals("Shared memory")) {
                memory = (String) tobj.get("lastvalue");
                clock = (String) tobj.get("lastclock");
                metricType = "Shared Memory";
                return new Memory(hostid, metricType, memory, clock);
            } else {
                continue;
            }
        }

        for (int i = 0; i < array2.size(); i++) {
            JSONObject tobj2 = (JSONObject) array2.get(i);

            if (!tobj2.get("hostid").equals(hostid))
                continue;
            if (name.equals("freeSwap") && tobj2.get("name").equals("Free swap space")) {
                memory = (String) tobj2.get("lastvalue");
                clock = (String) tobj2.get("lastclock");
                metricType = "Free Swap Space";
                return new Memory(hostid, metricType, memory, clock);
            } else {
                continue;
            }

        }

    } catch (HttpException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ParseException pe) {
        System.out.println("Error");
    }

    return new Memory(
            "Error: please provide the appropriate input parameters of the metric you are looking for its corresponding monitoring data:");
}

From source file:com.webpagebytes.plugins.WPBLocalFileStorage.java

private Properties getFileProperties(String filePath) throws IOException {
    Properties props = new Properties();
    FileInputStream fis = null;/* w w w  .  j  a v  a  2  s.c o m*/
    fis = new FileInputStream(filePath);
    try {
        props.loadFromXML(fis);
    } catch (IOException e) {
        throw e;
    } finally {
        IOUtils.closeQuietly(fis);
    }

    return props;
}

From source file:org.aludratest.cloud.impl.app.CloudManagerApplicationHolder.java

private MutablePreferences readPreferences(File f) {
    SimplePreferences prefs = new SimplePreferences(null);
    if (!f.exists()) {
        return prefs;
    }/*from w  w w.jav a 2  s. co  m*/

    Properties p = new Properties();

    FileInputStream fis = null;
    try {
        fis = new FileInputStream(f);
        p.loadFromXML(fis);

        for (String key : p.stringPropertyNames()) {
            String value = p.getProperty(key);
            if ("".equals(value)) {
                value = null;
            }
            prefs.setValue(key, value);
        }
    } catch (IOException e) {
        LOG.error("Could not read preferences file " + f.getAbsolutePath(), e);
        return prefs;
    } finally {
        IOUtils.closeQuietly(fis);
    }

    return prefs;
}

From source file:org.opencastproject.capture.admin.endpoint.CaptureAgentStateRestService.java

@POST
@Produces(MediaType.TEXT_XML)//from  w w w .jav  a2 s.c  o  m
@Path("agents/{name}/configuration")
@RestQuery(name = "setAgentStateConfiguration", description = "Set the configuration of a given capture agent, registering it if it does not exist", pathParameters = {
        @RestParameter(description = "The name of a given capture agent", isRequired = true, name = "name", type = Type.STRING) }, restParameters = {
                @RestParameter(description = "An XML representation of the capabilities, as specified in http://java.sun.com/dtd/properties.dtd (friendly names as keys, device locations as their corresponding values)", type = Type.TEXT, isRequired = true, name = "configuration") }, reponses = {
                        @RestResponse(description = "{name} set to {state}", responseCode = HttpServletResponse.SC_OK),
                        @RestResponse(description = "The configuration format is incorrect OR the agent name is blank or null", responseCode = HttpServletResponse.SC_BAD_REQUEST) }, returnDescription = "")
public Response setConfiguration(@PathParam("name") String agentName,
        @FormParam("configuration") String configuration) {
    if (service == null)
        return Response.serverError().status(Response.Status.SERVICE_UNAVAILABLE).build();

    if (StringUtils.isBlank(configuration)) {
        logger.debug("The configuration data cannot be blank");
        return Response.serverError().status(Response.Status.BAD_REQUEST).build();
    }

    Properties caps = new Properties();
    ByteArrayInputStream bais = null;
    try {
        bais = new ByteArrayInputStream(configuration.getBytes());
        caps.loadFromXML(bais);
        if (!service.setAgentConfiguration(agentName, caps))
            logger.debug("'{}''s configuration has not been updated because nothing has been changed",
                    agentName);

        // Prepares the value to return
        PropertiesResponse r = new PropertiesResponse(caps);
        logger.debug("{}'s configuration updated", agentName);
        return Response.ok(r).build();
    } catch (IOException e) {
        logger.debug("Unexpected I/O Exception when unmarshalling the capabilities: {}", e.getMessage());
        return Response.status(javax.ws.rs.core.Response.Status.BAD_REQUEST).build();
    } finally {
        IOUtils.closeQuietly(bais);
    }
}

From source file:org.onecmdb.ui.gwt.desktop.server.service.model.mdr.MDRSetupService.java

private void updateDataSource(IContentService svc, String token, ContentData data, TransformConfig config) {
    svc.stat(data);//from w ww  .  j a  v  a2 s.c o m
    if (!data.isExists() || data.isDirectory()) {
        return;
    }
    String content = svc.get(token, data);
    Properties p = new Properties();
    try {
        ByteArrayInputStream array = new ByteArrayInputStream(content.getBytes());
        p.loadFromXML(array);
    } catch (Exception e) {
        log.error("Can't read '" + data.getPath() + "'", e);
        // Ignore this.
        return;
    }

    Enumeration<?> keys = p.propertyNames();
    BaseModel dataSource = new BaseModel();
    String type = (String) p.get("type");
    while (keys.hasMoreElements()) {
        String key = (String) keys.nextElement();
        String value = p.getProperty(key);
        if (key.startsWith(type + ".")) {
            key = key.substring((type + ".").length());
        }
        dataSource.set(key, value);
    }

    config.setDataSourceType(type);
    config.setDataSource(type, dataSource);
}

From source file:org.olanto.TranslationText.server.UploadServlet.java

private String getFileExtension() {
    Properties prop;
    String fileName = SenseOS.getMYCAT_HOME() + "/config/GUI_fix.xml";
    FileInputStream f = null;// w  ww.  ja va  2  s  .  c  om
    try {
        f = new FileInputStream(fileName);
    } catch (Exception e) {
        System.out.println("cannot find properties file:" + fileName);
        _logger.error(e);
    }
    try {

        prop = new Properties();
        prop.loadFromXML(f);
        return prop.getProperty("QD_FILE_EXT");
    } catch (Exception e) {
        System.out.println("errors in properties file:" + fileName);
        _logger.error(e);
    }
    return null;
}

From source file:org.easy.ldap.LdapEnvironment.java

private Properties readFromFile(String filename, FileType fileType) throws IOException {
    InputStream file = null;/* w  w w .  j a  va  2s.c om*/
    Properties out = null;

    try {
        file = this.getClass().getClassLoader().getResourceAsStream(filename);

        if (file == null)
            throw new FileNotFoundException("Unable to find " + filename + " on classpath");

        out = new Properties();

        switch (fileType) {
        case PROPERTIES:
            out.load(file);
            break;
        case XML:
            out.loadFromXML(file);
            break;
        }
    } finally {
        if (file != null)
            file.close();
    }

    return out;

}

From source file:servlet.BPMNAnimationServlet.java

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    PrintWriter out = null;/*  w  ww.j  av a  2 s.c om*/
    List<Log> logs = new ArrayList<>();
    Set<XLog> xlogs = new HashSet<>();
    //Set<XLog> optimizedLogs = new HashSet<>();
    String jsonData = "";
    Definitions bpmnDefinition = null;

    if (!ServletFileUpload.isMultipartContent(req)) {
        res.getWriter().println("Does not support!");
        // if not, we stop here
        return;
    }

    /*
     * ------------------------------------------
     * Import event log files
     * logs variable contains list of imported logs
     * ------------------------------------------
     */
    // configures some settings

    DiskFileItemFactory factory = new DiskFileItemFactory();
    factory.setSizeThreshold(THRESHOLD_SIZE);
    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    ServletFileUpload upload = new ServletFileUpload(factory);
    upload.setFileSizeMax(MAX_FILE_SIZE);
    upload.setSizeMax(REQUEST_SIZE);

    // constructs the directory path to store upload file
    String uploadPath = getServletContext().getRealPath("") + File.separator + UPLOAD_DIRECTORY;
    // creates the directory if it does not exist
    File uploadDir = new File(uploadPath);
    if (!uploadDir.exists()) {
        uploadDir.mkdir();
    }

    try {

        // parses the request's content to extract file data
        List<FileItem> formItems = upload.parseRequest(req);
        Iterator iter = formItems.iterator();

        // iterates over form's fields
        while (iter.hasNext()) {
            FileItem item = (FileItem) iter.next();

            // processes only fields that are not form fields
            if (!item.isFormField()) {
                String fileName = new File(item.getName()).getName();
                String filePath = uploadPath + File.separator + fileName;
                File storeFile = new File(filePath);

                // saves the file on disk
                item.write(storeFile);
                LOGGER.info("Finish writing uploaded file to temp dir: " + filePath);

                LOGGER.info("Start importing file: " + filePath);
                item.getInputStream();
                OpenLogFilePlugin logImporter = new OpenLogFilePlugin();
                XLog xlog = (XLog) logImporter.importFile(storeFile);

                // color field must follow the log file
                item = (FileItem) iter.next();
                assert item.isFormField();
                assert "color".equals(item.getFieldName());
                LOGGER.info("Log color: " + item.getString());
                String color = item.getString();

                // Record the log
                Log log = new Log();
                log.fileName = fileName;
                log.xlog = xlog;
                log.color = item.getString();
                logs.add(log);
                xlogs.add(xlog);
            } else {
                if (item.getFieldName().equals("json")) {
                    jsonData = item.getString();
                }
            }
        }

        /*
        * ------------------------------------------
        * Convert JSON map to BPMN objects
        * ------------------------------------------
        */
        LOGGER.info("Then, convert JSON to BPMN map objects");
        if (!jsonData.equals("")) {
            bpmnDefinition = this.getBPMNfromJson(jsonData);
            LOGGER.info("BPMN Diagram Definition" + bpmnDefinition.toString());
        } else {
            LOGGER.info("JSON data sent to server is empty");
        }

        /*
        * ------------------------------------------
        * Optimize logs and process model
        * ------------------------------------------
        */
        Optimizer optimizer = new Optimizer();
        for (Log log : logs) {
            //optimizedLogs.add(optimizer.optimizeLog(log.xlog));
            log.xlog = optimizer.optimizeLog(log.xlog);
        }
        bpmnDefinition = optimizer.optimizeProcessModel(bpmnDefinition);

        /*
        * ------------------------------------------
        * Check BPMN diagram validity and replay log
        * ------------------------------------------
        */

        //Reading backtracking properties for testing
        String propertyFile = "/editor/animation/properties.xml";
        InputStream is = getServletContext().getResourceAsStream(propertyFile);
        Properties props = new Properties();
        props.loadFromXML(is);
        ReplayParams params = new ReplayParams();
        params.setMaxCost(Double.valueOf(props.getProperty("MaxCost")).doubleValue());
        params.setMaxDepth(Integer.valueOf(props.getProperty("MaxDepth")).intValue());
        params.setMinMatchPercent(Double.valueOf(props.getProperty("MinMatchPercent")).doubleValue());
        params.setMaxMatchPercent(Double.valueOf(props.getProperty("MaxMatchPercent")).doubleValue());
        params.setMaxConsecutiveUnmatch(Integer.valueOf(props.getProperty("MaxConsecutiveUnmatch")).intValue());
        params.setActivityMatchCost(Double.valueOf(props.getProperty("ActivityMatchCost")).doubleValue());
        params.setActivitySkipCost(Double.valueOf(props.getProperty("ActivitySkipCost")).doubleValue());
        params.setEventSkipCost(Double.valueOf(props.getProperty("EventSkipCost")).doubleValue());
        params.setNonActivityMoveCost(Double.valueOf(props.getProperty("NonActivityMoveCost")).doubleValue());
        params.setTraceChunkSize(Integer.valueOf(props.getProperty("TraceChunkSize")).intValue());
        params.setMaxNumberOfNodesVisited(
                Integer.valueOf(props.getProperty("MaxNumberOfNodesVisited")).intValue());
        params.setMaxActivitySkipPercent(
                Double.valueOf(props.getProperty("MaxActivitySkipPercent")).doubleValue());
        params.setMaxNodeDistance(Integer.valueOf(props.getProperty("MaxNodeDistance")).intValue());
        params.setTimelineSlots(Integer.valueOf(props.getProperty("TimelineSlots")).intValue());
        params.setTotalEngineSeconds(Integer.valueOf(props.getProperty("TotalEngineSeconds")).intValue());
        params.setProgressCircleBarRadius(
                Integer.valueOf(props.getProperty("ProgressCircleBarRadius")).intValue());
        params.setSequenceTokenDiffThreshold(
                Integer.valueOf(props.getProperty("SequenceTokenDiffThreshold")).intValue());
        params.setMaxTimePerTrace(Long.valueOf(props.getProperty("MaxTimePerTrace")).longValue());
        params.setMaxTimeShortestPathExploration(
                Long.valueOf(props.getProperty("MaxTimeShortestPathExploration")).longValue());
        params.setExactTraceFitnessCalculation(props.getProperty("ExactTraceFitnessCalculation"));
        params.setBacktrackingDebug(props.getProperty("BacktrackingDebug"));
        params.setExploreShortestPathDebug(props.getProperty("ExploreShortestPathDebug"));
        params.setCheckViciousCycle(props.getProperty("CheckViciousCycle"));
        params.setStartEventToFirstEventDuration(
                Integer.valueOf(props.getProperty("StartEventToFirstEventDuration")).intValue());
        params.setLastEventToEndEventDuration(
                Integer.valueOf(props.getProperty("LastEventToEndEventDuration")).intValue());

        Replayer replayer = new Replayer(bpmnDefinition, params);
        ArrayList<AnimationLog> replayedLogs = new ArrayList();
        if (replayer.isValidProcess()) {
            LOGGER.info("Process " + bpmnDefinition.getId() + " is valid");
            EncodeTraces.getEncodeTraces().read(xlogs); //build a mapping from traceId to charstream
            for (Log log : logs) {

                AnimationLog animationLog = replayer.replay(log.xlog, log.color);
                //AnimationLog animationLog = replayer.replayWithMultiThreading(log.xlog, log.color);
                if (animationLog != null && !animationLog.isEmpty()) {
                    replayedLogs.add(animationLog);
                }
            }

        } else {
            LOGGER.info(replayer.getProcessCheckingMsg());
        }

        /*
        * ------------------------------------------
        * Return Json animation
        * ------------------------------------------
        */
        LOGGER.info("Start sending back JSON animation script to browser");
        if (replayedLogs.size() > 0) {
            out = res.getWriter();
            res.setContentType("text/html"); // Ext2JS's file upload requires this rather than "application/json"
            res.setStatus(200);

            //To be replaced
            AnimationJSONBuilder jsonBuilder = new AnimationJSONBuilder(replayedLogs, replayer, params);
            JSONObject json = jsonBuilder.parseLogCollection();
            json.put("success", true); // Ext2JS's file upload requires this flag
            String string = json.toString();
            //LOGGER.info(string);
            jsonBuilder.clear();

            out.write(string);
        } else {
            /*
            out = res.getWriter();
            res.setContentType("text/html");
            res.setStatus(204);
            out.write("");
            */
            String json = "{success:false, errors: {errormsg: '" + "No logs can be played." + "'}}";
            res.setContentType("text/html; charset=UTF-8");
            res.getWriter().print(json);
        }

    } catch (Exception e) {
        try {
            LOGGER.severe(e.toString());
            /*
            res.setStatus(500);
            res.setContentType("text/plain");
            PrintWriter writer = new PrintWriter(out);
            writer.println("Failed to generate animation JSON script " + e);
            e.printStackTrace(writer);
            e.printStackTrace();
            res.getWriter().write(e.toString());
            */
            String json = "{success:false, errors: {errormsg: '" + e.getMessage() + "'}}";
            res.setContentType("text/html; charset=UTF-8");
            res.getWriter().print(json);
        } catch (Exception el) {
            System.err.println("Original exception was:");
            e.printStackTrace();
            System.err.println("Exception in exception handler was:");
            el.printStackTrace();
        }
    }

}

From source file:eu.planets_project.tb.impl.model.exec.ExecutionRecordImpl.java

public Properties getPropertiesListResult() throws IOException {
    if (!RESULT_PROPERTIES_LIST.equalsIgnoreCase(this.getResultType())) {
        return null;
    }//from w  w w  . j  a  v  a  2 s  .com
    Properties props = new Properties();
    ByteArrayInputStream bin = new ByteArrayInputStream(this.getResult().getBytes("UTF-8"));
    props.loadFromXML(bin);
    return props;
}