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.jtschohl.androidfirewall.MainActivity.java

/**
 * Get iptables information/*from   w  ww. j  a  v a2 s  . co  m*/
 */

private void getIptablesInfo() {
    final Context ctx = getApplicationContext();
    File sdCard = Environment.getExternalStorageDirectory();
    File dir = new File(sdCard.getAbsolutePath() + "/af_error_reports/");
    String filename = "iptables.txt";
    File file = new File(dir, filename);
    FileOutputStream fout = null;
    OutputStreamWriter output = null;
    String iptables = Api.showIptablesRules(ctx);

    try {
        for (String str : iptables.split("\r\n")) {
            fout = new FileOutputStream(file);
            output = new OutputStreamWriter(fout);
            output.write(str, 0, str.length());
        }
    } catch (IOException e) {
        Log.e(TAG, "File write failed: " + e.toString());
    } finally {
        try {
            if (output != null) {
                output.close();
                Log.d(TAG, "OUTPUT Closed");
            }
            if (fout != null) {
                fout.close();
                Log.d(TAG, "FOUT Closed");
                getLogcatInfo();
            }
        } catch (IOException e) {
            Log.e(TAG, String.format("File close failed: %s", e.toString()));
        }
    }
}

From source file:com.smartmarmot.dbforbix.config.Config.java

/**
 * Send request to Zabbix Server:/*from  w  w  w .j  a  va  2 s  .  c  o  m*/
 * @param host - Zabbix Server
 * @param port - Zabbix Server Port
 * @param json - body of request in json format
 * @return - body of response in json format
 */
public String requestZabbix(String host, int port, String json) {
    byte[] response = new byte[2048];
    Socket zabbix = null;
    OutputStreamWriter out = null;
    InputStream in = null;
    byte[] data = null;
    String resp = new String();

    try {
        zabbix = new Socket();
        //TODO socket timeout has to be read from config file
        zabbix.setSoTimeout(30000);

        zabbix.connect(new InetSocketAddress(host, port));
        OutputStream os = zabbix.getOutputStream();

        data = getRequestToZabbixServer(json);

        //send request
        os.write(data);
        os.flush();

        //read response
        in = zabbix.getInputStream();

        //convert response to string (expecting json)
        int pos1 = 13;
        int bRead = 0;
        while (true) {
            bRead = in.read(response);
            //LOG.debug("read="+read+"\nresponse="+new String(response));
            if (bRead <= 0)
                break;
            //remove binary header
            resp += new String(Arrays.copyOfRange(response, pos1, bRead));
            pos1 = 0;
        }
        //LOG.debug("requestZabbix(): resp: "+ resp);
        //resp=resp.substring(13);//remove binary header
        if (resp.isEmpty())
            throw new ZBXBadResponseException("Zabbix Server (" + host + ":" + port
                    + ") has returned empty response for request:\n" + json);

    } catch (ZBXBadResponseException respEx) {
        LOG.error(respEx.getLocalizedMessage());
    } catch (Exception ex) {
        LOG.error("Error getting data from Zabbix server (" + host + ":" + port + "): " + ex.getMessage());
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException e) {
            }
        if (out != null)
            try {
                out.close();
            } catch (IOException e) {
            }
        if (zabbix != null)
            try {
                zabbix.close();
            } catch (IOException e) {
            }
    }

    return resp;
}

