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:de.baumann.hhsmoodle.activities.Activity_todo.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    PreferenceManager.setDefaultValues(this, R.xml.user_settings, false);
    sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
    toDo_title = sharedPref.getString("toDo_title", "");
    String toDo_text = sharedPref.getString("toDo_text", "");
    toDo_icon = sharedPref.getString("toDo_icon", "");
    toDo_create = sharedPref.getString("toDo_create", "");
    todo_attachment = sharedPref.getString("toDo_attachment", "");
    if (!sharedPref.getString("toDo_seqno", "").isEmpty()) {
        toDo_seqno = Integer.parseInt(sharedPref.getString("toDo_seqno", ""));
    }/*from   w  w  w .j  av a 2s  .c  o  m*/

    setContentView(R.layout.activity_todo);
    setTitle(toDo_title);

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    helper_main.onStart(Activity_todo.this);

    final ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setDisplayHomeAsUpEnabled(true);
    }

    try {
        FileOutputStream fOut = new FileOutputStream(newFile());
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(toDo_text);
        myOutWriter.close();

        fOut.flush();
        fOut.close();
    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }

    lvItems = (ListView) findViewById(R.id.lvItems);
    items = new ArrayList<>();
    readItems();
    itemsAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1, items);
    lvItems.setAdapter(itemsAdapter);
    lvItems.post(new Runnable() {
        public void run() {
            lvItems.setSelection(lvItems.getCount() - 1);
        }
    });

    setupListViewListener();

    final EditText etNewItem = (EditText) findViewById(R.id.etNewItem);
    ImageButton ib_paste = (ImageButton) findViewById(R.id.imageButtonPaste);
    final ImageButton ib_not = (ImageButton) findViewById(R.id.imageButtonNot);

    switch (todo_attachment) {
    case "true":
        ib_not.setImageResource(R.drawable.alert_circle);
        break;
    case "":
        ib_not.setImageResource(R.drawable.alert_circle_red);
        break;
    }

    ib_not.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            switch (todo_attachment) {
            case "true":
                ib_not.setImageResource(R.drawable.alert_circle_red);
                sharedPref.edit().putString("toDo_attachment", "").apply();
                todo_attachment = sharedPref.getString("toDo_attachment", "");
                break;
            case "":
                ib_not.setImageResource(R.drawable.alert_circle);
                sharedPref.edit().putString("toDo_attachment", "true").apply();
                todo_attachment = sharedPref.getString("toDo_attachment", "");
                break;
            }

        }
    });

    ib_paste.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            final CharSequence[] options = { getString(R.string.paste_date), getString(R.string.paste_time) };
            new android.app.AlertDialog.Builder(Activity_todo.this)
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.dismiss();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.paste_date))) {
                                Date date = new Date();
                                SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd",
                                        Locale.getDefault());
                                String dateNow = format.format(date);
                                etNewItem.getText().insert(etNewItem.getSelectionStart(), dateNow);
                            }

                            if (options[item].equals(getString(R.string.paste_time))) {
                                Date date = new Date();
                                SimpleDateFormat format = new SimpleDateFormat("HH:mm", Locale.getDefault());
                                String timeNow = format.format(date);
                                etNewItem.getText().insert(etNewItem.getSelectionStart(), timeNow);
                            }
                        }
                    }).show();
        }
    });

    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            String itemText = etNewItem.getText().toString();

            if (itemText.isEmpty()) {
                Snackbar.make(lvItems, R.string.todo_enter, Snackbar.LENGTH_LONG).show();
            } else {
                itemsAdapter.add(itemText);
                etNewItem.setText("");
                writeItems();
                lvItems.post(new Runnable() {
                    public void run() {
                        lvItems.setSelection(lvItems.getCount() - 1);
                    }
                });
            }
        }
    });
}

