Example usage for java.io FileReader close

List of usage examples for java.io FileReader close

Introduction

In this page you can find the example usage for java.io FileReader close.

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:fsi_admin.admon.JAyudaPaginaDlg.java

private String generarIndiceReportes(String t_cuerpo, String remplazo, String interfaz, String color,
        String href) throws IOException {
    //carga el archivo de ayuda que contienen la plantilla completa
    String ps = "";
    FileReader file = new FileReader("/usr/local/forseti/bin/forseti_doc/indice_reportes.html");
    BufferedReader buff = new BufferedReader(file);
    boolean eof = false;
    while (!eof) {
        String line = buff.readLine();
        if (line == null)
            eof = true;/*from   w  w w  .j ava 2  s .c om*/
        else
            ps += line + "\n";
    }
    buff.close();
    file.close();
    buff = null;
    file = null;

    // extrae el inicio de la plantilla
    int ini_index = ps.indexOf("<!--_ini_modulos-->");
    String p_inicio = ps.substring(0, ini_index);
    // extrae los mdulos
    ini_index += 19;
    int fin_index = ps.indexOf("<!--_fin_modulos-->");
    String p_modulos = ps.substring(ini_index, fin_index);
    //extrae los submodulos
    ini_index = ps.indexOf("<!--_ini_submodulos-->") + 22;
    fin_index = ps.indexOf("<!--_fin_submodulos-->");
    String p_submodulos = ps.substring(ini_index, fin_index);
    //extrae los reportes
    ini_index = ps.indexOf("<!--_ini_reportes-->") + 20;
    fin_index = ps.indexOf("<!--_fin_reportes-->");
    String p_reportes = ps.substring(ini_index, fin_index);
    //extrae el fin de la plantilla
    ini_index = fin_index + 20;
    String p_final = ps.substring(ini_index);
    String cuerpo = "";
    String nbd = "";
    if (interfaz.equals("CEF")) {
        //System.out.println("Reportes del CEF");
        JAdmVariablesSet var = new JAdmVariablesSet(null);
        var.ConCat(true);
        var.m_Where = "ID_Variable = 'IDEMPAYUDA'";
        var.Open();
        JBDSSet set = new JBDSSet(null);
        set.ConCat(true);
        set.m_Where = "ID_BD = '" + var.getAbsRow(0).getVEntero() + "'";
        set.Open();
        if (set.getNumRows() == 0)
            return JUtil.replace(t_cuerpo, "fsi-cuerpo-todo", "&nbsp;");
        if (!set.getAbsRow(0).getSU().equals("3"))
            return JUtil.replace(t_cuerpo, "fsi-cuerpo-todo", "&nbsp;");
        nbd = set.getAbsRow(0).getNombre();
    }

    JUsuariosPermisosCatalogoSet pc = new JUsuariosPermisosCatalogoSet(null);
    if (interfaz.equals("SAF"))
        pc.ConCat(true);
    else {
        pc.ConCat(3);
        pc.setBD(nbd);
    }
    pc.Open();

    for (int p = 0; p < pc.getNumRows(); p++) {
        if (pc.getAbsRow(p).getID_Permiso().indexOf('_', 0) == -1) {
            String modulos = p_modulos;
            modulos = JUtil.replace(modulos, "fsi-color-modulo", color);
            modulos = JUtil.replace(modulos, "_modulo", pc.getAbsRow(p).getModulo());
            cuerpo += modulos + "\n";

            JUsuariosPermisosCatalogoSet pct = new JUsuariosPermisosCatalogoSet(null);
            if (interfaz.equals("SAF"))
                pct.ConCat(true);
            else {
                pct.ConCat(3);
                pct.setBD(nbd);
            }
            pct.m_Where = "ID_Permiso LIKE '" + JUtil.p(pc.getAbsRow(p).getID_Permiso()) + "_%'";
            pct.Open();

            for (int i = 0; i < pct.getNumRows(); i++) {
                if (StringUtils.countMatches(pct.getAbsRow(i).getID_Permiso(), "_") == 1) {
                    String submodulos = p_submodulos;
                    submodulos = JUtil.replace(submodulos, "_submodulo", pct.getAbsRow(i).getModulo());
                    cuerpo += submodulos + "\n";

                    JReportesSet prm = new JReportesSet(null);
                    if (interfaz.equals("SAF"))
                        prm.ConCat(true);
                    else {
                        prm.ConCat(3);
                        prm.setBD(nbd);
                    }
                    prm.m_OrderBy = "ID_Report ASC";
                    prm.m_Where = "Tipo = '" + JUtil.p(pct.getAbsRow(i).getID_Permiso()) + "'";
                    prm.Open();
                    //System.out.println(prm.getSQL());
                    for (int k = 0; k < prm.getNumRows(); k++) {
                        String reportes = p_reportes;
                        reportes = JUtil.replace(reportes, "_href_reporte",
                                href + "-" + prm.getAbsRow(k).getID_Report() + ".html");
                        reportes = JUtil.replace(reportes, "_clave_reporte",
                                Integer.toString(prm.getAbsRow(k).getID_Report()));
                        reportes = JUtil.replace(reportes, "_descripcion_reporte",
                                prm.getAbsRow(k).getDescription());
                        reportes = JUtil.replace(reportes, "_graficar_reporte", (prm.getAbsRow(k).getGraficar()
                                ? "<img src=\"../forsetidoc/IMG/chart.png\" style=\"border:0px solid;margin:0px;\" />"
                                : "&nbsp;"));
                        cuerpo += reportes + "\n";

                    }
                }
            }
        }
    }
    String pagina = p_inicio + "\n" + cuerpo + "\n" + p_final;
    return JUtil.replace(t_cuerpo, "fsi-cuerpo-todo", pagina);
}

From source file:com.photon.phresco.framework.rest.api.UtilService.java