From source file:io.mapzone.arena.share.ShareInfoServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {//from ww  w .  ja  v  a  2s.  c om
        // log.info( "QueryString: " + req.getQueryString() );
        // Enumeration<String> headerNames = req.getHeaderNames();
        // while (headerNames.hasMoreElements()) {
        // String header = headerNames.nextElement();
        // log.info( "HEADER '" + header + "': '" + req.getHeader( header ) + "'"
        // );
        // }

        if (req.getParameterMap().isEmpty() || StringUtils.isBlank(req.getParameter(PARAMETER_LAYERS))
                || StringUtils.isBlank(req.getParameter(PARAMETER_BBOX))) {
            resp.sendError(400, "No parameters found! Please specify at least '" + PARAMETER_LAYERS + "' and '"
                    + PARAMETER_BBOX + "'.");
            return;
        }

        final String layers = req.getParameter(PARAMETER_LAYERS);
        final String bbox = req.getParameter(PARAMETER_BBOX);
        final String authToken = req.getParameter(PARAMETER_AUTHTOKEN);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("text/html;charset=utf-8");

        final String projectName = ArenaConfig.getAppTitle();
        // FIXME add the project description here
        final String description = ArenaConfig.getAppTitle();
        final String arenaUrl = ArenaPlugin.instance().config().getProxyUrl() + ArenaPlugin.ALIAS;
        final StringBuilder imageUrl = new StringBuilder(ArenaPlugin.instance().config().getProxyUrl());
        imageUrl.append(GeoServerStarter.ALIAS);
        imageUrl.append(
                "?SERVICE=WMS&VERSION=1.3.0&REQUEST=GetMap&FORMAT=image%2Fpng&CRS=EPSG%3A3857&STYLES=&WIDTH=1200&HEIGHT=630");
        imageUrl.append("&LAYERS=").append(URLEncoder.encode(layers, "utf-8"));
        imageUrl.append("&BBOX=").append(URLEncoder.encode(bbox, "utf-8"));
        if (!StringUtils.isBlank(authToken)) {
            imageUrl.append("&authToken=").append(URLEncoder.encode(authToken, "utf-8"));
        }

        //            log.info( "IMGURL" + imageUrl.toString() );
        // convert addresses to result json
        OutputStreamWriter writer = new OutputStreamWriter(resp.getOutputStream());
        writer.write("<html>\n");
        writer.write(" <head>\n");
        writer.write("  <title>mapzone - " + projectName + "</title>\n");
        writer.write("  <meta name='author' content='mapzone' />\n");
        writer.write("  <meta name='description' content='" + description + "' />\n");
        writer.write(
                "  <meta name='keywords' content='location, geo, web, osm, map, maps, styling, wms, csv, xls, georeference, geofence, geocode' />\n");
        writer.write("  <meta name='robots' content='index,follow' />\n");
        writer.write("  <meta name='audience' content='all' />\n");
        // writer.write( " <meta name='revisit-after' content='5 days' />\n");
        // facebook/opengraph
        writer.write("  <meta property='og:locality' content='Leipzig'/>\n");
        writer.write("  <meta property='og:country-name' content='Germany'/>\n");
        writer.write("  <meta property='og:latitude' content='51.32794'/>\n");
        writer.write("  <meta property='og:longitude' content='12.33126'/>\n");
        writer.write("  <meta property='og:image:url' content='" + imageUrl.toString() + "' />\n");
        writer.write("  <meta property='og:image:type' content='image/png' />\n");
        writer.write("  <meta property='og:image:width' content='1200' />\n");
        writer.write("  <meta property='og:image:height' content='630' />\n");
        writer.write("  <meta property='og:type' content='article' />\n");
        writer.write("  <meta property='og:site_name' content='mapzone - " + projectName + "' />\n");
        // wird grad nicht von Facebook untersttzt
        // writer.write( " <meta property='fb:app_id' content='1754931524765083'
        // />\n");
        // writer.write( " <meta property='fb:admins' content='739545402735248'
        // />\n");
        writer.write(
                "  <meta property='article:publisher' content='https://www.facebook.com/mapzoneio-1401853630109662' />\n");
        writer.write("  <meta property='article:author' content='https://www.facebook.com/stundzig' />\n");

        // writer.write( " <meta property='og:url' content='" + arenaUrl + "'
        // />\n");

        // perform a redirect after 10ms
        writer.write("  <script type='text/javascript'>window.setTimeout(function(){window.location.href = '"
                + arenaUrl + "'; },10);</script>\n");
        writer.write(" </head>\n");
        writer.write(" <body>\n");
        // writer.write( " <iframe src='" + arenaUrl
        // + "' width='100%' height='520' frameborder='0'
        // allowfullscreen='allowfullscreen'></iframe>\n");
        writer.write(" </body>\n");
        writer.write("<head>\n");
        writer.flush();
        writer.close();

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:com.ingby.socbox.bischeck.servers.NRDPBatchServer.java

private void connectAndSend(String xml) throws ServerException {

    HttpURLConnection conn = null;
    OutputStreamWriter wr = null;

    try {//  w  ww  .j  a v a 2 s  .co  m
        LOGGER.debug("{} - Url: {}", instanceName, urlstr);
        String payload = cmd + xml;
        conn = createHTTPConnection(payload);
        wr = new OutputStreamWriter(conn.getOutputStream());
        wr.write(payload);
        wr.flush();

        /*
         * Look for status != 0 by building a DOM to parse
         * <status>0</status> <message>OK</message>
         */

        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = null;
        try {
            dBuilder = dbFactory.newDocumentBuilder();
        } catch (ParserConfigurationException e) {
            LOGGER.error("{} - Could not get a doc builder", instanceName, e);
            return;
        }

        /*
         * Getting the value for status and message tags
         */
        try (BufferedReader br = new BufferedReader(new InputStreamReader(conn.getInputStream()));) {

            StringBuilder sb = new StringBuilder();

            String line;
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }

            InputStream is = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("NRDP return string - {}", convertStreamToString(is));
                is.reset();
            }

            Document doc = null;

            doc = dBuilder.parse(is);

            doc.getDocumentElement().normalize();
            String rootNode = doc.getDocumentElement().getNodeName();
            NodeList responselist = doc.getElementsByTagName(rootNode);
            String result = (String) ((Element) responselist.item(0)).getElementsByTagName("status").item(0)
                    .getChildNodes().item(0).getNodeValue().trim();

            LOGGER.debug("NRDP return status is: {}", result);

            if (!"0".equals(result)) {
                String message = (String) ((Element) responselist.item(0)).getElementsByTagName("message")
                        .item(0).getChildNodes().item(0).getNodeValue().trim();
                LOGGER.error("{} - nrdp returned message \"{}\" for xml: {}", instanceName, message, xml);
            }
        } catch (SAXException e) {
            LOGGER.error("{} - Could not parse response xml", instanceName, e);
        }

    } catch (IOException e) {
        LOGGER.error("{} - Network error - check nrdp server and that service is started", instanceName, e);
        throw new ServerException(e);
    } finally {
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException ignore) {
            }
        }
        if (conn != null) {
            conn.disconnect();
        }
    }
}

