Example usage for java.io OutputStreamWriter close

List of usage examples for java.io OutputStreamWriter close

Introduction

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

Prototype

public void close() throws IOException 

Source Link

Usage

From source file:com.multimedia.service.wallpaper.CmsWallpaperService.java

protected boolean createDescriptionFile(File cur_dir, Long page_id, String page_name, boolean prepared) {
    File description = new File(cur_dir, DESCRIPTION_FILE);
    if (!description.exists()) {
        try {/*from   ww w  .j  a v  a 2s. co m*/
            description.createNewFile();
            OutputStreamWriter fos = new OutputStreamWriter(new FileOutputStream(description), "UTF-8");
            fos.write("id=");
            fos.write(String.valueOf(page_id));
            fos.write("\r\nname=");
            fos.write(page_name);
            fos.write("\r\nname_translit=");
            fos.write(FileUtils.toTranslit(page_name));
            if (prepared) {
                fos.write("\r\npre_uploaded=true");
            }
            fos.close();
        } catch (IOException ex) {
            logger.error("", ex);
            return false;
        }
    }
    return true;
}

From source file:net.mindengine.oculus.frontend.web.controllers.project.ProjectAjaxBrowseController.java

@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String id = request.getParameter("id");
    if (id == null || !id.startsWith("p"))
        throw new InvalidRequest();
    Long projectId = Long.parseLong(id.substring(1));

    boolean asRoot = false;
    if (request.getParameter("asRoot") != null) {
        asRoot = true;//from  www  .j a v  a  2s .co  m
    }
    List<Project> projects = projectDAO.getSubprojects(projectId);
    List<Test> tests = testDAO.getTestsByProjectId(projectId);

    OutputStream os = response.getOutputStream();
    response.setContentType("text/xml");
    OutputStreamWriter w = new OutputStreamWriter(os);

    w.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
    w.write("<tree id=\"");
    if (projectId.equals(0L) || asRoot) {
        w.write("0");
    } else
        w.write(id);
    w.write("\">");
    for (Project project : projects) {
        w.write("<item text=\"");
        w.write(StringEscapeUtils.escapeXml(project.getName()));
        w.write("\" id=\"p");
        w.write(Long.toString(project.getId()));
        w.write("\" im0=\"tombs.gif\" im1=\"tombs_open.gif\" im2=\"tombs.gif\" ");
        if (project.getSubprojectsCount() > 0 || project.getTestsCount() > 0) {
            w.write(" child=\"1\" ");
        }
        w.write("></item>");
    }

    for (Test test : tests) {
        w.write("<item text=\"");
        w.write(StringEscapeUtils.escapeXml(test.getName()));
        w.write("\" id=\"t");
        w.write(Long.toString(test.getId()));
        w.write("\" im0=\"iconTest.png\" im1=\"iconTest.png\" im2=\"iconTest.png\" ");
        w.write("></item>");
    }
    w.write("</tree>");

    w.flush();
    w.close();
    return null;
}

From source file:com.hardcopy.retroband.MainActivity.java

public void guardarDatos(int[] accel) {
    try {/*from  w w  w.  j a v a 2s  . c om*/
        File ruta_sd = Environment.getExternalStorageDirectory();

        File f = new File(ruta_sd.getAbsolutePath(), nombreArchivo);

        FileOutputStream fos = new FileOutputStream(f, true);// new
        // FileOutputStream(f);override

        OutputStreamWriter fout = new OutputStreamWriter(fos);

        for (int i = 0; i < accel.length; i += 3) {
            String texto = String.valueOf(accel[i]) + "," + String.valueOf(accel[i + 1]) + ","
                    + String.valueOf(accel[i + 2]) + "\n";
            // System.out.print(texto);
            fout.write(texto);
        }
        fout.close();
    } catch (Exception ex) {
        Log.e("Ficheros", "Error al escribir fichero a tarjeta SD");
    }
}