@GET
@Path("/killProcess")
@Produces(MediaType.APPLICATION_JSON)// www.  j a  va2 s.c om
public Response killProcess(@QueryParam("actionType") String actionType,
        @QueryParam(REST_QUERY_APPID) String appId, @QueryParam(REST_QUERY_APPDIR_NAME) String appDirName) {
    ResponseInfo responseData = new ResponseInfo();
    // Pass module as param ------------------
    String moduleName = ""; /* for temporary*/
    try {
        String rootModulePath = "";
        String subModuleName = "";
        if (StringUtils.isNotEmpty(moduleName)) {
            rootModulePath = Utility.getProjectHome() + appDirName;
            subModuleName = moduleName;
        } else {
            rootModulePath = Utility.getProjectHome() + appDirName;
        }

        File getpomFileLocation = Utility.getPomFileLocation(rootModulePath, subModuleName);
        File do_not_checkin = new File(
                getpomFileLocation.getParent() + File.separator + Constants.DO_NOT_CHECKIN_DIRY);
        File jsonFile = new File(do_not_checkin.getPath() + File.separator + "process.json");
        if (!jsonFile.exists()) {
            ResponseInfo<List<ApplicationInfo>> finalOutput = responseDataEvaluation(responseData, null, null,
                    RESPONSE_STATUS_SUCCESS, PHR11C00001);
            return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                    .build();
        }
        JSONObject jsonObject = new JSONObject();
        JSONParser parser = new JSONParser();
        FileReader reader = new FileReader(jsonFile);
        jsonObject = (JSONObject) parser.parse(reader);
        Object processId = jsonObject.get(actionType);
        if (processId == null) {
            ResponseInfo<List<ApplicationInfo>> finalOutput = responseDataEvaluation(responseData, null, null,
                    RESPONSE_STATUS_SUCCESS, PHR11C00001);
            return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                    .build();
        }
        if (System.getProperty(Constants.OS_NAME).startsWith(Constants.WINDOWS_PLATFORM)) {
            Runtime.getRuntime().exec("cmd /X /C taskkill /F /T /PID " + processId.toString());
        } else if (System.getProperty(Constants.OS_NAME).startsWith("Mac")) {
            Runtime.getRuntime().exec(Constants.JAVA_UNIX_PROCESS_KILL_CMD + processId.toString());
        }
        LockUtil.removeLock(appId, actionType);
        jsonObject.remove(actionType);
        FileWriter writer = new FileWriter(jsonFile);
        writer.write(jsonObject.toString());
        writer.close();
        reader.close();
        if (jsonObject.size() <= 0) {
            FileUtil.delete(jsonFile);
        }
        ResponseInfo<List<String>> finalOutput = responseDataEvaluation(responseData, null, null,
                RESPONSE_STATUS_SUCCESS, PHR11C00002);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (IOException e) {
        ResponseInfo<ProjectInfo> finalOutput = responseDataEvaluation(responseData, e, null,
                RESPONSE_STATUS_ERROR, PHR11C10001);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (ParseException e) {
        ResponseInfo<ProjectInfo> finalOutput = responseDataEvaluation(responseData, e, null,
                RESPONSE_STATUS_ERROR, PHR11C10002);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    } catch (PhrescoException e) {
        ResponseInfo<ProjectInfo> finalOutput = responseDataEvaluation(responseData, e, null,
                RESPONSE_STATUS_ERROR, PHR11C10003);
        return Response.status(Status.OK).entity(finalOutput).header("Access-Control-Allow-Origin", "*")
                .build();
    }
}

From source file:com.pingtel.sipviewer.SIPViewerFrame.java

public void applyAliasesFile(String strAliasesFile) {
    try {/*from  ww  w.j  a  v a2s . c om*/
        FileReader fr = new FileReader(strAliasesFile);

        BufferedReader reader = new BufferedReader(fr);
        String strLine = reader.readLine();
        while (strLine != null) {
            int pos = strLine.indexOf("=");
            if (pos > 0) {
                String strValue = strLine.substring(0, pos);
                String strKey = strLine.substring(pos + 1);

                strKey = strKey.trim();
                strValue = strValue.trim();

                // System.out.println("AddAlias: " + strValue + " -> " +
                // strKey) ;

                m_model.removeKey(strValue);
                m_model.addKeyAlias(strKey, strValue);
                m_model.reindexData();
            }

            strLine = reader.readLine();
        }

        reader.close();
        fr.close();
    } catch (Exception e) {
        System.out.println("Unable to apply aliases file: " + strAliasesFile);

        JOptionPane.showConfirmDialog(null, "Unable to apply aliases file: " + strAliasesFile, "Error",
                JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE, null);
        e.printStackTrace();
        this.dispose();
    }
}

From source file:org.apache.jsp.fileUploader_jsp.java

public void _jspService(HttpServletRequest request, HttpServletResponse response)
        throws java.io.IOException, ServletException {

    PageContext pageContext = null;/*from  www . jav a  2 s.c o m*/
    HttpSession session = null;
    ServletContext application = null;
    ServletConfig config = null;
    JspWriter out = null;
    Object page = this;
    JspWriter _jspx_out = null;
    PageContext _jspx_page_context = null;

    try {
        response.setContentType("text/html; charset=utf-8");
        pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
        _jspx_page_context = pageContext;
        application = pageContext.getServletContext();
        config = pageContext.getServletConfig();
        session = pageContext.getSession();
        out = pageContext.getOut();
        _jspx_out = out;

        out.write("<!--\n");
        out.write("Copyright 2012 The Infinit.e Open Source Project\n");
        out.write("\n");
        out.write("Licensed under the Apache License, Version 2.0 (the \"License\");\n");
        out.write("you may not use this file except in compliance with the License.\n");
        out.write("You may obtain a copy of the License at\n");
        out.write("\n");
        out.write("  http://www.apache.org/licenses/LICENSE-2.0\n");
        out.write("\n");
        out.write("Unless required by applicable law or agreed to in writing, software\n");
        out.write("distributed under the License is distributed on an \"AS IS\" BASIS,\n");
        out.write("WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n");
        out.write("See the License for the specific language governing permissions and\n");
        out.write("limitations under the License.\n");
        out.write("-->\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write("\n");
        out.write(
                "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n");
        out.write("<html xmlns=\"http://www.w3.org/1999/xhtml\">\n");
        out.write("<head>\n");
        out.write("<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n");
        out.write("<title>Infinit.e File Upload Tool</title>\n");
        out.write("<style media=\"screen\" type=\"text/css\">\n");
        out.write("\n");
        out.write("body \n");
        out.write("{\n");
        out.write("\tfont: 14px Arial,sans-serif;\n");
        out.write("}\n");
        out.write("h2\n");
        out.write("{\n");
        out.write("\tfont-family: \"Times New Roman\";\n");
        out.write("\tfont-style: italic;\n");
        out.write("\tfont-variant: normal;\n");
        out.write("\tfont-weight: normal;\n");
        out.write("\tfont-size: 24px;\n");
        out.write("\tline-height: 29px;\n");
        out.write("\tfont-size-adjust: none;\n");
        out.write("\tfont-stretch: normal;\n");
        out.write("\t-x-system-font: none;\n");
        out.write("\tcolor: #d2331f;\n");
        out.write("\tmargin-bottom: 25px;\n");
        out.write("}\n");
        out.write(".show {\n");
        out.write("display: ;\n");
        out.write("visibility: visible;\n");
        out.write("}\n");
        out.write(".hide {\n");
        out.write("display: none;\n");
        out.write("visibility: hidden;\n");
        out.write("}\n");
        out.write("</style>\n");
        out.write("<script language=\"javascript\" src=\"AppConstants.js\"> </script>\n");
        out.write("</head>\n");
        out.write("\n");
        out.write("<body onload=\"populate()\">\n");

        if (API_ROOT == null) {
            ServletContext context = session.getServletContext();
            String realContextPath = context.getRealPath("/");
            ScriptEngineManager manager = new ScriptEngineManager();
            ScriptEngine engine = manager.getEngineByName("javascript");
            try { // EC2 Machines
                FileReader reader = new FileReader(realContextPath + "/AppConstants.js");
                engine.eval(reader);
                reader.close();
                engine.eval("output = getEndPointUrl();");
                API_ROOT = (String) engine.get("output");
                SHARE_ROOT = API_ROOT + "share/get/";
            } catch (Exception je) {
                try { ////////////Windows + Tomcat
                    FileReader reader = new FileReader(realContextPath + "\\..\\AppConstants.js");
                    engine.eval(reader);
                    reader.close();
                    engine.eval("output = getEndPointUrl();");
                    API_ROOT = (String) engine.get("output");
                    SHARE_ROOT = API_ROOT + "share/get/";
                } catch (Exception e) {
                    System.err.println(e.toString());
                }
            }
            if (null == API_ROOT) {
                // Default to localhost
                API_ROOT = "http://localhost:8080/api/";
                SHARE_ROOT = "$infinite/share/get/";
            }

            if (API_ROOT.contains("localhost"))
                localCookie = true;
            else
                localCookie = false;
        }
        Boolean isLoggedIn = isLoggedIn(request, response);
        if (isLoggedIn == null) {
            out.println("The Infinit.e API cannot be reached.");
            out.println(API_ROOT);
        }

        else if (isLoggedIn == true) {
            showAll = (request.getParameter("sudo") != null);
            DEBUG_MODE = (request.getParameter("debug") != null);
            communityList = generateCommunityList(request, response);

            if (request.getParameter("logout") != null) {
                logOut(request, response);
                out.println("<div style=\" text-align: center;\">");
                out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                out.println("</div>");
            } else {

                out.println("<div style=\" text-align: center;\">");
                String contentType = request.getContentType();
                if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {

                    //      Create a new file upload handler
                    ServletFileUpload upload = new ServletFileUpload(new DiskFileItemFactory());
                    //      Parse the request
                    FileItemIterator iter = upload.getItemIterator(request);
                    byte[] fileBytes = null;
                    String fileDS = null;
                    byte[] iconBytes = null;
                    String iconDS = null;
                    Set<String> communities = new HashSet<String>();
                    boolean isFileSet = false;
                    while (iter.hasNext()) {
                        FileItemStream item = iter.next();
                        String name = item.getFieldName();
                        InputStream stream = item.openStream();
                        if (item.isFormField()) {
                            if (name.equalsIgnoreCase("communities")) {
                                communities.add(Streams.asString(stream));
                            } else
                                request.setAttribute(name, Streams.asString(stream));

                            //out.println("<b>" + name + ":</b>" + request.getAttribute(name).toString()+"</br>");
                        } else {
                            if (name.equalsIgnoreCase("file")) {
                                if (!item.getName().equals(""))
                                    isFileSet = true;
                                fileDS = item.getContentType();
                                fileBytes = IOUtils.toByteArray(stream);

                                // Check if this should be a java-archive (rather than just an octet stream)
                                if (fileDS.equals("application/octet-stream")) {
                                    ZipInputStream zis = new ZipInputStream(
                                            new ByteArrayInputStream(fileBytes));
                                    ZipEntry entry;
                                    while ((entry = zis.getNextEntry()) != null) {
                                        if (entry.getName().endsWith(".class")) {
                                            fileDS = "application/java-archive";
                                            break;
                                        }
                                    }
                                }
                                // Reset stream, and read
                            }
                        }
                    }

                    ////////////////////////////////////Delete Share ////////////////////////////////
                    if (request.getAttribute("deleteId") != null) {
                        String fileId = request.getAttribute("deleteId").toString();
                        if (fileId != null && fileId != "")
                            removeFromShare(fileId, request, response).toString();

                    }
                    ////////////////////////////////////Update Community Info////////////////////////////////
                    else if (null == fileBytes) {
                        String shareId = request.getAttribute("DBId").toString();
                        if (shareId != null && shareId != "")
                            addRemoveCommunities(shareId, communities, request, response);
                    } else {
                        //////////////////////////////////////////////////////////////////////////////////

                        Boolean newUpload = (request.getAttribute("DBId").toString().length() == 0);

                        ///////////////////////////////// SWF Manip  /////////////////////////////////
                        String shareId = request.getAttribute("DBId").toString();
                        String fileUrl = "";
                        String fileId = "";
                        String bin = request.getAttribute("binary").toString();
                        if (request.getAttribute("title") != null && request.getAttribute("description") != null
                                && fileBytes != null) {
                            if (!isFileSet) //if not a binary file or file was not changed
                            {
                                fileId = shareId;
                                if (shareId != null && shareId != "")
                                    addRemoveCommunities(shareId, communities, request, response);
                                out.println("File was not set, just updated communities.");
                            } else if (bin.equals("null")) //is a json file, make sure its okay and upload it
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        true, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            } else //is a binary, do normal
                            {
                                fileId = UpdateToShare(fileBytes, fileDS,
                                        request.getAttribute("title").toString(),
                                        request.getAttribute("description").toString(), shareId, communities,
                                        false, request.getAttribute("type").toString(), newUpload, request,
                                        response);
                            }

                            if (fileId.contains("Failed")) {
                                out.println(fileId);
                            } else {
                                fileUrl = SHARE_ROOT + fileId;
                                if (newUpload)
                                    out.println(
                                            "You have successfully added a file to the share, its location is: "
                                                    + fileUrl);
                                else
                                    out.println(
                                            "You have successfully updated a file on the share, its location is: "
                                                    + fileUrl);
                            }
                        } else {
                            fileUrl = null;
                            out.println("Error: Not enough information provided for file Upload");
                        }

                        ///////////////////////////////// End File Manip  /////////////////////////////////

                        out.println("</div>");
                    }
                } else {
                }

                out.write("\n");
                out.write("\t\n");
                out.write("\t<script>\n");
                out.write("\tfunction clearCommList()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  o.selected = false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction highlightComms(commList)\n");
                out.write("\t\t{\n");
                out.write("\t\t\tmult_comms = document.getElementById('communities');\n");
                out.write("\t\t\tfor ( var i = 0, l = mult_comms.options.length, o; i < l; i++ )\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t  o = mult_comms.options[i];\n");
                out.write("\t\t\t  if(commList.indexOf(o.value) == -1)\n");
                out.write("\t\t\t\to.selected = false;\n");
                out.write("\t\t\t  else  \n");
                out.write("\t\t\t  \to.selected = true;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t}\n");
                out.write("\tfunction populate()\n");
                out.write("\t{\n");
                out.write("\t\tvar typerow = document.getElementById('typerow');\n");
                out.write("\t\tvar type = document.getElementById('type');\n");
                out.write("\t\tvar title = document.getElementById('title');\n");
                out.write("\t\tvar description = document.getElementById('description');\n");
                out.write("\t\tvar file = document.getElementById('file');\n");
                out.write("\t\tvar created = document.getElementById('created');\n");
                out.write("\t\tvar DBId = document.getElementById('DBId');\n");
                out.write("\t\tvar deleteId = document.getElementById('deleteId');\n");
                out.write("\t\tvar deleteButton = document.getElementById('deleteButton');\n");
                out.write("\t\tvar share_url = document.getElementById('share_url');\n");
                out.write("\t\tvar owner_text = document.getElementById('owner_text');\n");
                out.write("\t\tvar owner = document.getElementById('owner');\n");
                out.write("\t\tvar url_row = document.getElementById('url_row');\n");
                out.write("\t\tvar dropdown = document.getElementById(\"upload_info\");\n");
                out.write("\t\tvar list = dropdown.options[dropdown.selectedIndex].value;\n");
                out.write("\t\tvar binary = document.getElementById(\"binary\");\n");
                out.write("\t\t\n");
                out.write("\t\tif (list == \"new\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"binary\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\tif ( list == \"newJSON\")\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle.value = \"\";\n");
                out.write("\t\t\tdescription.value = \"\";\n");
                out.write("\t\t\ttype.value = \"\";\n");
                out.write("\t\t\tcreated.value = \"\";\n");
                out.write("\t\t\tDBId.value = \"\";\n");
                out.write("\t\t\tdeleteId.value = \"\";\n");
                out.write("\t\t\tshare_url.value = \"\";\n");
                out.write("\t\t\towner.value = \"\";\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t\turl_row.className = \"hide\";\n");
                out.write("\t\t\towner.className = \"hide\";\n");
                out.write("\t\t\towner_text.className = \"hide\";\n");
                out.write("\t\t\tdeleteButton.className = \"hide\";\n");
                out.write("\t\t\tclearCommList();\n");
                out.write("\t\t\tbinary.value = \"null\";\n");
                out.write("\t\t\treturn;\n");
                out.write("\t\t}\n");
                out.write("\t\t\n");
                out.write("\t\t//_id, created, title, description\n");
                out.write("\t\tsplit = list.split(\"$$$\");\n");
                out.write("\t\t\n");
                out.write("\t\tres_id = split[0];\n");
                out.write("\t\tres_created = split[1];\n");
                out.write("\t\tres_title = split[2];\n");
                out.write("\t\tres_description = split[3];\n");
                out.write("\t\tres_url = split[4];\n");
                out.write("\t\tcommunities = split[5];\n");
                out.write("\t\tres_owner = split[6];\n");
                out.write("\t\tres_binary = split[7];\t\t\n");
                out.write("\t\tres_type = split[8];\t\t\t\n");
                out.write("\t\t\n");
                out.write("\t\tif ( res_binary == \"null\" )\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"show\";\n");
                out.write("\t\t}\n");
                out.write("\t\telse\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttyperow.className = \"hide\";\n");
                out.write("\t\t}\n");
                out.write("\t\ttitle.value = res_title;\n");
                out.write("\t\tdescription.value = res_description;\n");
                out.write("\t\tcreated.value = res_created;\n");
                out.write("\t\tDBId.value = res_id;\n");
                out.write("\t\tdeleteId.value = res_id;\n");
                out.write("\t\tshare_url.value = res_url;\n");
                out.write("\t\towner.value = res_owner;\t\t\n");
                out.write("\t\tdeleteButton.className = \"show\";\n");
                out.write("\t\towner.className = \"show\";\n");
                out.write("\t\towner_text.className = \"show\";\n");
                out.write("\t\turl_row.className = \"show\";\n");
                out.write("\t\thighlightComms(communities);\t\t\n");
                out.write("\t\tbinary.value = res_binary;\n");
                out.write("\t\ttype.value = res_type;\n");
                out.write("\t}\n");
                out.write("\t\tfunction validate_fields()\n");
                out.write("\t\t{\n");
                out.write("\t\t\ttitle = document.getElementById('title').value;\n");
                out.write("\t\t\tdescription = document.getElementById('description').value;\n");
                out.write("\t\t\tfile = document.getElementById('file').value;\n");
                out.write("\t\t\tbinary = document.getElementById(\"binary\").value;\n");
                out.write("\t\t\ttype = document.getElementById(\"type\").value;\n");
                out.write("\t\t\t//share_url = document.getElementById('share_url').value;\n");
                out.write("\t\t\t//file_url = document.getElementById('file_url').value;\n");
                out.write("\t\t\t//file_check = document.getElementById('file_check').checked;\n");
                out.write("\t\t\t\n");
                out.write("\t\t\tif (title == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a title.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif (description == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a description.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\tif ( binary == \"null\" && type == \"\")\n");
                out.write("\t\t\t{\n");
                out.write("\t\t\t\talert('Please provide a type.');\n");
                out.write("\t\t\t\treturn false;\n");
                out.write("\t\t\t}\n");
                out.write("\t\t\t\n");
                out.write("\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction confirmDelete()\n");
                out.write("\t\t{\n");
                out.write(
                        "\t\t\tvar agree=confirm(\"Are you sure you wish to Delete this file from the File Share?\");\n");
                out.write("\t\t\tif (agree)\n");
                out.write("\t\t\t\treturn true ;\n");
                out.write("\t\t\telse\n");
                out.write("\t\t\t\treturn false ;\n");
                out.write("\t\t}\n");
                out.write("\t\tfunction showResults()\n");
                out.write("\t\t{\n");
                out.write("\t\t\tvar title = document.getElementById('DBId').value;\n");
                out.write("\t\t\tvar url = getEndPointUrl() + \"share/get/\" + title;\n");
                out.write("\t\t\twindow.open(url, '_blank');\n");
                out.write("\t\t\twindow.focus();\t\t\t\n");
                out.write("\t\t}\n");
                out.write("\t\t// -->\n");
                out.write("\t\t</script>\n");
                out.write("\t</script>\n");
                out.write(
                        "\t\t<div id=\"uploader_outter_div\" name=\"uploader_outter_div\" align=\"center\" style=\"width:100%\" >\n");
                out.write(
                        "\t    \t<div id=\"uploader_div\" name=\"uploader_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:475px; margin:auto\">\n");
                out.write("\t        \t<h2>File Uploader</h2>\n");
                out.write("\t        \t<form id=\"search_form\" name=\"search_form\" method=\"get\">\n");
                out.write("\t        \t\t<div align=\"center\"\">\n");
                out.write("\t        \t\t<label for=\"ext\">Filter On</label>\n");
                out.write("\t\t\t\t\t  <select name=\"ext\" id=\"ext\" onchange=\"this.form.submit();\">\n");
                out.write("\t\t\t\t\t    ");

                out.print(populateMediaTypes(request, response));

                out.write("\n");
                out.write("\t\t\t\t\t  </select>\n");
                out.write("\t\t\t\t\t </div>\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t        \t<form id=\"delete_form\" name=\"delete_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return confirmDelete()\" >\n");
                out.write(
                        "\t        \t\t<select id=\"upload_info\" onchange=\"populate()\" name=\"upload_info\"><option value=\"new\">Upload New File</option><option value=\"newJSON\">Upload New JSON</option> ");

                out.print(populatePreviousUploads(request, response));

                out.write("</select>\n");
                out.write(
                        "\t        \t\t<input type=\"submit\" name=\"deleteButton\" id=\"deleteButton\" class=\"hidden\" value=\"Delete\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteId\" id=\"deleteId\" />\n");
                out.write("\t        \t\t<input type=\"hidden\" name=\"deleteFile\" id=\"deleteFile\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t        \t</form>\n");
                out.write(
                        "\t            <form id=\"upload_form\" name=\"upload_form\" method=\"post\" enctype=\"multipart/form-data\" onsubmit=\"javascript:return validate_fields();\" >\n");
                out.write(
                        "\t                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px; padding-right:10px\">\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td colspan=\"2\" align=\"center\"></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Title:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"title\" id=\"title\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>Description:</td>\n");
                out.write(
                        "\t                    <td><textarea rows=\"4\" cols=\"30\" name=\"description\" id=\"description\" ></textarea></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"typerow\">\n");
                out.write("\t                    <td>Type:</td>\n");
                out.write(
                        "\t                    <td><input type=\"text\" name=\"type\" id=\"type\" size=\"39\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td>Communities:</td>\n");
                out.write("\t                  \t<td>");

                out.print(communityList);

                out.write("</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                  \t<td id=\"owner_text\">Owner:</td>\n");
                out.write("\t                  \t<td>\n");
                out.write(
                        "\t                    <input type=\"text\" name=\"owner\" id=\"owner\" readonly=\"readonly\" size=\"25\" />\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write("\t                    <td>File:</td>\n");
                out.write("\t                    <td><input type=\"file\" name=\"file\" id=\"file\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr id=\"url_row\" class=\"hide\">\n");
                out.write("\t                  \t<td>Share URL:</td>\n");
                out.write(
                        "\t                  \t<td><input type=\"text\" name=\"share_url\" id=\"share_url\" readonly=\"readonly\" size=\"38\"/>\n");
                out.write(
                        "\t                  \t<input type=\"button\" onclick=\"showResults()\" value=\"View\"/>\n");
                out.write("\t                  \t</td>\n");
                out.write("\t                \t<td></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                  <tr>\n");
                out.write(
                        "\t                    <td colspan=\"2\" style=\"text-align:right\"><input type=\"submit\" value=\"Submit\" /></td>\n");
                out.write("\t                  </tr>\n");
                out.write("\t                </table>\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"created\" id=\"created\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"DBId\" id=\"DBId\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"fileUrl\" id=\"fileUrl\" />\n");
                out.write("\t\t\t\t\t<input type=\"hidden\" name=\"binary\" id=\"binary\" />\n");
                out.write("\t\t\t\t\t ");

                if (showAll)
                    out.print("<input type=\"hidden\" name=\"sudo\" id=\"sudo\" value=\"true\" />");

                out.write("\t        \t\t\n");
                out.write("\t\t\t\t</form>\n");
                out.write("\t        </div>\n");
                out.write("\t        <form id=\"logout_form\" name=\"logout_form\" method=\"post\">\n");
                out.write(
                        "\t        \t<input type=\"submit\" name=\"logout\" id = \"logout\" value=\"Log Out\" />\n");
                out.write("\t        </form>\n");
                out.write("\t    </div>\n");
                out.write("\t    </p>\n");
                out.write("\t\n");

            }
        } else if (isLoggedIn == false) {
            //localCookie =(request.getParameter("local") != null);
            //System.out.println("LocalCookie = " + localCookie.toString());
            String errorMsg = "";
            if (request.getParameter("logintext") != null || request.getParameter("passwordtext") != null) {
                if (logMeIn(request.getParameter("logintext"), request.getParameter("passwordtext"), request,
                        response)) {
                    showAll = (request.getParameter("sudo") != null);
                    out.println("<meta http-equiv=\"refresh\" content=\"0\">");
                    out.println("Login Success");
                } else {
                    errorMsg = "Log in Failed, Please Try again";
                }

            }

            out.write("\n");
            out.write("\n");
            out.write("<script>\n");
            out.write("\tfunction validate_fields()\n");
            out.write("\t{\n");
            out.write("\t\tuname = document.getElementById('logintext').value;\n");
            out.write("\t\tpword = document.getElementById('passwordtext').value;\n");
            out.write("\t\t\n");
            out.write("\t\tif (uname == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your username.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t\tif (pword == \"\")\n");
            out.write("\t\t{\n");
            out.write("\t\t\talert('Please provide your password.');\n");
            out.write("\t\t\treturn false;\n");
            out.write("\t\t}\n");
            out.write("\t}\n");
            out.write("\n");
            out.write("\n");
            out.write("</script>\n");
            out.write(
                    "\t<div id=\"login_outter_div\" name=\"login_outter_div\" align=\"center\" style=\"width:100%\" >\n");
            out.write(
                    "    \t<div id=\"login_div\" name=\"login_div\" style=\"border-style:solid; border-color:#999999; border-radius: 10px; width:450px; margin:auto\">\n");
            out.write("        \t<h2>Login</h2>\n");
            out.write(
                    "            <form id=\"login_form\" name=\"login_form\" method=\"post\" onsubmit=\"javascript:return validate_fields();\" >\n");
            out.write(
                    "                <table width=\"100%\" border=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"padding-left:10px\">\n");
            out.write("                  <tr>\n");
            out.write("                    <td>User Name</td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write("                    <td>Password</td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td><input type=\"text\" name=\"logintext\" id=\"logintext\" width=\"190px\" /></td>\n");
            out.write("                    <td>&nbsp;</td>\n");
            out.write(
                    "                    <td><input type=\"password\" name=\"passwordtext\" id=\"passwordtext\" width=\"190px\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                  <tr>\n");
            out.write(
                    "                    <td colspan=\"3\" align=\"right\"><input name=\"Login\" type=\"submit\" value=\"Login\" /></td>\n");
            out.write("                  </tr>\n");
            out.write("                </table>\n");
            out.write("\t\t\t</form>\n");
            out.write("        </div>\n");
            out.write("    </div>\n");
            out.write("\t<div style=\"color: red; text-align: center;\"> ");
            out.print(errorMsg);
            out.write(" </div>\n");

        }

        out.write("\n");
        out.write("    \n");
        out.write("    \n");
        out.write("</body>\n");
        out.write("</html>");
    } catch (Throwable t) {
        if (!(t instanceof SkipPageException)) {
            out = _jspx_out;
            if (out != null && out.getBufferSize() != 0)
                try {
                    out.clearBuffer();
                } catch (java.io.IOException e) {
                }
            if (_jspx_page_context != null)
                _jspx_page_context.handlePageException(t);
        }
    } finally {
        _jspxFactory.releasePageContext(_jspx_page_context);
    }
}

From source file:org.kuali.kfs.gl.batch.service.impl.PosterServiceImpl.java

/**
 * Post ICR Encumbrance GL entries to GL tables.
 *//*  ww w . ja  v  a 2 s  .c o  m*/
@Override
public void postIcrEncumbranceEntries() {
    if (LOG.isDebugEnabled()) {
        LOG.debug("postIcrEncumbranceEntries() started");
    }
    Date runDate = dateTimeService.getCurrentSqlDate();
    try {
        FileReader INPUT_GLE_FILE = new FileReader(batchFileDirectoryName + File.separator
                + GeneralLedgerConstants.BatchFileSystem.ICR_ENCUMBRANCE_POSTER_INPUT_FILE
                + GeneralLedgerConstants.BatchFileSystem.EXTENSION);
        File OUTPUT_ERR_FILE = new File(batchFileDirectoryName + File.separator
                + GeneralLedgerConstants.BatchFileSystem.ICR_ENCUMBRANCE_POSTER_ERROR_OUTPUT_FILE
                + GeneralLedgerConstants.BatchFileSystem.EXTENSION);

        postEntries(PosterService.MODE_ICRENCMB, INPUT_GLE_FILE, null, OUTPUT_ERR_FILE);

        INPUT_GLE_FILE.close();
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
        throw new RuntimeException("postIcrEncumbranceEntries Stopped: " + e1.getMessage(), e1);
    } catch (IOException ioe) {
        LOG.error("postIcrEncumbranceEntries stopped due to: " + ioe.getMessage(), ioe);
        throw new RuntimeException(ioe);
    }
}

From source file:com.chinamobile.bcbsp.fault.browse.ReadFaultlog.java

/**
 * file is the srcFile,and keys is the given key and the keys can be null then
 * the function is read all the record in the file,if none of keys ,it is
 * better to use read(File file) ,the function need not judge for each record
 * return the match condition record//from  w  ww . j av a2s.  c  o m
 * @param file
 *        source file
 * @param keys
 *        keys to tell whether need to read the file.
 * @return fault list.
 */
private List<Fault> readFileWithKey(File file, String[] keys) {
    FileReader fr = null;
    try {
        List<Fault> records = new ArrayList<Fault>();
        fr = new FileReader(file);
        br = new BufferedReader(fr);
        String tempRecord = null;
        String filds[] = null;
        while ((tempRecord = br.readLine()) != null) {
            boolean matching = true;
            if (keys != null) {
                for (String key : keys) {
                    if (key == null) {
                        continue;
                    }
                    if ((tempRecord.indexOf(key) == -1)
                            && (tempRecord.toLowerCase().indexOf(key.toLowerCase()) == -1)) {
                        matching = false;
                        break;
                    }
                }
            }
            if (matching == true) {
                filds = tempRecord.split("--");
                Fault fault = new Fault();
                fault.setTimeOfFailure(filds[0].trim());
                fault.setType(getType(filds[1].trim()));
                fault.setLevel(getLevel(filds[2].trim()));
                fault.setWorkerNodeName(filds[3].trim());
                fault.setJobName((filds[4].trim()));
                fault.setStaffName(filds[5].trim());
                fault.setExceptionMessage(filds[6].trim());
                fault.setFaultStatus(getBoolean(filds[7].trim()));
                records.add(fault);
            } else {
                continue;
            }
        }
        br.close();
        fr.close();
        return records;
    } catch (FileNotFoundException e) {
        LOG.error("[readFileWithKey]", e);
        return new ArrayList<Fault>();
    } catch (IOException e) {
        LOG.error("[readFileWithKey]", e);
        try {
            br.close();
            fr.close();
        } catch (IOException e1) {
            LOG.error("[readFileWithKey]", e1);
        }
        return new ArrayList<Fault>();
    }
}

From source file:com.clustercontrol.util.KeyCheck.java

/**
 * //from w ww.ja v a2s  . co  m
 * @param type
 * @return
 */
private static boolean checkCommon(String type) {

    boolean keyCheck = false;

    String etcdir = System.getProperty("hinemos.manager.etc.dir");

    File[] files = null;
    PublicKey publicKey = null;
    try {
        publicKey = getPublicKey(PUBLIC_KEY_STR);
        m_log.info("etcdir=" + etcdir);
        File directory = new File(etcdir); // TODO ?????
        files = directory.listFiles();
        if (files == null) {
            m_log.warn(etcdir + " does not exist");
            return false;
        }
        m_log.info("key files=" + files.length);
    } catch (Exception e) {
        m_log.warn(e.getMessage(), e);
        return false;
    }

    SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
    int yearMonth = Integer.parseInt(sdf.format(new Date()));
    for (File file : files) {
        FileReader fileReader = null;
        try {
            String filename = file.getName();
            String filenamePre = filename.substring(0, 6);

            /*
             * ?0:
             * ??????
             * ??????
             */
            String[] fileTypeArr = filename.split("_");
            if (fileTypeArr.length != 3 || !fileTypeArr[2].equals(type)) {
                m_log.debug("file type different. fileName:" + filename + ", targetType:" + type);
                continue;
            }

            /*
             * ?1:
             * ???
             * ???prefix???????
             * ????????201401_001???????prefix=201401
             */
            m_log.trace("filename=" + filename + ", filePrefix=" + filenamePre);
            if (yearMonth <= Integer.parseInt(filenamePre)) {
                m_log.debug("OK time limit, filename=" + filename);
            } else {
                m_log.debug("NG time limit, filename=" + filename);
                continue;
            }

            /*
             * ?2:
             * ?????????????????
             */
            fileReader = new FileReader(file);
            int charLength = 256;
            char[] cbuf = new char[charLength];
            fileReader.read(cbuf, 0, charLength);
            String str = decrypt(new String(cbuf), publicKey);
            m_log.trace("filename=" + filename + ", contents=" + str);
            if (filename.equals(str)) {
                m_log.debug("OK valid file, filename=" + filename);
                // ????????????
                keyCheck = true;
                break;
            } else {
                m_log.debug("NG valid file, filename=" + filename);
                continue;
            }
        } catch (Exception e) {
            if (e instanceof NumberFormatException) {
                m_log.info(e.getMessage());
            } else {
                m_log.info(e.getMessage(), e);
            }
        } finally {
            if (fileReader != null) {
                try {
                    fileReader.close();
                } catch (IOException e) {
                    // nop
                }
            }
        }
    }
    m_log.info("license check result:" + keyCheck);
    return keyCheck;
}

From source file:hoot.services.controllers.ingest.CustomScriptResource.java

protected boolean validateExport(String script) {

    boolean canExport = false;
    org.mozilla.javascript.Context context = org.mozilla.javascript.Context.enter();
    try {// w w  w .j  av  a  2 s  . com
        // initialize Rhino

        org.mozilla.javascript.ScriptableObject scope = context.initStandardObjects();
        context.setOptimizationLevel(-1);

        scope.put("context", scope, context);
        scope.put("scope", scope, scope);
        scope.put("APP_ROOT", scope, homeFolder);

        FileReader frHeader = new FileReader(jsHeaderScriptPath);
        BufferedReader jsHeader = new BufferedReader(frHeader);
        context.evaluateReader(scope, jsHeader, "jsHeader", 1, null);

        StringReader sr = new StringReader(script);
        BufferedReader translation_script = new BufferedReader(sr);
        context.evaluateReader(scope, translation_script, "translation_script", 1, null);

        // call getDbSchema call any required preloading functions
        Object getSchemaObj = scope.get("getDbSchema", scope);
        Object translateToOgr = scope.get("translateToOgr", scope);

        boolean getDbSchemaExist = false;
        if (getSchemaObj != null) {
            // If not exist then will return Tag instead of function
            if (getSchemaObj instanceof Function) {
                getDbSchemaExist = true;
            }
        }

        boolean translateToOgrExist = false;
        if (translateToOgr != null) {
            // If not exist then will return Tag instead of function
            if (translateToOgr instanceof Function) {
                translateToOgrExist = true;
            }
        }

        canExport = getDbSchemaExist && translateToOgrExist;

        frHeader.close();
        jsHeader.close();
        sr.close();
        translation_script.close();

    } catch (Exception ex) {
        log.error(ex.getMessage());
    } finally {
        context.exit();
    }
    return canExport;
}

From source file:org.gvnix.web.menu.roo.addon.MenuEntryOperationsImpl.java

/**
 * Updates the contents for one resource represented by the given target
 * file path and relative source path./* ww w  .  j  a v  a  2 s .  c  om*/
 * 
 * @param relativePath path relative to {@link Path.SRC_MAIN_WEBAPP} of
 *        target file
 * @param resourceName path relative to classpath of file to be copied
 *        (cannot be null)
 * @param toReplace
 * @param containsStrings
 */
private void updateResource(String relativePath, String resourceName, Map<String, String> toReplace,
        String[] containsStrings) {
    PathResolver pathResolver = getPathResolver();

    String targetPath = pathResolver.getIdentifier(LogicalPath.getInstance(Path.SRC_MAIN_WEBAPP, ""),
            relativePath);

    InputStream resource = getClass().getResourceAsStream(resourceName);

    String sourceContents;
    String targetContents = null;

    // load resource to copy
    try {
        sourceContents = IOUtils.toString(new InputStreamReader(resource));
        // Replace params
        if (toReplace != null) {
            for (Entry<String, String> entry : toReplace.entrySet()) {
                sourceContents = StringUtils.replace(sourceContents, entry.getKey(), entry.getValue());
            }
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unable to load file to be copied '".concat(resourceName).concat("'"),
                e);
    } finally {
        try {
            resource.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // load target contents if exists
    if (fileManager.exists(targetPath)) {
        FileReader reader = null;
        try {
            reader = new FileReader(targetPath);
            targetContents = IOUtils.toString(reader);
        } catch (Exception e) {
            throw new IllegalStateException("Error reading '".concat(targetPath).concat("'"), e);
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    // prepare mutable file
    // use MutableFile in combination with FileManager to take advantage of
    // Roos transactional file handling which offers automatic rollback if
    // an
    // exception occurs
    MutableFile target = fileManager.updateFile(targetPath);

    if (target == null) {
        return;
    }

    try {
        InputStream inputStream = null;
        OutputStreamWriter outputStream = null;
        try {
            inputStream = IOUtils.toInputStream(sourceContents);
            outputStream = new OutputStreamWriter(target.getOutputStream());
            IOUtils.copy(inputStream, outputStream);
        } finally {
            IOUtils.closeQuietly(inputStream);
            IOUtils.closeQuietly(outputStream);
        }
    } catch (IOException e) {
        throw new IllegalStateException("Unable to create/update '".concat(targetPath).concat("'"), e);
    }
}

From source file:it.illinois.adsc.ema.softgrid.monitoring.ui.SPMainFrame.java

private void refresh() {
    if (!chartPanelVisible) {
        return;/*from www .jav a 2 s . c om*/
    }
    try {
        File file = new File(ConfigUtil.LIMIT_VIOLATION_RECORD_FILE);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                JOptionPane.showMessageDialog(this, "Invalid Limit Violation Path\n" + file.getAbsolutePath());
                //                    System.exit(0);
            }
        }

        BufferedReader bufferedReader;
        String line = "";
        for (MonitorConfig monitorConfig : monitorConfigs) {
            monitorConfig.setXySeries(new XYSeries(monitorConfig.toString()));
        }
        long lineCount = -1;
        long racordCount = 0;
        String type = "";
        boolean found = false;
        for (int j = 0; j < 2; j++) {
            File logFile = new File(ConfigUtil.LOG_FILE);
            if (!logFile.exists()) {
                logFile = new File(ConfigUtil.LOG_FILE + "." + j);
                if (!logFile.exists()) {
                    System.out.println("Invalid IED log file path.\n" + logFile.getAbsolutePath());
                    break;
                }
            } else {
                j = 2;
            }
            bufferedReader = new BufferedReader(new FileReader(logFile));
            while ((line = bufferedReader.readLine()) != null) {
                lineCount++;
                String[] data = line.split(":");
                if (data.length >= 4 && data[0].equals("Data")) {
                    double timeinMilis = (Double.parseDouble(data[1]) - startTime) * 100.00 / 100000.00;
                    if (timeinMilis < 0)
                        startTime -= 10;
                    //                      Day day = new Day(Long.parseLong(data[1]));
                    type = data[3];
                    //                      select the type
                    ArrayList<MonitorConfig> newMonitors = new ArrayList<MonitorConfig>();
                    ArrayList<MonitorConfig> removableQueries = new ArrayList<MonitorConfig>();
                    for (MonitorConfig monitorConfig : monitorConfigs) {
                        if (monitorConfig.getDeviceType().equalsIgnoreCase(type)) {
                            if (monitorConfig.getKeyValueMap().isEmpty()) {
                                found = true;
                            } else {
                                for (String key : monitorConfig.getKeyValueMap().keySet()) {
                                    found = false;
                                    for (int i = 4; i < data.length; i++) {
                                        if (data[i].equalsIgnoreCase(key) && data.length >= i + 1) {
                                            if (data[i + 1].trim().equalsIgnoreCase(
                                                    monitorConfig.getKeyValueMap().get(key))) {
                                                found = true;
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            if (found) {
                                for (int i = 4; i < data.length; i++) {
                                    if (monitorConfig.getXySeries() != null
                                            && data[i].equalsIgnoreCase(monitorConfig.getVariable())) {
                                        double value = 0;
                                        try {
                                            if (data[i + 1].equals("Closed")) {
                                                value = 0;
                                            } else if (data[i + 1].equals("Open")) {
                                                value = 1;
                                            } else {
                                                value = Double.parseDouble(data[i + 1]);
                                            }
                                            if (this.isVisible() && timeinMilis > 0 && value < 0.5
                                                    && monitorConfig.getVariable().contains("BusKVVolt")) {
                                                JOptionPane.showMessageDialog(this, "Blackout occurred...!");
                                                try {
                                                    Thread.sleep(7000);
                                                } catch (InterruptedException e) {
                                                    e.printStackTrace();
                                                }
                                                stopIEDServers();
                                            }
                                        } catch (NumberFormatException e) {
                                            System.out.println("data[2] = " + data[2]);
                                            e.printStackTrace();
                                            return;
                                        }
                                        monitorConfig.getXySeries().add(timeinMilis, value);
                                        maxTimeRange = (long) timeinMilis;
                                        if (maxTimeRange > 0 && dataFileWriter != null) {
                                            dataFileWriter
                                                    .write(maxTimeRange + " , " + monitorConfig.getVariable()
                                                            + " , " + String.valueOf(value) + "\n");
                                            dataFileWriter.flush();
                                        }
                                        if (racordCount >= 100000) {
                                            XYDataItem xyDataItem = monitorConfig.getXySeries().remove(0);
                                            minTimeRange = xyDataItem.getX().longValue();
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if (monitorConfigs.size() < 10) {
                        monitorConfigs.addAll(newMonitors);
                    }
                    if (racordCount < 50000) {
                        racordCount++;
                    }
                }
            }
            bufferedReader.close();
        }
        SMAlert smAlert = lastAlert;
        while (smAlert != null && smAlert.getPreviouseAlert() != null) {
            smAlert = smAlert.getPreviouseAlert();
            long addedTime = alertTimeMap.get(smAlert);
            if ((System.currentTimeMillis() - addedTime) > ALERT_STORE_DURATION) {
                removeAlert(smAlert);
            }
        }
        FileReader fileReader = null;
        BufferedReader violationReader = null;
        try {
            fileReader = new FileReader(file);
            violationReader = new BufferedReader(fileReader);
            while ((line = violationReader.readLine()) != null) {
                String[] vlData = line.split(",");
                try {
                    long addedTime = Long.parseLong(vlData[0]);
                    if ((System.currentTimeMillis() - addedTime) <= ALERT_STORE_DURATION) {
                        addAlert(addedTime, new SMAlert(vlData[3], vlData[2], vlData[1]));
                    }
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                violationReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                fileReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        lastLine = lineCount;
        dataset.removeAllSeries();
        for (MonitorConfig monitorConfig : monitorConfigs) {
            if (monitorConfig.getXySeries() != null) {
                dataset.addSeries(monitorConfig.getXySeries());
            }
        }
        ChartPanel tempNewPanel = getChartPanel();
        if (tempNewPanel != null) {
            JPanel tempPanel = chartPanel;
            chartPanel = tempNewPanel;
            chartPanel.updateUI();
            Component component = resultTabbedPane.getSelectedComponent();
            resultTabbedPane.remove(tempPanel);
            resultTabbedPane.add(chartPanel, "Chart Panel");
            resultTabbedPane.setSelectedComponent(component == tempPanel ? chartPanel : component);
            //              this.getContentPane().add(chartPanel, new GridBagConstraints(0, 2, 1, 1, 0.75, 0.75, GridBagConstraints.CENTER, GridBagConstraints.BOTH, new Insets(12, 0, 12, 0), 0, 0));
            //              if (tempPanel != null) {
            //                  this.getContentPane().remove(tempPanel);
            //              }
            chartPanel.updateUI();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    this.getContentPane().repaint();
}