Example usage for java.io OutputStreamWriter write

List of usage examples for java.io OutputStreamWriter write

Introduction

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

Prototype

public void write(int c) throws IOException 

Source Link

Document

Writes a single character.

Usage

From source file:com.hangum.tadpole.importexport.core.dialogs.SQLToDBImportDialog.java

private void saveLog() {
    try {//  w  w w. j  a v a2  s .c  om
        if (bufferBatchResult == null || "".equals(bufferBatchResult.toString())) { //$NON-NLS-1$
            MessageDialog.openWarning(null, Messages.get().Warning,
                    Messages.get().SQLToDBImportDialog_LogEmpty);
            return;
        }
        String filename = PublicTadpoleDefine.TEMP_DIR + userDB.getDisplay_name() + "_SQLImportResult.log"; //$NON-NLS-1$

        FileOutputStream fos = new FileOutputStream(filename);
        OutputStreamWriter bw = new OutputStreamWriter(fos, "UTF-8"); //$NON-NLS-1$

        bw.write(bufferBatchResult.toString());
        bw.close();

        String strImportResultLogContent = FileUtils.readFileToString(new File(filename));

        downloadExtFile(userDB.getDisplay_name() + "_SQLImportResult.log", strImportResultLogContent);//sbExportData.toString()); //$NON-NLS-1$
    } catch (Exception ee) {
        logger.error("log writer", ee); //$NON-NLS-1$
    }
}

From source file:br.gov.frameworkdemoiselle.monitoring.internal.implementation.zabbix.ZabbixSender.java

/**
 * @param key//from www .  j a  v a 2 s  . c o m
 * @param value
 * @throws IOException
 */
private void send(final String key, final String value) throws IOException {

    final long start = System.currentTimeMillis();

    final StringBuilder message = new StringBuilder(head);
    message.append(encodeBase64(key));
    message.append(middle);
    message.append(encodeBase64(value == null ? "" : value));
    message.append(tail);

    logger.debug(bundle.getString("zabbix-sender-sending-message", this.zabbixHost, key, value));
    logger.trace(bundle.getString("zabbix-sender-detailed-message", message));

    Socket socket = null;
    OutputStreamWriter out = null;
    InputStream in = null;

    try {
        socket = new Socket(zabbixServer, zabbixPort);
        socket.setSoTimeout(TIMEOUT);

        out = new OutputStreamWriter(socket.getOutputStream());
        out.write(message.toString());
        out.flush();

        in = socket.getInputStream();
        final int read = in.read(response);

        final String resp = new String(response);
        logger.debug(bundle.getString("zabbix-sender-received-response", resp));
        if (read != 2 || response[0] != 'O' || response[1] != 'K') {
            logger.warn(bundle.getString("zabbix-sender-unexpected-response", key, resp));
        }

    } finally {
        if (in != null) {
            in.close();
        }
        if (out != null) {
            out.close();
        }
        if (socket != null) {
            socket.close();
        }
    }

    final long elapsed = System.currentTimeMillis() - start;
    logger.trace(bundle.getString("zabbix-sender-message-sent", elapsed));
}

From source file:clientserver.ServerThread.java

final void initClientData() {
    try {/*ww w  .  j  av  a  2 s . co  m*/
        OutputStreamWriter os = new OutputStreamWriter(socket.getOutputStream(), StandardCharsets.UTF_8);
        JSONObject jWriteobj = new JSONObject();
        jWriteobj.put("name1", "sp_on");
        jWriteobj.put("value1", 245);
        jWriteobj.put("name2", "sp_off");
        jWriteobj.put("value2", 45);
        jWriteobj.put("name3", "mc_on");
        jWriteobj.put("value3", 3455);
        jWriteobj.put("name4", "mc_off");
        jWriteobj.put("value4", 2045);
        os.write(jWriteobj.toString());
        os.flush();
    } catch (IOException e) {
        System.out.println("Write socket closing" + e.getMessage());
    }
}

From source file:org.miloss.fgsms.services.rs.impl.reports.ws.ThroughputByHostingServer.java