From source file:io.mapzone.arena.geocode.GeocodeServlet.java

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    try {/*from w  w w.  jav  a2s. co m*/

        EventManager.instance().publish(new ServletRequestEvent(getServletContext(), req));

        if (req.getParameterMap().isEmpty()) {
            resp.sendError(400, "No parameters found! Please specify at least 'text'.");
            return;
        }

        GeocodeQuery query = extractQuery(req);

        // perform search
        List<Address> addresses = service.geocode(query);

        resp.setStatus(HttpStatus.SC_OK);
        resp.setContentType("application/json;charset=utf-8");
        handleCors(req, resp);

        // convert addresses to result json
        OutputStreamWriter outputStreamWriter = new OutputStreamWriter(resp.getOutputStream());
        JSONWriter writer = new JSONWriter(outputStreamWriter);
        writer.object();
        writer.key("results");
        writer.array();
        for (Address address : addresses) {
            writer.value(toJSON(address));
        }
        writer.endArray();
        writer.endObject();
        outputStreamWriter.flush();
        outputStreamWriter.close();
    } catch (Exception e) {
        e.printStackTrace();
        resp.sendError(HttpStatus.SC_INTERNAL_SERVER_ERROR, e.getMessage());
    }
}

From source file:com.cubusmail.gwtui.server.services.ShowMessageSourceServlet.java

@Override
public void service(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

    try {/*from   w ww.j  av a 2  s.c o m*/
        String messageId = request.getParameter("messageId");
        if (messageId != null) {
            IMailbox mailbox = SessionManager.get().getMailbox();
            Message msg = mailbox.getCurrentFolder().getMessageById(Long.parseLong(messageId));

            ContentType contentType = new ContentType("text/plain");
            response.setContentType(contentType.getBaseType());
            response.setHeader("expires", "0");
            String charset = null;
            if (msg.getContentType() != null) {
                try {
                    charset = new ContentType(msg.getContentType()).getParameter("charset");
                } catch (Throwable e) {
                    // should never happen
                }
            }
            if (null == charset || charset.equalsIgnoreCase(CubusConstants.US_ASCII)) {
                charset = CubusConstants.DEFAULT_CHARSET;
            }

            OutputStream outputStream = response.getOutputStream();

            // writing the header
            String header = generateHeader(msg);
            outputStream.write(header.getBytes(), 0, header.length());

            BufferedInputStream bufInputStream = new BufferedInputStream(msg.getInputStream());

            InputStreamReader reader = null;

            try {
                reader = new InputStreamReader(bufInputStream, charset);
            } catch (UnsupportedEncodingException e) {
                logger.error(e.getMessage(), e);
                reader = new InputStreamReader(bufInputStream);
            }

            OutputStreamWriter writer = new OutputStreamWriter(outputStream);
            char[] inBuf = new char[1024];
            int len = 0;
            try {
                while ((len = reader.read(inBuf)) > 0) {
                    writer.write(inBuf, 0, len);
                }
            } catch (Throwable e) {
                logger.warn("Download canceled!");
            }

            writer.flush();
            writer.close();
            outputStream.flush();
            outputStream.close();
        }

    } catch (Exception e) {
        logger.error(e.getMessage(), e);
    }
}

From source file:com.amastigote.xdu.query.module.EduSystem.java

@Override
public boolean login(String username, String password) throws IOException {
    preLogin();/*from  www .  j av a 2  s.  c  om*/
    URL url = new URL(LOGIN_HOST + LOGIN_SUFFIX);
    HttpURLConnection httpURLConnection_a = (HttpURLConnection) url.openConnection();
    httpURLConnection_a.setRequestMethod("POST");
    httpURLConnection_a.setUseCaches(false);
    httpURLConnection_a.setInstanceFollowRedirects(false);
    httpURLConnection_a.setDoOutput(true);

    String OUTPUT_DATA = "username=";
    OUTPUT_DATA += username;
    OUTPUT_DATA += "&password=";
    OUTPUT_DATA += password;
    OUTPUT_DATA += "&submit=";
    OUTPUT_DATA += "&lt=" + LOGIN_PARAM_lt;
    OUTPUT_DATA += "&execution=" + LOGIN_PARAM_execution;
    OUTPUT_DATA += "&_eventId=" + LOGIN_PARAM__eventId;
    OUTPUT_DATA += "&rmShown=" + LOGIN_PARAM_rmShown;

    httpURLConnection_a.setRequestProperty("Cookie",
            "route=" + ROUTE
                    + "; org.springframework.web.servlet.i18n.CookieLocaleResolver.LOCALE=zh_CN; JSESSIONID="
                    + LOGIN_JSESSIONID + "; BIGipServeridsnew.xidian.edu.cn=" + BIGIP_SERVER_IDS_NEW + ";");

    httpURLConnection_a.connect();
    OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection_a.getOutputStream(),
            "UTF-8");
    outputStreamWriter.write(OUTPUT_DATA);
    outputStreamWriter.flush();
    outputStreamWriter.close();

    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(httpURLConnection_a.getInputStream()));
    String html = "";
    String temp;

    while ((temp = bufferedReader.readLine()) != null) {
        html += temp;
    }

    Document document = Jsoup.parse(html);
    Elements elements = document.select("a");
    if (elements.size() == 0)
        return false;
    String SYS_LOCATION = elements.get(0).attr("href");

    URL sys_location = new URL(SYS_LOCATION);
    HttpURLConnection httpUrlConnection_b = (HttpURLConnection) sys_location.openConnection();
    httpUrlConnection_b.setInstanceFollowRedirects(false);
    httpUrlConnection_b.connect();
    List<String> cookies_to_set = httpUrlConnection_b.getHeaderFields().get("Set-Cookie");
    for (String e : cookies_to_set)
        if (e.contains("JSESSIONID="))
            SYS_JSESSIONID = e.substring(11, e.indexOf(";"));
    httpURLConnection_a.disconnect();
    httpUrlConnection_b.disconnect();
    return checkIsLogin(username);
}