From source file:com.jose.castsocialconnector.main.MainActivity.java

public void writeTempFile() {
    File myFile = new File(Environment.getExternalStorageDirectory(), "SocialConnContacts.xml");
    try {/*from   ww w. j  a  v  a2 s  .c o m*/
        FileOutputStream fOut = new FileOutputStream(myFile);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(
                "<?xml version=\"1.0\"?> <owners> <owner> <id>0</id> <nickname>Jose</nickname> <photo></photo> <email>jose.wt@gmail.com</email> <skype>ochoadelorenzi</skype> <instagram></instagram> </owner> </owners> <contacts> <contact> <id>0</id> <nickname>Natalia</nickname> <photo>http://www.expertoanimal.com/es/images/9/7/5/img_nombres_para_perros_originales_y_bonitos_5579_paso_1_600.jpg</photo> <email>jose.wt@gmail.com</email> <skype>ochoadelorenzi</skype> <instagram></instagram> </contact> <contact> <id>1</id> <nickname>Javiera</nickname> <photo>http://www.estudiantes.info/ciencias_naturales/images/leonpadre2.jpg</photo> <email>jose.wt@gmail.com</email> <skype>nat_saintmartins</skype> <instagram></instagram> </contact> <contact> <id>2</id> <nickname>Victor</nickname> <photo>http://cdn.20m.es/img2/recortes/2012/01/10/44326-857-550.jpg</photo> <email>jose.wt@gmail.com</email> <skype>carla.sambrizzi</skype> <instagram></instagram> </contact> <contact> <id>3</id> <nickname>Luis</nickname> <photo>http://4.bp.blogspot.com/-F8VTQuaZvuQ/Vl9gw0xGV2I/AAAAAAAADT8/mNmXSbTuiXw/s1600/New-Mixed-HD-Wallpapers-Pack-50_igoryk06-43.jpg</photo> <email>juan.ochoa@ug.uchile.cl</email> <skype>juanma8a</skype> <instagram></instagram> </contact> </contacts>");
        //            myOutWriter.append("<?xml version=\"1.0\"?> <owners> <owner> <id>0</id> <nickname>Jose</nickname> <photo></photo> <email>jose.wt@gmail.com</email> <skype>ochoadelorenzi</skype> <instagram></instagram> </owner> </owners> <contacts> <contact> <id>1</id> <nickname>Natalia</nickname> <photo> http://a5.mzstatic.com/us/r30/Purple5/v4/5a/2e/e9/5a2ee9b3-8f0e-4f8b-4043-dd3e3ea29766/icon128-2x.png </photo> <email>nacha.sanmartin@gmail.com</email> <skype>nat_saintmartins</skype> <instagram>nat_saintmartins</instagram> </contact> </contacts>");
        //            myOutWriter.append("<?xml version=\"1.0\"?> <owners> <owner> <id>0</id> <nickname>Jose</nickname> <photo></photo> <email>jose.wt@gmail.com</email> <skype>ochoadelorenzi</skype> <instagram></instagram> </owner> </owners> <contacts><contact> <id>0</id> <nickname>Jose</nickname> <photo> http://comicsalliance.com/files/2012/07/asmsdccpanelmain-1342466154.jpg </photo> <email>jose.wt@gmail.com</email> <skype>ochoadelorenzi</skype> <instagram></instagram> </contact>  <contact> <id>1</id> <nickname>Natalia</nickname> <photo> http://a5.mzstatic.com/us/r30/Purple5/v4/5a/2e/e9/5a2ee9b3-8f0e-4f8b-4043-dd3e3ea29766/icon128-2x.png </photo> <email>nacha.sanmartin@gmail.com</email> <skype>nat_saintmartins</skype> <instagram>nat_saintmartins</instagram> </contact> </contacts>");
        myOutWriter.close();
        fOut.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:org.fcrepo.server.access.FedoraAccessServlet.java

public void getObjectProfile(Context context, String PID, Date asOfDateTime, boolean xml,
        HttpServletRequest request, HttpServletResponse response) throws ServerException {

    OutputStreamWriter out = null;
    Date versDateTime = asOfDateTime;
    ObjectProfile objProfile = null;//from www . j  a v a2 s .c om
    PipedWriter pw = null;
    PipedReader pr = null;
    try {
        pw = new PipedWriter();
        pr = new PipedReader(pw);
        objProfile = m_access.getObjectProfile(context, PID, asOfDateTime);
        if (objProfile != null) {
            // Object Profile found.
            // Serialize the ObjectProfile object into XML
            new ProfileSerializerThread(context, PID, objProfile, versDateTime, pw).start();
            if (xml) {
                // Return results as raw XML
                response.setContentType(CONTENT_TYPE_XML);

                // Insures stream read from PipedReader correctly translates
                // utf-8
                // encoded characters to OutputStreamWriter.
                out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
                char[] buf = new char[BUF];
                int len = 0;
                while ((len = pr.read(buf, 0, BUF)) != -1) {
                    out.write(buf, 0, len);
                }
                out.flush();
            } else {
                // Transform results into an html table
                response.setContentType(CONTENT_TYPE_HTML);
                out = new OutputStreamWriter(response.getOutputStream(), "UTF-8");
                File xslFile = new File(m_server.getHomeDir(), "access/viewObjectProfile.xslt");
                Templates template = XmlTransformUtility.getTemplates(xslFile);
                Transformer transformer = template.newTransformer();
                transformer.setParameter("fedora", context.getEnvironmentValue(FEDORA_APP_CONTEXT_NAME));
                transformer.transform(new StreamSource(pr), new StreamResult(out));
            }
            out.flush();

        } else {
            throw new GeneralException("No object profile returned");
        }
    } catch (ServerException e) {
        throw e;
    } catch (Throwable th) {
        String message = "Error getting object profile";
        logger.error(message, th);
        throw new GeneralException(message, th);
    } finally {
        try {
            if (pr != null) {
                pr.close();
            }
            if (out != null) {
                out.close();
            }
        } catch (Throwable th) {
            String message = "Error closing output";
            logger.error(message, th);
            throw new StreamIOException(message);
        }
    }
}

From source file:org.jmxtrans.embedded.output.CopperEggWriter.java

public String Send_Commmand(String command, String msgtype, String payload, Integer ExpectInt) {
    HttpURLConnection urlConnection = null;
    URL myurl = null;/*from   w w w . j a va 2  s  . c o m*/
    OutputStreamWriter wr = null;
    int responseCode = 0;
    String id = null;
    int error = 0;

    try {
        myurl = new URL(url_str + command);
        urlConnection = (HttpURLConnection) myurl.openConnection();
        urlConnection.setRequestMethod(msgtype);
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        urlConnection.setReadTimeout(coppereggApiTimeoutInMillis);
        urlConnection.addRequestProperty("User-Agent", "Mozilla/4.76");
        urlConnection.setRequestProperty("content-type", "application/json; charset=utf-8");
        urlConnection.setRequestProperty("Authorization", "Basic " + basicAuthentication);

        wr = new OutputStreamWriter(urlConnection.getOutputStream(), "UTF-8");
        wr.write(payload);
        wr.flush();

        responseCode = urlConnection.getResponseCode();
        if (responseCode != 200) {
            logger.warn(
                    "Send Command: Response code " + responseCode + " url is " + myurl + " command " + msgtype);
            error = 1;
        }
    } catch (Exception e) {
        exceptionCounter.incrementAndGet();
        logger.warn("Exception in Send Command: url is " + myurl + " command " + msgtype + "; " + e);
        error = 1;
    } finally {
        if (urlConnection != null) {
            try {
                if (error > 0) {
                    InputStream err = urlConnection.getErrorStream();
                    String errString = convertStreamToString(err);
                    logger.warn("Reported error : " + errString);
                    IoUtils2.closeQuietly(err);
                } else {
                    InputStream in = urlConnection.getInputStream();
                    String theString = convertStreamToString(in);
                    id = jparse(theString, ExpectInt);
                    IoUtils2.closeQuietly(in);
                }
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Exception in Send Command : flushing http connection " + e);
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                exceptionCounter.incrementAndGet();
                logger.warn("Exception in Send Command: closing OutputWriter " + e);
            }
        }
    }
    return (id);
}

From source file:com.MainFiles.Functions.java

public String getCustomerDetails(String strAccountNumber) throws IOException {
    String[] strCustomerNameArray;
    String strCustomerName = "";
    String fname = "";
    String mname = "";
    String lname = "";
    try {//from  w  w w. j av a2 s. c o m
        URL url = new URL(CUSTOMER_DETAILS_URL);
        Map<String, String> params = new LinkedHashMap<>();

        params.put("username", CUSTOMER_DETAILS_USERNAME);
        params.put("password", CUSTOMER_DETAILS_PASSWORD);
        params.put("source", CUSTOMER_DETAILS_SOURCE_ID);
        params.put("account", strAccountNumber);

        StringBuilder postData = new StringBuilder();
        for (Map.Entry<String, String> param : params.entrySet()) {
            if (postData.length() != 0) {
                postData.append('&');
            }
            postData.append(URLEncoder.encode(param.getKey(), "UTF-8"));
            postData.append('=');
            postData.append(URLEncoder.encode(String.valueOf(param.getValue()), "UTF-8"));
        }
        String urlParameters = postData.toString();
        URLConnection conn = url.openConnection();

        conn.setDoOutput(true);

        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        writer.write(urlParameters);
        writer.flush();

        String result = "";
        String line;
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));

        while ((line = reader.readLine()) != null) {
            result += line;
        }
        writer.close();
        reader.close();

        JSONObject respobj = new JSONObject(result);
        if (respobj.has("FSTNAME") || respobj.has("MIDNAME") || respobj.has("LSTNAME")) {
            if (respobj.has("FSTNAME")) {
                fname = respobj.get("FSTNAME").toString().toUpperCase() + ' ';
            }
            if (respobj.has("MIDNAME")) {
                mname = respobj.get("MIDNAME").toString().toUpperCase() + ' ';
            }
            if (respobj.has("LSTNAME")) {
                lname = respobj.get("LSTNAME").toString().toUpperCase() + ' ';
            }
            strCustomerName = fname + mname + lname;
        } else {
            strCustomerName = "N/A";
        }

    } catch (Exception ex) {
        this.log("\nINFO : Function getCustomerDetails() " + ex.getMessage() + "\n" + this.StackTraceWriter(ex),
                "ERROR");
    }

    // System.out.println(strCustomerName);
    return strCustomerName;
}