@Override
public void generateReport(OutputStreamWriter data, List<String> urls, String path, List<String> files,
        TimeRange range, String currentuser, SecurityWrapper classification, WebServiceContext ctx)
        throws IOException {

    if (!UserIdentityUtil.hasGlobalAdministratorRole(currentuser, "INVOCATIONS_BY_HOSTING_SERVER",
            classification, ctx)) {/*from  ww w  . ja v  a2s.  c o m*/
        data.write("<h2>Access for " + GetDisplayName() + " was denied for non-global admin users</h2>");
        return;
    }
    double d = range.getEnd().getTimeInMillis() - range.getStart().getTimeInMillis();
    double day = d / 86400000;
    double hours = d / 3600000;
    double min = d / 60000;
    double sec = d / 1000;
    Connection con = Utility.getPerformanceDBConnection();
    try {
        PreparedStatement cmd = null;
        ResultSet rs = null;
        DefaultCategoryDataset set = new DefaultCategoryDataset();
        JFreeChart chart = null;
        data.append("<hr /><h2>").append(GetDisplayName()).append("</h2>");
        data.append(GetHtmlFormattedHelp() + "<br />");
        data.append(
                "<table  class=\"table table-hover\"><tr><th>Service Hostname</th><th>Invocations</th><th>Msg/Day</th><th>Msg/Hour</th><th>Msg/Min</th><th>Msg/Sec</th></tr>");

        // for (int i = 0; i < urls.size(); i++) {
        List<String> hosts = new ArrayList<String>();
        try {
            cmd = con.prepareStatement(
                    "select hostingsource from rawdata where (UTCdatetime > ?) and (UTCdatetime < ?) group by hostingsource ;");
            cmd.setLong(1, range.getStart().getTimeInMillis());
            cmd.setLong(2, range.getEnd().getTimeInMillis());
            rs = cmd.executeQuery();
            while (rs.next()) {
                String s = rs.getString(1);
                if (!Utility.stringIsNullOrEmpty(s)) {
                    s = s.trim();
                }
                if (!Utility.stringIsNullOrEmpty(s)) {
                    hosts.add(s);
                }
            }
        } catch (Exception ex) {
        } finally {
            DBUtils.safeClose(rs);
            DBUtils.safeClose(cmd);
        }

        for (int i = 0; i < hosts.size(); i++) {
            long count = 0;
            try {
                cmd = con.prepareStatement("select count(*) from RawData where hostingsource=? and "
                        + "(UTCdatetime > ?) and (UTCdatetime < ?) ;");
                cmd.setString(1, hosts.get(i));
                cmd.setLong(2, range.getStart().getTimeInMillis());
                cmd.setLong(3, range.getEnd().getTimeInMillis());
                rs = cmd.executeQuery();

                try {
                    if (rs.next()) {
                        count = rs.getLong(1);
                    }
                } catch (Exception ex) {
                    log.log(Level.DEBUG, null, ex);
                }
            } catch (Exception ex) {
                log.log(Level.ERROR, "Error opening or querying the database.", ex);
            } finally {
                DBUtils.safeClose(rs);
                DBUtils.safeClose(cmd);
            }
            data.append("<tr><td>").append(Utility.encodeHTML(hosts.get(i))).append("</td><td>");
            data.append(count + "");
            data.append("</td><td>").append(format.format((double) ((double) count / day))).append("</td><td>")
                    .append(format.format((double) ((double) count / hours))).append("</td><td>")
                    .append(format.format((double) ((double) count / min))).append("</td><td>")
                    .append(format.format((double) ((double) count / sec))).append("</td></tr>");
            if (count > 0) {
                set.addValue((double) ((double) count / day), hosts.get(i), hosts.get(i));
            }
        }

        chart = org.jfree.chart.ChartFactory.createBarChart(GetDisplayName(), "Service URL", "", set,
                PlotOrientation.HORIZONTAL, true, false, false);
        data.append("</table>");
        try {
            ChartUtilities.saveChartAsPNG(new File(
                    path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png"), chart,
                    1500, pixelHeightCalc(hosts.size()));
        } catch (IOException ex) {
            log.log(Level.ERROR, "Error saving chart image for request", ex);
        }

        data.append("<img src=\"image_").append(this.getClass().getSimpleName()).append(".png\">");
        files.add(path + getFilePathDelimitor() + "image_" + this.getClass().getSimpleName() + ".png");
    } catch (Exception ex) {
        log.log(Level.ERROR, null, ex);
    } finally {
        DBUtils.safeClose(con);
    }
}

From source file:org.guanxi.sp.engine.service.saml2.WebBrowserSSOAuthConsumerService.java

private String processGuardConnection(String acsURL, String entityID, String keystoreFile,
        String keystorePassword, String truststoreFile, String truststorePassword,
        ResponseDocument responseDocument, String guardSession) throws GuanxiException, IOException {
    EntityConnection connection;/*  www.j av a2  s.  co m*/

    Bag bag = getBag(responseDocument, guardSession);

    // Initialise the connection to the Guard's attribute consumer service
    connection = new EntityConnection(acsURL, entityID, keystoreFile, keystorePassword, truststoreFile,
            truststorePassword, EntityConnection.PROBING_OFF);
    connection.setDoOutput(true);
    connection.connect();

    // Send the data to the Guard in an explicit POST variable
    String json = URLEncoder.encode(Guanxi.REQUEST_PARAMETER_SAML_ATTRIBUTES, "UTF-8") + "="
            + URLEncoder.encode(bag.toJSON(), "UTF-8");

    OutputStreamWriter wr = new OutputStreamWriter(connection.getOutputStream());
    wr.write(json);
    wr.flush();
    wr.close();

    //os.close();

    // ...and read the response from the Guard
    return new String(Utils.read(connection.getInputStream()));
}

From source file:it.greenvulcano.gvesb.virtual.rest.RestCallOperation.java

@Override
public GVBuffer perform(GVBuffer gvBuffer) throws ConnectionException, CallException, InvalidDataException {

    try {/*from  w  w w. j av a2 s .c o  m*/
        final GVBufferPropertyFormatter formatter = new GVBufferPropertyFormatter(gvBuffer);

        String expandedUrl = formatter.format(url);
        String querystring = "";

        if (!params.isEmpty()) {

            querystring = params.entrySet().stream().map(
                    e -> formatter.formatAndEncode(e.getKey()) + "=" + formatter.formatAndEncode(e.getValue()))
                    .collect(Collectors.joining("&"));

            expandedUrl = expandedUrl.concat("?").concat(querystring);
        }

        StringBuffer callDump = new StringBuffer();
        callDump.append("Performing RestCallOperation " + name).append("\n        ").append("URL: ")
                .append(expandedUrl);

        URL requestUrl = new URL(expandedUrl);

        HttpURLConnection httpURLConnection;
        if (truststorePath != null && expandedUrl.startsWith("https://")) {
            httpURLConnection = openSecureConnection(requestUrl);
        } else {
            httpURLConnection = (HttpURLConnection) requestUrl.openConnection();
        }
        callDump.append("\n        ").append("Method: " + method);

        callDump.append("\n        ").append("Connection timeout: " + connectionTimeout);
        callDump.append("\n        ").append("Read timeout: " + readTimeout);

        httpURLConnection.setRequestMethod(method);
        httpURLConnection.setConnectTimeout(connectionTimeout);
        httpURLConnection.setReadTimeout(readTimeout);

        for (Entry<String, String> header : headers.entrySet()) {
            String k = formatter.format(header.getKey());
            String v = formatter.format(header.getValue());
            httpURLConnection.setRequestProperty(k, v);
            callDump.append("\n        ").append("Header: " + k + "=" + v);
            if ("content-type".equalsIgnoreCase(k) && "application/x-www-form-urlencoded".equalsIgnoreCase(v)) {
                body = querystring;
            }

        }

        if (sendGVBufferObject && gvBuffer.getObject() != null) {
            byte[] requestData;
            if (gvBuffer.getObject() instanceof byte[]) {
                requestData = (byte[]) gvBuffer.getObject();
            } else {
                requestData = gvBuffer.getObject().toString().getBytes();

            }
            httpURLConnection.setRequestProperty("Content-Length", Integer.toString(requestData.length));
            callDump.append("\n        ").append("Content-Length: " + requestData.length);
            callDump.append("\n        ").append("Request body: binary");
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            DataOutputStream dataOutputStream = new DataOutputStream(httpURLConnection.getOutputStream());
            dataOutputStream.write(requestData);

            dataOutputStream.flush();
            dataOutputStream.close();

        } else if (Objects.nonNull(body) && body.length() > 0) {

            String expandedBody = formatter.format(body);
            callDump.append("\n        ").append("Request body: " + expandedBody);
            logger.debug(callDump.toString());

            httpURLConnection.setDoOutput(true);

            OutputStreamWriter outputStreamWriter = new OutputStreamWriter(httpURLConnection.getOutputStream());
            outputStreamWriter.write(expandedBody);
            outputStreamWriter.flush();
            outputStreamWriter.close();

        }

        httpURLConnection.connect();

        InputStream responseStream = null;

        try {
            httpURLConnection.getResponseCode();
            responseStream = httpURLConnection.getInputStream();
        } catch (IOException connectionFail) {
            responseStream = httpURLConnection.getErrorStream();
        }

        for (Entry<String, List<String>> header : httpURLConnection.getHeaderFields().entrySet()) {
            if (Objects.nonNull(header.getKey()) && Objects.nonNull(header.getValue())) {
                gvBuffer.setProperty(RESPONSE_HEADER_PREFIX.concat(header.getKey().toUpperCase()),
                        header.getValue().stream().collect(Collectors.joining(";")));
            }
        }

        if (responseStream != null) {

            byte[] responseData = IOUtils.toByteArray(responseStream);
            String responseContentType = Optional
                    .ofNullable(gvBuffer.getProperty(RESPONSE_HEADER_PREFIX.concat("CONTENT-TYPE"))).orElse("");

            if (responseContentType.startsWith("application/json")
                    || responseContentType.startsWith("application/javascript")) {
                gvBuffer.setObject(new String(responseData, "UTF-8"));
            } else {
                gvBuffer.setObject(responseData);
            }

        } else { // No content
            gvBuffer.setObject(null);
        }

        gvBuffer.setProperty(RESPONSE_STATUS, String.valueOf(httpURLConnection.getResponseCode()));
        gvBuffer.setProperty(RESPONSE_MESSAGE,
                Optional.ofNullable(httpURLConnection.getResponseMessage()).orElse("NULL"));

        httpURLConnection.disconnect();

    } catch (Exception exc) {
        throw new CallException("GV_CALL_SERVICE_ERROR",
                new String[][] { { "service", gvBuffer.getService() }, { "system", gvBuffer.getSystem() },
                        { "tid", gvBuffer.getId().toString() }, { "message", exc.getMessage() } },
                exc);
    }
    return gvBuffer;
}

From source file:biblivre3.cataloging.bibliographic.BiblioBO.java

private MemoryFileDTO createFile(final Collection<RecordDTO> records) {
    final MemoryFileDTO file = new MemoryFileDTO();
    file.setFileName(new Date().getTime() + ".mrc");
    try {//from   w ww .  j a  v  a 2s .co  m
        final ByteArrayOutputStream baos = new ByteArrayOutputStream();
        final OutputStreamWriter writer = new OutputStreamWriter(baos, "UTF-8");
        for (RecordDTO dto : records) {
            writer.write(dto.getIso2709());
            writer.write(ApplicationConstants.LINE_BREAK);
        }
        writer.flush();
        writer.close();
        file.setFileData(baos.toByteArray());
    } catch (Exception e) {
        log.error(e.getMessage(), e);
    }
    return file;
}

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 a 2 s.  co  m*/
        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.denimgroup.threadfix.importer.cli.ScriptRunner.java

public long checkRunningAndFixStatements(String errorLogFile, String fixedSqlFile) {

    long errorCount = 0;

    File outputFixedScript = new File(fixedSqlFile);

    FileOutputStream fos = null;//  w ww  . jav a 2 s .c  om
    try {
        List<String> lines = FileUtils.readLines(new File(errorLogFile));

        if (lines != null && lines.size() > 1) {
            fos = new FileOutputStream(outputFixedScript);
            OutputStreamWriter osw = new OutputStreamWriter(fos);

            String preLine = null;
            Map<String, Object> map = new HashMap<>();
            osw.write("SET FOREIGN_KEY_CHECKS=0;\n");
            for (String currentLine : lines) {

                if (!currentLine.contains("Error executing: INSERT INTO")) {
                    // Remove all weird characters if they cause 'incorrect string value' SQLExeption
                    if (currentLine.toLowerCase().contains("incorrect string value")) {
                        if (preLine != null) {
                            String fixedStatement = preLine.replace("Error executing: ", "")
                                    .replaceAll("[^\\x00-\\x7F]", "");
                            osw.write(fixedStatement + ";\n");
                        }
                    }
                    // If there is unknown column, then delete that column and its value
                    else if (currentLine.contains("MySQLSyntaxErrorException: Unknown column")) {
                        osw.write(getFixedUnknownColStatement(currentLine,
                                preLine.replace("Error executing: ", "")));
                    }
                    // too long string for column, cut it off
                    else if (currentLine.contains("Data too long for column")) {
                        map = exactTableFromString(preLine);
                        if (map == null || map.isEmpty()) {
                            LOGGER.error("Unable to fix statement: " + preLine);
                            LOGGER.error("Error was: " + currentLine);
                            osw.write(preLine.replace("Error executing: ", "") + ";\n");
                            continue;
                        }
                        osw.write(fixLongColumnStatement(preLine, currentLine, map));
                    }
                    // Older version of MySQL doesn't take time with fraction like '2015-10-28 13:01:59.289000000'
                    else if (currentLine.contains("Data truncation: Incorrect datetime value")) {
                        osw.write(fixDateWrongStatement(preLine, currentLine));
                    } else if (currentLine.contains("Packet for query is too large")) {
                        LOGGER.error(currentLine);
                        if (preLine.contains("INSERT INTO DOCUMENT")) {
                            LOGGER.warn(
                                    "You have failed to import a big document. Please upload that document by ThreadFix UI.");
                            map = exactTableFromString(preLine);
                            if (map != null && !map.isEmpty()) {
                                Map<String, String> fieldMap = (Map) map.get("tableFields");
                                for (String key : fieldMap.keySet()) {
                                    if (!key.equalsIgnoreCase("file")) {
                                        LOGGER.warn(key + ": " + fieldMap.get(key));
                                    }
                                }
                            }
                        } else {
                            osw.write(preLine.replace("Error executing: ", "") + ";\n");
                        }
                    } else if (currentLine
                            .contains("MySQLSyntaxErrorException: You have an error in your SQL syntax; "
                                    + "check the manual that corresponds to your MySQL server version")) {
                        osw.write(fixSyntaxStatement(preLine.replace("Error executing: ", ""), currentLine));
                    }
                    // Unresolved-yet SQLException, then write whole statement to fixed Sql script
                    else {
                        if (preLine != null && preLine.contains("Error executing: INSERT INTO")) {
                            osw.write(preLine.replace("Error executing: ", "") + ";\n");
                        }
                    }
                } else {
                    errorCount += 1;
                }
                preLine = currentLine;
            }

            osw.write("SET FOREIGN_KEY_CHECKS=1;\n");
            osw.close();
        }
    } catch (IOException e) {
        LOGGER.error("Error", e);
    }
    return errorCount;
}

From source file:markson.visuals.sitapp.settingActivity.java

public void WriteSettings(Context context, String data) {

    FileOutputStream fOut = null;

    OutputStreamWriter osw = null;

    try {/*www.  j  a  v  a 2 s  .c  o  m*/

        fOut = openFileOutput("settings.dat", MODE_PRIVATE);

        osw = new OutputStreamWriter(fOut);

        osw.write(data);

        osw.flush();

        //Toast.makeText(context, "Classes Saved",Toast.LENGTH_SHORT).show();

    }

    catch (Exception e) {

        e.printStackTrace();

        Toast.makeText(context, "Settings not saved", Toast.LENGTH_SHORT).show();

    }

    finally {

        try {

            osw.close();

            fOut.close();

        } catch (IOException e) {

            e.printStackTrace();

        }

    }

}