From source file:org.apache.karaf.cave.server.storage.CaveRepositoryImpl.java

/**
 * Generate the repository.xml with the artifact at the given URL.
 *
 * @throws Exception in case of repository.xml update failure.
 *///from w w w .ja  v a 2s  . c om
private void generateRepositoryXml() throws Exception {
    File repositoryXml = this.getRepositoryXmlFile();
    OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(repositoryXml));
    new DataModelHelperImpl().writeRepository(obrRepository, writer);
    writer.flush();
    writer.close();
}

From source file:com.sfs.jbtimporter.JBTImporter.java

/**
 * Transform the issues to the new XML format.
 *
 * @param jbt the jbt processor/*www  .  j a va  2 s. com*/
 * @param issues the issues
 */
private static void transformIssues(final JBTProcessor jbt, final List<JBTIssue> issues) {

    final File xsltFile = new File(jbt.getXsltFileName());

    final Source xsltSource = new StreamSource(xsltFile);
    final TransformerFactory transFact = TransformerFactory.newInstance();
    Transformer trans = null;

    try {
        final Templates cachedXSLT = transFact.newTemplates(xsltSource);
        trans = cachedXSLT.newTransformer();
    } catch (TransformerConfigurationException tce) {
        System.out.println("ERROR configuring XSLT engine: " + tce.getMessage());
    }
    // Enable indenting and UTF8 encoding
    trans.setOutputProperty(OutputKeys.INDENT, "yes");
    trans.setOutputProperty(OutputKeys.ENCODING, "UTF-8");

    if (trans != null) {
        for (JBTIssue issue : issues) {
            System.out.println("Processing Issue ID: " + issue.getId());
            System.out.println("Filename: " + issue.getFullFileName());

            // Read the XML file
            final File xmlFile = new File(issue.getFullFileName());
            final File tempFile = new File(issue.getFullFileName() + ".tmp");
            final File originalFile = new File(issue.getFullFileName() + ".old");

            Source xmlSource = null;
            if (originalFile.exists()) {
                // The original file exists, use that as the XML source
                xmlSource = new StreamSource(originalFile);
            } else {
                // No backup exists, use the .xml file.
                xmlSource = new StreamSource(xmlFile);
            }

            // Transform the XML file
            try {
                trans.transform(xmlSource, new StreamResult(tempFile));

                if (originalFile.exists()) {
                    // Delete the .xml file as it needs to be replaced
                    xmlFile.delete();
                } else {
                    // Rename the existing file with the .old extension
                    xmlFile.renameTo(originalFile);
                }
            } catch (TransformerException te) {
                System.out.println("ERROR transforming XML: " + te.getMessage());
            }

            // Read the xmlFile and convert the special characters

            OutputStreamWriter out = null;
            try {

                final BufferedReader in = new BufferedReader(
                        new InputStreamReader(new FileInputStream(tempFile), "UTF8"));

                out = new OutputStreamWriter(new FileOutputStream(xmlFile), "UTF-8");

                int ch = -1;
                ch = in.read();
                while (ch != -1) {
                    final char c = (char) ch;

                    if (jbt.getSpecialCharacterMap().containsKey(c)) {
                        // System.out.println("Replacing character: " + c 
                        //        + ", " + jbt.getSpecialCharacterMap().get(c));
                        out.write(jbt.getSpecialCharacterMap().get(c));
                    } else {
                        out.write(c);
                    }
                    ch = in.read();
                }
            } catch (IOException ie) {
                System.out.println("ERROR converting special characters: " + ie.getMessage());
            } finally {
                try {
                    if (out != null) {
                        out.close();
                    }
                } catch (IOException ie) {
                    System.out.println("ERROR closing the XML file: " + ie.getMessage());
                }
                // Delete the temporary file
                tempFile.delete();
            }

            System.out.println("-------------------------------------");
        }
    }
}