From source file:de.uni_koeln.spinfo.maalr.services.editor.server.EditorServiceImpl.java

public void export(Set<String> fields, EditorQuery query, File dest)
        throws NoDatabaseAvailableException, IOException {
    query.setCurrent(0);/*from  www .j  av a  2 s  . c om*/
    ZipOutputStream zout = new ZipOutputStream(new FileOutputStream(dest));
    zout.putNextEntry(new ZipEntry("exported.tsv"));
    OutputStream out = new BufferedOutputStream(zout);
    OutputStreamWriter writer = new OutputStreamWriter(out, "UTF-8");
    for (String field : fields) {
        writer.write(field);
        writer.write("\t");
    }
    writer.write("\n");
    while (true) {
        LexEntryList result = Database.getInstance().queryForLexEntries(query.getUserOrIp(), query.getRole(),
                query.getVerification(), query.getVerifier(), query.getStartTime(), query.getEndTime(),
                query.getState(), query.getPageSize(), query.getCurrent(), query.getSortColumn(),
                query.isSortAscending());
        if (result == null || result.getEntries() == null || result.getEntries().size() == 0)
            break;
        for (LexEntry lexEntry : result.entries()) {
            addUserInfos(lexEntry);
            LemmaVersion version = lexEntry.getCurrent();
            write(writer, version, fields);
            writer.write("\n");
        }
        query.setCurrent(query.getCurrent() + query.getPageSize());
    }
    writer.flush();
    zout.closeEntry();
    writer.close();
}

From source file:edu.ur.ir.ir_export.service.DefaultContributorTypeExportService.java

/** 
 * Create the xml file for the set of collections.
 * /*  w  ww  .  ja  v a 2  s .c o  m*/
 * @param xmlFile - file to write the xml to
 * @param contributor types - set of contributor types to export
 * 
 * @throws IOException - if writing to the file fails.
 */
