Example usage for java.io PrintWriter append

List of usage examples for java.io PrintWriter append

Introduction

In this page you can find the example usage for java.io PrintWriter append.

Prototype

public PrintWriter append(char c) 

Source Link

Document

Appends the specified character to this writer.

Usage

From source file:org.auraframework.http.AuraTestFilter.java

private void writeJsTestScript(PrintWriter out, DefDescriptor<?> targetDescriptor, String testName,
        int testTimeout) throws IOException {
    TestSuiteDef suiteDef;/*from   w ww.  ja va  2 s .c  o m*/
    TestCaseDef testDef;
    try {
        suiteDef = getTestSuite(targetDescriptor);
        testDef = getTestCase(suiteDef, testName);
        testDef.validateDefinition();
    } catch (QuickFixException e) {
        out.append(String.format("$A.test.run('%s',{},1,'%s');", testName, e.getMessage()));
        return;
    }

    out.append(String.format("var testBootstrapFunction = function(testName, suiteProps, testTimeout) { \n"
            + "if(!$A.test.isComplete()) {\n" + "if(window.sessionStorage) {\n"
            + "var oldStatus = sessionStorage.getItem('TestRunStatus'); \n"
            + "sessionStorage.setItem('TestRunStatus',(oldStatus?oldStatus:'')+'Run '+testName+', timeStamp#'+$A.test.time()+'.'); \n"
            + "}\n" + "$A.test.run(testName, suiteProps, testTimeout); \n" + "} else {\n"
            + "if(window.sessionStorage) {\n" + "var oldStatus = sessionStorage.getItem('TestRunStatus'); \n"
            + "sessionStorage.setItem('TestRunStatus',(oldStatus?oldStatus:'')+'Skip '+testName+', Test Already Complete, timeStamp#'+$A.test.time()+'.'); \n"
            + "}\n" + "}\n" + "}; \n"
            + "if(window && window.Aura && window.Aura.appBootstrapStatus === 'loaded' " + //bootstrap is finished
            "&& window.$A && window.$A.test && window.$A.test.isComplete instanceof Function ) { \n" + //but the test wasn't
            "if(window.sessionStorage) {\n" +
            //"var oldStatus = sessionStorage.getItem('TestRunStatus'); \n"+
            "sessionStorage.setItem('TestRunStatus','Run %s directly, as bootstrap finish before we can push test to its run-after, timeStamp#'+$A.test.time()+'.'); \n"
            + "}\n" + "testBootstrapFunction('%s', %s, '%s'); \n" + "} else {\n"
            + "if(window.sessionStorage) {\n" +
            //"var oldStatus = sessionStorage.getItem('TestRunStatus'); \n"+
            "sessionStorage.setItem('TestRunStatus','Push %s to bootstrap run after, timeStamp#'+$A.test.time()+'.'); \n"
            + "}\n" + "window.Aura || (window.Aura = {}); \n"
            + "window.Aura.afterBootstrapReady || (window.Aura.afterBootstrapReady = []); \n"
            + "window.Aura.afterBootstrapReady.push(testBootstrapFunction.bind(this, '%s', %s, '%s')); \n"
            + "} \n", testName, testName, suiteDef.getCode() + "\t\n", testTimeout, testName, testName,
            suiteDef.getCode() + "\t\n", testTimeout));
}

From source file:org.jahia.utils.maven.plugin.resources.GWTDictionaryMojo.java

/**
 * Performs conversion of the property file into JavaScript file.
 * //  w w  w. ja  v a 2s  .com
 * @param locale
 *            locale to be used
 * @throws IOException
 *             in case of an error
 */