From source file:com.mbientlab.metawear.app.CustomFragment.java

public void writeToFile(String data, String name) {
    File path = new File(Environment.getExternalStorageDirectory().getPath() + "/SensorFusedData/");

    // Make sure the path directory exists.
    if (!path.exists()) {
        // Make it, if it doesn't exit
        path.mkdirs();//w  w  w. j av a 2  s. c  o m
    }

    final File file = new File(path, name);

    // Save your stream, don't forget to flush() it before closing it.

    try {
        file.createNewFile();
        FileOutputStream fOut = new FileOutputStream(file);
        OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
        myOutWriter.append(data);

        myOutWriter.close();

        fOut.flush();
        fOut.close();
        showLog("File wrote successfully - " + file.getAbsolutePath());
        Toast.makeText(getActivity(), "File wrote successfully - " + file.getAbsolutePath(), Toast.LENGTH_SHORT)
                .show();
    } catch (IOException e) {
        Log.e("Exception", "File write failed: " + e.toString());
    }
}

From source file:org.apache.uima.ruta.resource.TreeWordList.java

private void writeCompressedTWLFile(TextNode root, String path, String encoding) throws IOException {
    FileOutputStream fos = new FileOutputStream(path);
    BufferedOutputStream bos = new BufferedOutputStream(fos);
    ZipOutputStream zos = new ZipOutputStream(bos);
    OutputStreamWriter writer = new OutputStreamWriter(zos, encoding);
    zos.putNextEntry(new ZipEntry(path));
    writeTWLFile(root, writer);/*  ww w .j a va 2s. com*/
    writer.flush();
    zos.closeEntry();
    writer.close();
}

From source file:com.tqlab.plugin.mybatis.maven.MyBatisGeneratorMojo.java