public void createXmlFile(File xmlFile, Collection<ContributorType> contributorTypes) throws IOException {
    DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
    DocumentBuilder builder;

    String path = FilenameUtils.getPath(xmlFile.getCanonicalPath());
    if (!path.equals("")) {
        File pathOnly = new File(FilenameUtils.getFullPath(xmlFile.getCanonicalPath()));
        FileUtils.forceMkdir(pathOnly);
    }

    if (!xmlFile.exists()) {
        if (!xmlFile.createNewFile()) {
            throw new IllegalStateException("could not create file");
        }
    }

    try {
        builder = factory.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        throw new IllegalStateException(e);
    }

    DOMImplementation impl = builder.getDOMImplementation();
    DOMImplementationLS domLs = (DOMImplementationLS) impl.getFeature("LS", "3.0");
    LSSerializer serializer = domLs.createLSSerializer();
    LSOutput lsOut = domLs.createLSOutput();

    Document doc = impl.createDocument(null, "contributor_types", null);
    Element root = doc.getDocumentElement();

    FileOutputStream fos;
    OutputStreamWriter outputStreamWriter;
    BufferedWriter writer;

    try {
        fos = new FileOutputStream(xmlFile);

        try {
            outputStreamWriter = new OutputStreamWriter(fos, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            throw new IllegalStateException(e);
        }
        writer = new BufferedWriter(outputStreamWriter);
        lsOut.setCharacterStream(writer);
    } catch (FileNotFoundException e) {
        throw new IllegalStateException(e);
    }

    // create XML for the child collections
    for (ContributorType ct : contributorTypes) {
        Element contributorType = doc.createElement("contributor_type");

        this.addIdElement(contributorType, ct.getId().toString(), doc);
        this.addNameElement(contributorType, ct.getName(), doc);
        this.addDescription(contributorType, ct.getDescription(), doc);
        this.addSystemCode(contributorType, ct.getUniqueSystemCode(), doc);
    }
    serializer.write(root, lsOut);

    try {
        fos.close();
        writer.close();
        outputStreamWriter.close();
    } catch (Exception e) {
        throw new IllegalStateException(e);
    }

}

From source file:com.redhat.rhn.frontend.action.common.DownloadFile.java

@Override
protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request,
        HttpServletResponse response) throws Exception {

    String path = "";
    Map params = (Map) request.getAttribute(PARAMS);
    String type = (String) params.get(TYPE);
    if (type.equals(DownloadManager.DOWNLOAD_TYPE_KICKSTART)) {
        return getStreamInfoKickstart(mapping, form, request, response, path);
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER)) {
        String url = ConfigDefaults.get().getCobblerServerUrl() + (String) params.get(URL_STRING);
        KickstartHelper helper = new KickstartHelper(request);
        String data = "";
        if (helper.isProxyRequest()) {
            data = KickstartManager.getInstance().renderKickstart(helper.getKickstartHost(), url);
        } else {// w  w  w . j  av  a2  s . c  o  m
            data = KickstartManager.getInstance().renderKickstart(url);
        }
        setTextContentInfo(response, data.length());
        return getStreamForText(data.getBytes());
    } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_COBBLER_API)) {
        // read data from POST body
        String postData = new String();
        String line = null;
        BufferedReader reader = request.getReader();
        while ((line = reader.readLine()) != null) {
            postData += line;
        }

        // Send data
        URL url = new URL(ConfigDefaults.get().getCobblerServerUrl() + "/cobbler_api");
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
        // this will write POST /download//cobbler_api instead of
        // POST /cobbler_api, but cobbler do not mind
        wr.write(postData, 0, postData.length());
        wr.flush();
        conn.connect();

        // Get the response
        String output = new String();
        BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        while ((line = rd.readLine()) != null) {
            output += line;
        }
        wr.close();

        KickstartHelper helper = new KickstartHelper(request);
        if (helper.isProxyRequest()) {
            // Search/replacing all instances of cobbler host with host
            // we pass in, for use with Spacewalk Proxy.
            output = output.replaceAll(ConfigDefaults.get().getCobblerHost(), helper.getForwardedHost());
        }

        setXmlContentInfo(response, output.length());
        return getStreamForXml(output.getBytes());
    } else {
        Long fileId = (Long) params.get(FILEID);
        Long userid = (Long) params.get(USERID);
        User user = UserFactory.lookupById(userid);
        if (type.equals(DownloadManager.DOWNLOAD_TYPE_PACKAGE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            setBinaryContentInfo(response, pack.getPackageSize().intValue());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + pack.getPath();
            return getStreamForBinary(path);
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_SOURCE)) {
            Package pack = PackageFactory.lookupByIdAndOrg(fileId, user.getOrg());
            List<PackageSource> src = PackageFactory.lookupPackageSources(pack);
            if (!src.isEmpty()) {
                setBinaryContentInfo(response, src.get(0).getPackageSize().intValue());
                path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + src.get(0).getPath();
                return getStreamForBinary(path);
            }
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_REPO_LOG)) {
            Channel c = ChannelFactory.lookupById(fileId);
            ChannelManager.verifyChannelAdmin(user, fileId);
            StringBuilder output = new StringBuilder();
            for (String fileName : ChannelManager.getLatestSyncLogFiles(c)) {
                RandomAccessFile file = new RandomAccessFile(fileName, "r");
                long fileLength = file.length();
                if (fileLength > DOWNLOAD_REPO_LOG_LENGTH) {
                    file.seek(fileLength - DOWNLOAD_REPO_LOG_LENGTH);
                    // throw away text till end of the actual line
                    file.readLine();
                } else {
                    file.seek(0);
                }
                String line;
                while ((line = file.readLine()) != null) {
                    output.append(line);
                    output.append("\n");
                }
                file.close();
                if (output.length() > DOWNLOAD_REPO_LOG_MIN_LENGTH) {
                    break;
                }
            }

            setTextContentInfo(response, output.length());
            return getStreamForText(output.toString().getBytes());
        } else if (type.equals(DownloadManager.DOWNLOAD_TYPE_CRASHFILE)) {
            CrashFile crashFile = CrashManager.lookupCrashFileByUserAndId(user, fileId);
            String crashPath = crashFile.getCrash().getStoragePath();
            setBinaryContentInfo(response, (int) crashFile.getFilesize());
            path = Config.get().getString(ConfigDefaults.MOUNT_POINT) + "/" + crashPath + "/"
                    + crashFile.getFilename();
            return getStreamForBinary(path);

        }
    }

    throw new UnknownDownloadTypeException(
            "The specified download type " + type + " is not currently supported");

}