private void convert(String locale) throws IOException {
    ResourceBundle defBundle = lookupBundle("", "en");
    if (defBundle == null) {
        throw new FileNotFoundException("ERROR : Couldn't find bundle with name " + resourceBundle
                + ".properties nor " + resourceBundle + "_en.properties in " + src + " folder, skipping...");
    }

    ResourceBundle bundle = locale != null ? lookupBundle(locale) : null;

    if (!dest.exists() && !dest.mkdirs()) {
        throw new IOException("Unable to create folder " + dest);
    }
    File target = new File(dest, targetFileName + (locale != null ? "_" + locale : "") + ".js");
    getLog().info("Creating " + target + " ...");
    PrintWriter out = new PrintWriter(target);
    Enumeration<String> keyEnum = defBundle.getKeys();
    List<String> keys = new LinkedList<String>();
    while (keyEnum.hasMoreElements()) {
        keys.add(keyEnum.nextElement());
    }
    Collections.sort(keys);
    out.print("var ");
    out.print(dictionaryName);
    out.print("={");
    if (prettyPrint) {
        out.println();
    }
    for (Iterator<String> iterator = keys.iterator(); iterator.hasNext();) {
        String key = iterator.next();
        String value = bundle != null ? JavaScriptDictionaryMojo.getValue(bundle, key) : null;
        if (value == null) {
            value = JavaScriptDictionaryMojo.getValue(defBundle, key);
        }

        if (value != null) {
            out.append(normalizeKey(key)).append(":\"").append(JavaScriptDictionaryMojo.escape(value))
                    .append("\"");
            if (iterator.hasNext()) {
                out.append(",");
            }
            if (prettyPrint) {
                out.println();
            }
        }
    }
    out.print("};");
    if (prettyPrint) {
        out.println();
    }

    out.flush();
    out.close();
    getLog().info("done");
}

From source file:org.kalypso.model.hydrology.internal.preprocessing.writer.NetFileWriter.java

@Override
protected void writeContent(final PrintWriter writer) throws IOException, NAPreprocessorException {
    final NetElement[] channels = m_relevantElements.getChannels();
    for (final NetElement netElement : channels)
        netElement.write(writer);//  w w w.ja  v  a 2  s.  co m

    final Entry<NetElement, Integer>[] rootChannels = m_relevantElements.getRootChannels();
    for (final Entry<NetElement, Integer> entry : rootChannels) {
        final NetElement netElement = entry.getKey();
        final Integer virtualChannelId = entry.getValue();
        netElement.writeRootChannel(writer, virtualChannelId);
    }

    try {
        final Node[] nodeCollector = m_relevantElements.getNodes();
        writer.append("99999\n"); //$NON-NLS-1$
        appendNodeList(nodeCollector, writer);
        writer.append("99999\n"); //$NON-NLS-1$
    } catch (final SensorException e) {
        e.printStackTrace();
        throw new NAPreprocessorException(Messages.getString("NetFileWriter_0"), e); //$NON-NLS-1$
    }
}

From source file:com.example.testtab.fragment.TwitEyesPageFragment.java

public boolean save(String name, String data) {
    try {/*from w  w w. ja v  a 2  s. c  o m*/
        OutputStream out = this.mContext.openFileOutput(name, this.mContext.MODE_PRIVATE);
        PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8"));
        writer.append(data);
        writer.close();
    } catch (IOException e) {
        return false;
    }
    return true;
}

From source file:com.ifeng.computing.service.impl.DataFactoryServiceTest.java