From source file:de.interactive_instruments.ShapeChange.Target.FeatureCatalogue.FeatureCatalogue.java

/**
 * Transforms the contents of the temporary feature catalogue xml and
 * inserts it into a specific place (denoted by a placeholder) of a docx
 * template file. The result is copied into a new output file. The template
 * file is not modified./*from  w  w w.  j a v a 2  s.c o  m*/
 * 
 * @param xmlName
 *            Name of the temporary feature catalogue xml file, located in
 *            the output directory.
 * @param outfileBasename
 *            Base name of the output file, without file type ending.
 */
private void writeDOCX(String xmlName, String outfileBasename) {

    if (!OutputFormat.toLowerCase().contains("docx"))
        return;

    StatusBoard.getStatusBoard().statusChanged(STATUS_WRITE_DOCX);

    ZipHandler zipHandler = new ZipHandler();

    String docxfileName = outfileBasename + ".docx";

    try {

        // Setup directories
        File outDir = new File(outputDirectory);
        File tmpDir = new File(outDir, "tmpdocx");
        File tmpinputDir = new File(tmpDir, "input");
        File tmpoutputDir = new File(tmpDir, "output");

        // get docx template

        // create temporary file for the docx template copy
        File docxtemplate_copy = new File(tmpDir, "docxtemplatecopy.tmp");

        // populate temporary file either from remote or local URI
        if (docxTemplateFilePath.toLowerCase().startsWith("http")) {
            URL templateUrl = new URL(docxTemplateFilePath);
            FileUtils.copyURLToFile(templateUrl, docxtemplate_copy);
        } else {
            File docxtemplate = new File(docxTemplateFilePath);
            if (docxtemplate.exists()) {
                FileUtils.copyFile(docxtemplate, docxtemplate_copy);
            } else {
                result.addError(this, 19, docxtemplate.getAbsolutePath());
                return;
            }
        }

        /*
         * Unzip the docx template to tmpinputDir and tmpoutputDir The
         * contents of the tmpinputdir will be used as input for the
         * transformation. The transformation result will overwrite the
         * relevant files in the tmpoutputDir.
         */
        zipHandler.unzip(docxtemplate_copy, tmpinputDir);
        zipHandler.unzip(docxtemplate_copy, tmpoutputDir);

        /*
         * Get hold of the styles.xml file from which the transformation
         * will get relevant information. The path to this file will be used
         * as a transformation parameter.
         */
        File styleXmlFile = new File(tmpinputDir, "word/styles.xml");
        if (!styleXmlFile.canRead()) {
            result.addError(null, 301, styleXmlFile.getName(), "styles.xml");
            return;
        }

        /*
         * Get hold of the temporary feature catalog xml file. The path to
         * this file will be used as a transformation parameter.
         */
        File xmlFile = new File(outDir, xmlName);
        if (!styleXmlFile.canRead()) {
            result.addError(null, 301, styleXmlFile.getName(), xmlName);
            return;
        }

        /*
         * Get hold of the input document.xml file (internal .xml file from
         * the docxtemplate). It will be used as the source for the
         * transformation.
         */
        File indocumentxmlFile = new File(tmpinputDir, "word/document.xml");
        if (!indocumentxmlFile.canRead()) {
            result.addError(null, 301, indocumentxmlFile.getName(), "document.xml");
            return;
        }

        /*
         * Get hold of the output document.xml file. It will be used as the
         * transformation target.
         */
        File outdocumentxmlFile = new File(tmpoutputDir, "word/document.xml");
        if (!outdocumentxmlFile.canWrite()) {
            result.addError(null, 307, outdocumentxmlFile.getName(), "document.xml");
            return;
        }

        /*
         * Prepare the transformation.
         */
        transformationParameters.put("styleXmlPath", styleXmlFile.toURI().toString());
        transformationParameters.put("catalogXmlPath", xmlFile.toURI().toString());
        transformationParameters.put("DOCX_PLACEHOLDER", DOCX_PLACEHOLDER);

        /*
         * Execute the transformation.
         */
        this.xsltWrite(indocumentxmlFile, xsldocxfileName, outdocumentxmlFile);

        if (includeDiagrams) {
            /*
             * === Process image information ===
             */

            /*
             * 1. Copy content of temporary images folder to output folder
             */
            File mediaDir = new File(tmpoutputDir, "word/media");
            FileUtils.copyDirectoryToDirectory(options.imageTmpDir(), mediaDir);

            /*
             * 2. Create image information file. The path to this file will
             * be used as a transformation parameter.
             */

            Document imgInfoDoc = createDocument();

            imgInfoDoc.appendChild(imgInfoDoc.createComment("Temporary file containing image metadata"));

            Element imgInfoRoot = imgInfoDoc.createElement("images");
            imgInfoDoc.appendChild(imgInfoRoot);

            addAttribute(imgInfoDoc, imgInfoRoot, "xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

            List<ImageMetadata> imageList = new ArrayList<ImageMetadata>(imageSet);
            Collections.sort(imageList, new Comparator<ImageMetadata>() {

                @Override
                public int compare(ImageMetadata o1, ImageMetadata o2) {
                    return o1.getId().compareTo(o2.getId());
                }
            });

            for (ImageMetadata im : imageList) {

                Element e1 = imgInfoDoc.createElement("image");

                addAttribute(imgInfoDoc, e1, "id", im.getId());
                addAttribute(imgInfoDoc, e1, "relPath", im.getRelPathToFile());

                imgInfoRoot.appendChild(e1);
            }

            Properties outputFormat = OutputPropertiesFactory.getDefaultMethodProperties("xml");
            outputFormat.setProperty("indent", "yes");
            outputFormat.setProperty("{http://xml.apache.org/xalan}indent-amount", "2");
            if (encoding != null)
                outputFormat.setProperty("encoding", encoding);

            File relsFile = new File(tmpDir, "docx_relationships.tmp.xml");

            try {

                OutputStream fout = new FileOutputStream(relsFile);
                OutputStream bout = new BufferedOutputStream(fout);
                OutputStreamWriter outputXML = new OutputStreamWriter(bout,
                        outputFormat.getProperty("encoding"));

                Serializer serializer = SerializerFactory.getSerializer(outputFormat);
                serializer.setWriter(outputXML);
                serializer.asDOMSerializer().serialize(imgInfoDoc);
                outputXML.close();
            } catch (Exception e) {
                String m = e.getMessage();
                if (m != null) {
                    result.addError(m);
                }
                e.printStackTrace(System.err);
            }

            /*
             * 3. Apply transformation to relationships file
             */

            /*
             * Get hold of the input relationships file (internal file from
             * the docx template). It will be used as the source for the
             * transformation.
             */

            File inRelsXmlFile = new File(tmpinputDir, "word/_rels/document.xml.rels");
            if (!inRelsXmlFile.canRead()) {
                result.addError(null, 301, inRelsXmlFile.getName(), "document.xml.rels");
                return;
            }

            /*
             * Get hold of the output relationships file. It will be used as
             * the transformation target.
             */
            File outRelsXmlFile = new File(tmpoutputDir, "word/_rels/document.xml.rels");
            if (!outRelsXmlFile.canWrite()) {
                result.addError(null, 307, outRelsXmlFile.getName(), "document.xml.rels");
                return;
            }

            /*
             * Prepare the transformation.
             */
            transformationParameters.put("imageInfoXmlPath", relsFile.toURI().toString());

            /*
             * Execute the transformation.
             */
            this.xsltWrite(inRelsXmlFile, xsldocxrelsfileName, outRelsXmlFile);
        }

        /*
         * === Create the docx result file ===
         */

        // Get hold of the output docx file (it will be overwritten or
        // initialized).
        File outFile = new File(outDir, docxfileName);

        /*
         * Zip the temporary output directory and copy it to the output docx
         * file.
         */
        zipHandler.zip(tmpoutputDir, outFile);

        /*
         * === Delete the temporary directory ===
         */

        try {
            FileUtils.deleteDirectory(tmpDir);
        } catch (IOException e) {
            result.addWarning(this, 20, e.getMessage());
        }

        result.addResult(getTargetID(), outputDirectory, docxfileName, null);

    } catch (Exception e) {
        String m = e.getMessage();
        if (m != null) {
            result.addError(m);
        }
        e.printStackTrace(System.err);
    }
}

From source file:com.mocap.MocapFragment.java

public void SaveOBJ(Context context, MyGLSurfaceView glview) {
    Log.i(TAG, "DIR: ");
    float sVertices[] = glview.getsVertices();
    FileOutputStream fOut = null;
    OutputStreamWriter osw = null;

    File mFile;// w w w. j a v  a2  s. c o m

    if (Environment.DIRECTORY_PICTURES != null) {
        try {
            mFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    "mocap.obj");

            Log.i(TAG, "Long Vertices: " + sVertices.length);
            fOut = new FileOutputStream(mFile);
            osw = new OutputStreamWriter(fOut);
            osw.write("# *.obj file (Generate by Mocap 3D)\n");
            osw.flush();

            for (int i = 0; i < sVertices.length - 4; i = i + 3) {

                try {
                    String data = "v " + Float.toString(sVertices[i]) + " " + Float.toString(sVertices[i + 1])
                            + " " + Float.toString(sVertices[i + 2]) + "\n";
                    Log.i(TAG, i + ": " + data);
                    osw.write(data);
                    osw.flush();

                } catch (Exception e) {
                    Toast.makeText(context, "erreur d'criture: " + e, Toast.LENGTH_SHORT).show();
                    Log.i(TAG, "Erreur: " + e);
                }

            }

            osw.write("# lignes:\n");
            osw.write("l ");
            osw.flush();
            ;
            for (int i = 1; i < (-1 + sVertices.length / 3); i++) {
                osw.write(i + " ");
                osw.flush();
            }
            //popup surgissant pour le rsultat
            Toast.makeText(getActivity(), "Save : " + Environment.DIRECTORY_PICTURES + "/mocap.obj ",
                    Toast.LENGTH_SHORT).show();

            //lancement d'un explorateur de fichiers vers le fichier crer
            //systeme des intend
            try {
                File root = new File(Environment.DIRECTORY_PICTURES);
                Uri uri = Uri.fromFile(mFile);

                Intent intent = new Intent();
                intent.setAction(Intent.ACTION_GET_CONTENT);
                intent.setData(uri);

                // Verify that the intent will resolve to an activity
                if (intent.resolveActivity(getActivity().getPackageManager()) != null) {
                    Log.i(TAG, "intent pk: ");
                    getActivity().startActivityForResult(intent, 1);
                }
            } catch (Exception e) {
                Log.i(TAG, "Erreur intent: " + e);
            }
        } catch (Exception e) {
            Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
        } finally {
            try {
                osw.close();
                fOut.close();
            } catch (IOException e) {
                Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();
            }

        }

    } else {
        Toast.makeText(context, "Pas de carte ext", Toast.LENGTH_SHORT).show();
    }
}