From source file:com.denimgroup.threadfix.importer.cli.CommandLineMigration.java

private static void convert(String inputScript, String outputScript) {
    File file = new File(inputScript);

    LOGGER.info("Converting threadfix script to mySql script " + outputScript + " ...");

    File outputFile = new File(outputScript);

    FileOutputStream fos = null;//from w  w  w .j a  va2s.c o m
    try {
        fos = new FileOutputStream(outputFile);

        OutputStreamWriter osw = new OutputStreamWriter(fos);

        List<String> lines = FileUtils.readLines(file);

        osw.write("SET FOREIGN_KEY_CHECKS=0;\n");

        String table;
        for (String line : lines) {
            if (line != null && line.toUpperCase().startsWith("CREATE MEMORY TABLE ")) {
                table = RegexUtils.getRegexResult(line, TABLE_PATTERN);
                System.out.println("Create new table:" + table);
                String[] tableName = table.split("\\(", 2);
                if (tableName.length == 2) {
                    List<String> fieldList = list();
                    String[] fields = tableName[1].trim().replace("(", "").replace(")", "").split(",");
                    for (int i = 0; i < fields.length; i++) {
                        if (!"CONSTRAINT".equalsIgnoreCase(fields[i].trim().split(" ")[0])) {
                            String field = fields[i].trim().split(" ")[0].replace("\"", "");
                            if (!fieldList.contains(field))
                                fieldList.add(field);
                        }
                    }
                    String fieldsStr = org.apache.commons.lang3.StringUtils.join(fieldList, ",");
                    tableMap.put(tableName[0].toUpperCase(), "(" + fieldsStr + ")");
                }
            } else if (line != null && line.toUpperCase().startsWith("INSERT INTO ")) {
                table = RegexUtils.getRegexResult(line, INSERT_PATTERN).toUpperCase();
                if (tableMap.get(table) != null) {
                    line = line.replaceFirst(" " + table + " ", " " + table + tableMap.get(table) + " ");
                    if (line.contains(ACUNETIX_ESCAPE)) {
                        line = line.replace(ACUNETIX_ESCAPE, ACUNETIX_ESCAPE_REPLACE);
                    }
                    line = escapeString(line) + ";\n";

                    osw.write(line);
                }
            }
        }
        osw.write("SET FOREIGN_KEY_CHECKS=1;\n");
        osw.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:fr.gouv.finances.dgfip.xemelios.importers.archives.ArchiveImporter.java

protected FileInfo doImportManifeste(Document manif, String archiveName) throws IOException {
    DocumentModel dm = documentsModel.getDocumentById("manifeste2");
    String idColl = "0000";
    String libColl = "Traabilit";
    String idBudg = "00";
    String libBudg = "--";

    Pair collectivite = new Pair(idColl, libColl);
    Pair budget = new Pair(idBudg, libBudg);
    if (importedArchiveManifeste != null) {
        try {/*from  ww  w  .  ja v  a 2 s .co m*/
            DataLayerManager.getImplementation().removeDocument(dm, budget, collectivite, archiveName + ".xml",
                    user);
        } catch (Exception ex) {
            logger.error("while dropping previous manifeste", ex);
        }
    }

    File outputFile = null;
    try {
        outputFile = new File(FileUtils.getTempDir(), archiveName + ".xml");
        Charset cs = Charset.forName("UTF-8");
        OutputStreamWriter osw = new OutputStreamWriter(new FileOutputStream(outputFile), cs);
        osw.write(manif.toXML());
        osw.flush();
        osw.close();
        Class clazz = Class.forName(dm.getImportClass());
        Constructor cc = clazz.getConstructor(XemeliosUser.class, PropertiesExpansion.class);
        Object obj = cc.newInstance(getUser(), applicationProperties);
        if (!(obj instanceof EtatImporteur)) {
            throw new DataConfigurationException(
                    "Cette classe n'est pas un importeur.\nLe fichier de configuration qui vous a t livr est certainement invalide.\nVeuillez contacter votre fournisseur.");
        }
        EtatImporteur ei = (EtatImporteur) obj;
        // WARNING : if one name per archive (and not one per volume), change this
        ei.setArchiveName(archiveName);
        ei.setImpSvcProvider(importServiceProvider);
        importServiceProvider.setEtatImporter(ei);
        ei.setOverwriteRule("never");
        ei.setApplicationConfiguration(applicationProperties);

        ei.setDocument(dm);
        File[] fichiers = new File[] { outputFile };
        ei.setFilesToImport(fichiers);

        importServiceProvider.setCollectivite(collectivite);
        importServiceProvider.setBudget(budget);
        ei.setCollectivite(collectivite);
        ei.setBudget(budget);

        ei.run();
        FileInfo fInfo = ei.getFileInfo();
        if (ei.getWarningCount() > 0)
            fInfo.setWarningCount(ei.getWarningCount());
        return fInfo;
    } catch (Exception ex) {
        logger.error("importer", ex);
        return new FileInfo();
    } finally {
        if (outputFile.exists()) {
            outputFile.delete();
        }
    }
}

From source file:com.moviejukebox.plugin.AnimatorPlugin.java

/**
 * Retrieve Animator matching the specified movie name and year.
 *
 * This routine is base on a Google request.
 *///from  w  w  w  . j a v  a 2  s  .co m
private String getAnimatorId(String movieName, String year) {
    try {
        String animatorId = Movie.UNKNOWN;
        String allmultsId = Movie.UNKNOWN;

        String sb = movieName;
        // Unaccenting letters
        sb = Normalizer.normalize(sb, Normalizer.Form.NFD);
        // Return simple letters '' & ''
        sb = sb.replaceAll("" + (char) 774, "");
        sb = sb.replaceAll("" + (char) 774, "");
        sb = sb.replaceAll("\\p{InCombiningDiacriticalMarks}+", "");

        sb = "text=" + URLEncoder.encode(sb, "Cp1251").replace(" ", "+");

        // Get ID from animator.ru
        if (animatorDiscovery) {
            String uri = "http://www.animator.ru/db/?p=search&SearchMask=1&" + sb;
            if (StringTools.isValidString(year)) {
                uri = uri + "&year0=" + year;
                uri = uri + "&year1=" + year;
            }
            String xml = httpClient.request(uri);
            // Checking for zero results
            if (xml.contains("[?? ]")) {
                // It's search results page, searching a link to the movie page
                int beginIndex;
                if (-1 != xml.indexOf("? ")) {
                    for (String tmp : HTMLTools.extractTags(xml, "? ", HTML_TD, HTML_HREF,
                            "<br><br>")) {
                        if (0 < tmp.indexOf("[?? ]")) {
                            beginIndex = tmp.indexOf(" .)");
                            if (beginIndex >= 0) {
                                String year2 = tmp.substring(beginIndex - 4, beginIndex);
                                if (year2.equals(year)) {
                                    beginIndex = tmp.indexOf("http://www.animator.ru/db/?p=show_film&fid=",
                                            beginIndex);
                                    if (beginIndex >= 0) {
                                        StringTokenizer st = new StringTokenizer(tmp.substring(beginIndex + 43),
                                                " ");
                                        animatorId = st.nextToken();
                                        break;
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }

        // Get ID from allmults.org
        if (multsDiscovery) {
            URL url = new URL("http://allmults.org/search.php");
            URLConnection conn = url.openConnection(YamjHttpClientBuilder.getProxy());
            conn.setDoOutput(true);

            OutputStreamWriter osWriter = null;
            StringBuilder xmlLines = new StringBuilder();

            try {
                osWriter = new OutputStreamWriter(conn.getOutputStream());
                osWriter.write(sb);
                osWriter.flush();

                try (InputStreamReader inReader = new InputStreamReader(conn.getInputStream(), "cp1251");
                        BufferedReader bReader = new BufferedReader(inReader)) {
                    String line;
                    while ((line = bReader.readLine()) != null) {
                        xmlLines.append(line);
                    }
                }

                osWriter.flush();
            } finally {
                if (osWriter != null) {
                    osWriter.close();
                }
            }

            if (xmlLines.indexOf("<div class=\"post\"") != -1) {
                for (String tmp : HTMLTools.extractTags(xmlLines.toString(),
                        "  ?  ", "<ul><li>", "<div class=\"entry\"",
                        "</div>")) {
                    int pos = tmp.indexOf("<img ");
                    if (pos != -1) {
                        int temp = tmp.indexOf(" alt=\"");
                        if (temp != -1) {
                            String year2 = tmp.substring(temp + 6, tmp.indexOf("\"", temp + 6) - 1);
                            year2 = year2.substring(year2.length() - 4);
                            if (year2.equals(year)) {
                                temp = tmp.indexOf(" src=\"/images/multiki/");
                                if (temp != -1) {
                                    allmultsId = tmp.substring(temp + 22, tmp.indexOf(".jpg", temp + 22));
                                    break;
                                }
                            }
                        }
                    }
                }
            }
        }

        return (animatorId.equals(Movie.UNKNOWN) && allmultsId.equals(Movie.UNKNOWN)) ? Movie.UNKNOWN
                : animatorId + ":" + allmultsId;
    } catch (IOException error) {
        LOG.error("Failed retreiving Animator Id for movie : {}", movieName);
        LOG.error("Error : {}", error.getMessage());
        return Movie.UNKNOWN;
    }
}

From source file:org.opendatakit.utilities.ODKFileUtils.java

/**
 * TODO this is almost identical to checkOdkAppVersion
 *
 * @param appName           the app name
 * @param odkAppVersionFile the file that contains the installed version
 * @param apkVersion        the version to overwrite odkAppVerisonFile with
 *//*from w w w.j  a va  2 s.  co m*/
private static void writeConfiguredOdkAppVersion(String appName, String odkAppVersionFile, String apkVersion) {
    File versionFile = new File(getDataFolder(appName), odkAppVersionFile);

    if (!versionFile.exists()) {
        if (!versionFile.getParentFile().mkdirs()) {
            //throw new RuntimeException("Failed mkdirs on " + versionFile.getPath());
            WebLogger.getLogger(appName).e(TAG, "Failed mkdirs on " + versionFile.getParentFile().getPath());
        }
    }

    FileOutputStream fs = null;
    OutputStreamWriter w = null;
    BufferedWriter bw = null;
    try {
        fs = new FileOutputStream(versionFile, false);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            w = new OutputStreamWriter(fs, StandardCharsets.UTF_8);
        } else {
            //noinspection deprecation
            w = new OutputStreamWriter(fs, Charsets.UTF_8);
        }
        bw = new BufferedWriter(w);
        bw.write(apkVersion);
        bw.write("\n");
    } catch (IOException e) {
        WebLogger.getLogger(appName).printStackTrace(e);
    } finally {
        if (bw != null) {
            try {
                bw.flush();
                bw.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        }
        if (w != null) {
            try {
                w.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        }
        if (fs != null) {
            try {
                fs.close();
            } catch (IOException e) {
                WebLogger.getLogger(appName).printStackTrace(e);
            }
        }
    }
}