@Test
public void buildPushData() {

    File file = null;/*from  ww  w . jav a 2  s .  co  m*/
    PrintWriter pw = null;
    OutputStream out = null;

    try {
        file = new File("F:BIG_EVENT_LOG2.txt");
        pw = new PrintWriter(new File("F:/HUGE_FILE.txt"));

        int start = 0;
        List<NewsItem> newsList = new ArrayList<NewsItem>();
        List<LogData> logList = new ArrayList<LogData>();

        Map<String, Object> map = new HashMap<String, Object>();
        map.put("limit", LIMIT_SIZE);

        int steps = (MAX_USER_SIZE % LIMIT_SIZE == 0) ? (MAX_USER_SIZE / LIMIT_SIZE)
                : (MAX_USER_SIZE / LIMIT_SIZE + 1);

        Map<String, Object> newsMap = new HashMap<String, Object>();
        newsMap.put("start", 0);
        newsMap.put("limit", NEWS_ITEM_SIZE);

        pw.append("[");

        ObjectMapper mapper = new ObjectMapper();
        for (int i = 0; i < steps; i++) {
            start = i * LIMIT_SIZE;
            map.put("start", start);

            log.info("Step {} loading ... , Start index is [{}]", i, start);

            logList = dataFactoryService.readLogData(map);

            for (int j = 0, length = logList.size(); j < length; j++) {
                LogData data = logList.get(j);

                newsMap.put("pId", data.getpId());
                newsList = dataFactoryService.readNewsByUserId(newsMap);

                data.setNewsItem(newsList);

                if (i == 0 && j == 0) {
                    pw.append(mapper.writeValueAsString(data));
                } else {
                    pw.append(",");
                    pw.append(mapper.writeValueAsString(data));
                }

                if (j % 50 == 0)
                    pw.flush();

            }

            out = new BufferedOutputStream(new FileOutputStream(file, true), BUFFER_SIZE);
            mapper.writeValue(out, logList);

        }

        pw.append("]");

    } catch (JsonGenerationException e) {
        log.error(e.getMessage(), e);
    } catch (JsonMappingException e) {
        log.error(e.getMessage(), e);
    } catch (FileNotFoundException e) {
        log.error(e.getMessage(), e);
    } catch (IOException e) {
        log.error(e.getMessage(), e);
    } finally {
        if (out != null) {
            try {
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

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

    }
}

From source file:org.everrest.websockets.client.WSClient.java

private byte[] getHandshake() {
    ByteArrayOutputStream out = new ByteArrayOutputStream();
    PrintWriter handshake = new PrintWriter(out);
    handshake.format("GET %s HTTP/1.1\r\n", target.getPath());
    final int port = target.getPort();
    if (port == 80) {
        handshake.format("Host: %s\r\n", target.getHost());
    } else {/*from w  ww  .j a  va  2s.  c o m*/
        handshake.format("Host: %s:%d\r\n", target.getHost(), port);
    }
    handshake.append("Upgrade: Websocket\r\n");
    handshake.append("Connection: Upgrade\r\n");
    String[] subProtocol = getSubProtocols();
    if (subProtocol != null && subProtocol.length > 0) {
        handshake.format("Sec-WebSocket-Protocol: %s\r\n", Arrays.toString(subProtocol));
    }
    handshake.format("Sec-WebSocket-Key: %s\r\n", secWebSocketKey);
    handshake.format("Sec-WebSocket-Version: %d\r\n", 13);
    handshake.append("Sec-WebSocket-Protocol: chat\r\n");
    String origin = getOrigin();
    if (origin != null) {
        handshake.format("Origin: %s\r\n", origin);
    }
    handshake.append('\r');
    handshake.append('\n');
    handshake.flush();
    return out.toByteArray();
}

From source file:sos.Sos.java

/** returns an XML service description with information about the interface 
 * (offered operations and endpoints) as well as the available sensor data,
 * such as the period for which sensor data is available,
 * sensors that produce the measured values, 
 * or phenomena that are observed (for example air temperature).
 * /*from  w w  w  .  j a va2s. c o  m*/
 * @param request Http Servlet Request
 * @param response Http Servlet Response
 * @param out PrintWriter for Http Servlet Response
 * @param snannySostServerConfig the sos server configuration
 * @throws SnannySostServerException  server exception (I/O problem)
 */
private void getCapabilities(HttpServletRequest request, HttpServletResponse response, PrintWriter out,
        SnannySostServerConfig snannySostServerConfig) throws SnannySostServerException {
    try {
        InputStream in = snannySostServerConfig.getCababilitiesInputstream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        String line;
        response.setContentType("application/xml;charset=" + snannySostServerConfig.getCharset().name());
        while ((line = reader.readLine()) != null) {
            out.append(line);
        }
        reader.close();
    } catch (IOException ioe) {
        throw new SnannySostServerException(SnannySostServerMessages.ERROR_getCapabilities,
                Status.SERVICE_UNAVAILABLE);
    }
}

From source file:UploadTest.java

@Test
public void form_test() {
    try {// ww  w  .  j ava2  s.com
        url = new URL("http://localhost:9000/resource/frl:6376982/data");
        httpCon = (HttpURLConnection) url.openConnection();
        String userpass = user + ":" + password;
        basicAuth = "Basic " + new String(new Base64().encode(userpass.getBytes()));
        httpCon.setRequestProperty("Authorization", basicAuth);
        String fieldName = "data";
        File uploadFile = new File("/home/raul/test/frl%3A6376982/6376990.pdf");
        String boundary = "" + System.currentTimeMillis() + "";

        httpCon.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
        httpCon.setRequestProperty("file", "6376986.pdf");

        httpCon.setUseCaches(false);
        httpCon.setDoOutput(true);
        httpCon.setDoInput(true);

        httpCon.setRequestMethod("PUT");

        OutputStream outputStream = null;
        try {
            outputStream = (httpCon.getOutputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }
        PrintWriter writer = null;
        try {
            writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        String LINE_FEED = "\r\n";
        String fileName = uploadFile.getName();
        writer.append("--" + boundary).append(LINE_FEED);
        System.out.println("--" + boundary + (LINE_FEED));
        writer.append(
                "Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName + "\"")
                .append(LINE_FEED);
        System.out.println("Content-Disposition: form-data; name=\"" + fieldName + "\"; filename=\"" + fileName
                + "\"" + (LINE_FEED));
        writer.append("Content-Type: " + URLConnection.guessContentTypeFromName(fileName)).append(LINE_FEED);
        System.out.println("Content-Type: " + URLConnection.guessContentTypeFromName(fileName) + (LINE_FEED));
        writer.append("Content-Transfer-Encoding: binary").append(LINE_FEED);
        System.out.println("Content-Transfer-Encoding: binary" + (LINE_FEED));
        writer.append(LINE_FEED);

        writer.flush();

        fileToOutputStream(uploadFile, outputStream);

        // httpCon.getInputStream();
        try {
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }

        writer.append(LINE_FEED);
        writer.flush();
        writer.close();
        httpCon.disconnect();

        try {
            System.out.println(httpCon.getResponseCode());
            System.out.println(httpCon.getResponseMessage());
        } catch (IOException e) {
            e.printStackTrace();
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:kr.motd.maven.exec.ExecMojo.java

protected File createEnvWrapperFile(File envScript) throws IOException {
    PrintWriter writer = null;
    File tmpFile = null;//w ww. jav  a2 s  .  c o m
    try {

        if (OS.isFamilyWindows()) {
            tmpFile = File.createTempFile("env", ".bat");
            writer = new PrintWriter(tmpFile);
            writer.append("@echo off").println();
            writer.append("call \"").append(envScript.getCanonicalPath()).append("\"").println();
            writer.append("echo " + EnvStreamConsumer.START_PARSING_INDICATOR).println();
            writer.append("set").println();
            writer.flush();
        } else {
            tmpFile = File.createTempFile("env", ".sh");
            // tmpFile.setExecutable( true );//java 6 only
            writer = new PrintWriter(tmpFile);
            writer.append("#! /bin/sh").println();
            writer.append(". ").append(envScript.getCanonicalPath()).println(); // works on all unix??
            writer.append("echo " + EnvStreamConsumer.START_PARSING_INDICATOR).println();
            writer.append("env").println();
            writer.flush();
        }
    } finally {
        IOUtil.close(writer);
    }

    return tmpFile;

}

From source file:org.auraframework.http.resource.InlineJs.java

/**
 * Writes javascript into pre init "beforeFrameworkInit"
 *
 * @param def current application or component
 * @param mode current Mode from AuraContext
 * @param out response writer//from ww w.j  ava 2s. co m
 */
private void appendPreInitJavascripts(BaseComponentDef def, Mode mode, PrintWriter out) {
    if (this.preInitJavascripts != null && !this.preInitJavascripts.isEmpty()) {
        StringBuilder sb = new StringBuilder();
        for (PreInitJavascript js : this.preInitJavascripts) {
            if (js.shouldInsert(def, mode)) {
                String code = js.getJavascriptCode(def, mode);
                if (code != null && !code.isEmpty()) {
                    sb.append(
                            String.format("window.Aura.beforeFrameworkInit.push(function() { %s ; }); ", code));
                }
            }
        }
        if (sb.length() > 0) {
            String output = String.format(
                    ";(function() { window.Aura = window.Aura || {}; window.Aura.beforeFrameworkInit = Aura.beforeFrameworkInit || []; %s }());",
                    sb.toString());
            out.append(output);
        }
    }
}