private MybatisExecutorCallback createMybatisExecutorCallback() {

    return new MybatisExecutorCallback() {

        private List<String> jdbcConfig = new ArrayList<String>();
        private List<String> springConfig = new ArrayList<String>();
        private List<String> osgiConfig = new ArrayList<String>();

        @Override//from w w w.j av a2  s.  c  om
        public void onWriteJdbcConfig(String str) {
            jdbcConfig.add(str);
        }

        @Override
        public void onWriteSpringConfig(String str) {
            springConfig.add(str);
        }

        @Override
        public void onWriteOsgiConfig(String str) {
            osgiConfig.add(str);
        }

        @Override
        public void onFinsh(boolean overwrite) throws IOException {

            if (jdbcConfig.size() > 0) {
                this.write(outputDirectory.getAbsolutePath() + File.separator + "src/main/resources/",
                        "jdbc.properties", "jdbc.template", "${jdbc}", getConfigStr(jdbcConfig), true);
            }

            if (springConfig.size() > 0) {
                this.write(
                        outputDirectory.getAbsolutePath() + File.separator
                                + "src/main/resources/META-INF/spring/",
                        "common-db-mapper.xml", "common-db-mapper.template", "${beans}",
                        getConfigStr(springConfig), overwrite);
            }

            if (osgiConfig.size() > 0) {
                this.write(
                        outputDirectory.getAbsolutePath() + File.separator
                                + "src/main/resources/META-INF/spring/",
                        "common-dal-osgi.xml", "common-dal-osgi.template", "${osgi}", getConfigStr(osgiConfig),
                        overwrite);
            }

        }

        @Override
        public String getJdbcConfigPostfix() {
            return jdbcConfig.size() == 0 ? "" : "." + jdbcConfig.size();
        }

        @Override
        public String getStringConfigPostfix() {
            return springConfig.size() == 0 ? "" : "." + springConfig.size();
        }

        @Override
        public String getOsgiConfigPostfix() {
            return osgiConfig.size() == 0 ? "" : "." + osgiConfig.size();
        }

        private String getConfigStr(List<String> list) {
            if (null == list) {
                return "";
            }
            String str = "";
            for (String s : list) {
                str += s + "\r\n";
            }
            return str;
        }

        private void write(String outDir, String fileName, String templateName, String replaceStr,
                String repalceValue, boolean overwrite) throws IOException {

            InputStream is = this.getClass().getResourceAsStream("/" + templateName);
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            String line = null;
            StringBuffer buf = new StringBuffer();
            while (null != (line = br.readLine())) {
                buf.append(line);
                buf.append(Constants.LINE_SEPARATOR);
            }

            String result = buf.toString().replace(replaceStr, repalceValue);
            File dir = new File(outDir);
            if (!dir.exists()) {
                dir.mkdirs();
            }

            String outputPath = dir + File.separator + fileName;

            if (!overwrite) {
                File file = new File(outputPath);
                while (file.exists()) {
                    String name = getFileName(file.getName());
                    outputPath = dir + File.separator + name;
                    file = new File(outputPath);
                }
            }

            this.write(outputPath, result);
        }

        private void write(String filePath, String str) throws IOException {
            File file = new File(filePath);

            if (file.getParentFile() != null && !file.getParentFile().exists()) {
                file.getParentFile().mkdirs();
            }

            OutputStreamWriter writer = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
            writer.write(str);
            writer.flush();
            writer.close();

            MyBatisGeneratorMojo.this.getLog().info(str);

        }

        private String getFileName(String name) {
            int index = name.lastIndexOf(".");
            if (index > 0) {
                String temp1 = name.substring(0, index);
                String temp2 = name.substring(index + 1);
                try {
                    Integer i = Integer.parseInt(temp2);
                    i++;
                    temp1 = temp1 + "." + i;
                    return temp1;
                } catch (Exception e) {
                    return name + ".1";
                }
            }
            return name + ".1";
        }

    };
}

From source file:com.alternatecomputing.jschnizzle.renderer.WebSequenceRenderer.java

public BufferedImage render(Diagram diagram) {
    String script = diagram.getScript();
    if (script == null) {
        throw new RendererException("no script defined.");
    }/* ww w .  ja  v a  2s.  c  om*/

    String style = diagram.getStyle().getValue();
    String baseURL = getBaseURL();

    try {
        // build parameter string
        String data = "style=" + style + "&format=svg&message=" + URLEncoder.encode(script, "UTF-8");

        // send the request
        URL url = new URL(baseURL);
        URLConnection conn = url.openConnection();
        conn.setDoOutput(true);
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());

        // write parameters
        writer.write(data);
        writer.flush();

        // get the response
        StringBuffer answer = new StringBuffer();
        BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            answer.append(line);
        }
        writer.close();
        reader.close();

        JSONObject json = JSONObject.fromString(answer.toString());

        HttpClient client = new HttpClient();
        String proxyHost = System.getProperty("http.proxyHost");
        String proxyPort = System.getProperty("http.proxyPort");
        if (StringUtils.isNotBlank(proxyHost) && StringUtils.isNotBlank(proxyPort)) {
            client.getHostConfiguration().setProxy(proxyHost, Integer.parseInt(proxyPort));
        }
        String getURI = baseURL + json.getString("img");
        GetMethod getMethod = new GetMethod(getURI);
        client.executeMethod(getMethod);
        String svgContents = getMethod.getResponseBodyAsString();
        getMethod.releaseConnection();
        LOGGER.debug(svgContents);

        diagram.setEncodedImage(svgContents);
        TranscoderInput input = new TranscoderInput(new ByteArrayInputStream(svgContents.getBytes()));
        BufferedImageTranscoder imageTranscoder = new BufferedImageTranscoder();
        imageTranscoder.transcode(input, null);

        // log any errors to the UI console
        JSONArray errors = json.getJSONArray("errors");
        for (int eIdx = 0; eIdx < errors.length(); ++eIdx) {
            LOGGER.error("JSON error: " + errors.getString(eIdx));
        }
        return imageTranscoder.getBufferedImage();

    } catch (MalformedURLException e) {
        throw new RendererException(e);
    } catch (IOException e) {
        throw new RendererException(e);
    } catch (TranscoderException e) {
        throw new RendererException(e);
    }
}