Example usage for java.io Writer write

List of usage examples for java.io Writer write

Introduction

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

Prototype

public void write(String str) throws IOException 

Source Link

Document

Writes a string.

Usage

From source file:fr.itinerennes.bundler.tasks.StopTask.java

private void write(final File outputFile, final Object o) {
    Writer w = null;
    try {//from   w w  w . j a v a 2s .co  m
        w = new PrintWriter(outputFile, "utf-8");
        w.write(gson.toJson(o));
    } catch (IOException e) {
        LOGGER.error("Can't serialize {} {}", new Object[] { o, outputFile, e });
    } finally {
        IOUtils.closeQuietly(w);
    }
}

From source file:io.undertow.server.handlers.HttpTunnelingViaConnectTestCase.java

@Test
public void testConnectViaProxy() throws Exception {

    final HttpHost proxy = new HttpHost(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default") + 1, "http");
    final HttpHost target = new HttpHost(DefaultServer.getHostAddress("default"),
            DefaultServer.getHostPort("default"), "http");
    ProxyClient proxyClient = new ProxyClient();
    Socket socket = proxyClient.tunnel(proxy, target, new UsernamePasswordCredentials("a", "b"));
    try {//from  w w w .ja v  a 2  s  . com
        Writer out = new OutputStreamWriter(socket.getOutputStream(), HTTP.DEF_CONTENT_CHARSET);
        out.write("GET / HTTP/1.1\r\n");
        out.write("Host: " + target.toHostString() + "\r\n");
        out.write("Connection: close\r\n");
        out.write("\r\n");
        out.flush();
        BufferedReader in = new BufferedReader(
                new InputStreamReader(socket.getInputStream(), HTTP.DEF_CONTENT_CHARSET));
        String line = null;
        boolean found = false;
        while ((line = in.readLine()) != null) {
            System.out.println(line);
            if (line.equals("MyHeader: MyValue")) {
                found = true;
            }
        }
        Assert.assertTrue(found);
    } finally {
        socket.close();
    }
}

From source file:Main.java

/**
 * Unescape (and normalize) the given XML string.
 * /*ww  w .j  a  v  a2  s . c  o  m*/
 * Only element content (excluding markup) and attributes (values) need to be unescaped.
 * Markup, comments, CDATA sections, and prosessing instructions need to be left unchanged.
 * 
 *
 * @param writer         The writer where the escaped string is written to.
 * @param str            The given XML string (character text or attribute value; unescaped).
 */
private static void unescape(Writer writer, String str) throws Exception {
    // First, normalize end-of-line delimiters
    str = str.replaceAll("(?i)
", "
"); // case-insensitive matching
    str = str.replaceAll("(?i)
…", "
"); // case-insensitive matching
    str = str.replaceAll("(?i)…", "
"); // case-insensitive matching
    str = str.replaceAll("(?i)
", "
"); // case-insensitive matching
    str = str.replaceAll("(?i)
", "
"); // case-insensitive matching

    // Finally, unescape characters
    for (int i = 0; i < str.length(); i++) {
        char c = str.charAt(i);

        switch (c) {
        // ampersand:
        case '&':
            int nextIdx = i + 1;
            int semiColonIdx = str.indexOf(';', nextIdx);
            // Found ampersand did not start an entity, no following semi-colon exists
            if (semiColonIdx == -1) {
                // The the text looks like &...
                writer.write(c);
                continue;
            }
            int amphersandIdx = str.indexOf('&', nextIdx);
            // Found ampersand did not start an entity, no following semi-colon before next ampersand
            if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) {
                // Then the text looks like &...&...;
                writer.write(c);
                continue;
            }

            String entityContent = str.substring(nextIdx, semiColonIdx);
            int entityValue = -1;
            if (entityContent.length() > 0) {
                // Escaped value content is an integer (decimal or hexadecimal)
                if (entityContent.charAt(0) == '#') {
                    if (entityContent.length() > 1) {
                        char isHexChar = entityContent.charAt(1);

                        try {
                            switch (isHexChar) {
                            // hexadecimal, 16 base
                            case 'X':
                            case 'x':
                                entityValue = Integer.parseInt(entityContent.substring(2), 16);
                                break;
                            // decimal, 10 base
                            default:
                                entityValue = Integer.parseInt(entityContent.substring(1), 10);
                            }
                            if (entityValue > 0xFFFF) {
                                entityValue = -1;
                            }
                        } catch (NumberFormatException nfex) {
                            entityValue = -1;
                        }
                    }
                }
                // Escaped value content is an entity name
                else {
                    // less-than:
                    if ("lt".equals(entityContent) == true) {
                        entityValue = 60;
                    }
                    // ampersand:
                    else if ("amp".equals(entityContent) == true) {
                        entityValue = 38;
                    }
                    // greater-than:
                    else if ("gt".equals(entityContent) == true) {
                        entityValue = 62;
                    }
                    // single-quote:
                    else if ("apos".equals(entityContent) == true) {
                        entityValue = 39;
                    }
                    // double-quote:
                    else if ("quot".equals(entityContent) == true) {
                        entityValue = 34;
                    }
                }
            }

            // Entity value was not found (not an XML entity value)
            if (entityValue == -1) {
                writer.write('&');
                writer.write(entityContent);
                writer.write(';');
            }
            // Entity value was found
            else {
                writer.write(entityValue);
            }
            i = semiColonIdx; // move index up to the semi-colon
            break;
        // else, default print char
        default:
            writer.write(c);
        }
    }
}

From source file:com.github.peterjanes.node.NpmPackageJsonMojo.java

/**
 *
 * @throws MojoExecutionException if anything unexpected happens.
 *///from   ww w .jav  a 2s.c  om
public void execute() throws MojoExecutionException {
    if (!outputDirectory.exists()) {
        outputDirectory.mkdirs();
    }

    File packageJsonFile = new File(outputDirectory, "package.json");

    try {
        packageJsonFile.getParentFile().mkdirs();
        JSONObject packageJson = new JSONObject();
        packageJson.put("name", mavenProject.getName());
        packageJson.put("version", mavenProject.getProperties().getProperty("node.project.version"));
        packageJson.put("description", mavenProject.getDescription());
        packageJson.put("main", mainModule);

        List<Artifact> dependencyArtifacts = getNodeArtifacts(ResolutionScope.COMPILE);
        JSONObject dependencies = new JSONObject();
        // TODO: dependency.getVersion() may (and often will) return a
        // -SNAPSHOT. Figure out how to open the .tgz and pull in its
        // actual version, or rewrite the version as a range.
        for (Artifact dependency : dependencyArtifacts) {
            dependencies.put(dependency.getArtifactId(), dependency.getVersion());
        }
        addNpmDependencies(dependencies, npmDependencies);
        packageJson.put("dependencies", dependencies);

        List<Artifact> devDependencyArtifacts = getNodeArtifacts(ResolutionScope.TEST);
        JSONObject devDependencies = new JSONObject();
        for (Artifact devDependency : devDependencyArtifacts) {
            devDependencies.put(devDependency.getArtifactId(), devDependency.getVersion());
        }
        addNpmDependencies(devDependencies, npmTestDependencies);
        packageJson.put("devDependencies", devDependencies);

        JSONObject scripts = new JSONObject();
        scripts.put("test", "mocha -u exports -R xunit-file --recursive");
        scripts.put("coverage", "mocha -u exports -R mocha-lcov-reporter-file --recursive");
        packageJson.put("scripts", scripts);

        Writer w = new FileWriter(packageJsonFile);
        w.write(packageJson.toString());
        w.flush();
        w.close();
    } catch (IOException e) {
        throw new MojoExecutionException("Could not write package.json to " + packageJsonFile.getAbsolutePath(),
                e);
    }
}

From source file:com.flexive.faces.javascript.menu.DojoMenuWriter.java

@Override
public void writeEventSubscriptions(Writer out) throws IOException {
    for (Map.Entry<String, String> entry : engageSubscriptions.entrySet()) {
        out.write("dojo.event.topic.subscribe(dojo.widget.byId('" + entry.getKey() + "').eventNames.engage, "
                + entry.getValue() + ");\n");
        //            out.write("dojo.widget.byId('" + entry.getKey() + "').onClick = " + entry.getValue() + ";\n");
    }/*from  w  w w  . jav a2s  .c  o m*/
}

From source file:com.boundlessgeo.geoserver.json.JSONArr.java

@Override
void write(Writer out) throws IOException {
    if (raw == null) {
        out.write("null");
    } else {//from w w w.  j a v a2 s .  co  m
        boolean first = true;
        Iterator iter = iterator();
        out.write('[');
        while (iter.hasNext()) {
            if (first)
                first = false;
            else
                out.write(',');

            Object value = iter.next();
            if (value == null) {
                out.write("null");
                continue;
            }
            value = wrapOrSelf(value);
            JSONWrapper.write(value, out);
        }
        out.write(']');

    }
    out.flush();
}

From source file:edu.cornell.mannlib.vitro.webapp.controller.edit.MenuManagementEdit.java

private void sendReorderResponse(String errorMessage, HttpServletResponse resp) {
    try {/*from w w w. j  a  v  a  2  s .  c  om*/
        JSONObject rObj = new JSONObject();
        resp.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");

        if (errorMessage != null && !errorMessage.isEmpty()) {
            rObj.put("errorMessage", errorMessage);
            resp.setStatus(500 /*HttpURLConnection.HTTP_SERVER_ERROR*/);
        } else {
            rObj.put("errorMessage", "");
        }
        Writer writer = resp.getWriter();
        writer.write(rObj.toString());
    } catch (Exception ex) {
        log.error("Error creating JSON object for response", ex);
    }
}

From source file:com.soulgalore.crawler.run.CrawlAndVerifyAssetsToCsv.java

private void crawl() {
    final Injector injector = Guice.createInjector(new CrawlModule());
    final Crawler crawler = injector.getInstance(Crawler.class);

    final StringBuilder builder = new StringBuilder();
    builder.append("URL,parent,error\n");

    final CrawlerResult result = crawler.getUrls(getConfiguration());
    System.out.println("Crawled  " + result.getVerifiedURLResponses().size() + " pages");

    System.out.println("Start verify assets ...");
    AssetsVerifier verifier = injector.getInstance(AssetsVerifier.class);
    AssetsVerificationResult assetsResult = verifier.verify(result.getVerifiedURLResponses(),
            getConfiguration());/*from   w ww . j a  va 2 s. c  o  m*/

    System.out.println(assetsResult.getWorkingAssets().size() + " assets is ok, "
            + assetsResult.getNonWorkingAssets().size() + " is not");

    for (AssetResponse resp : assetsResult.getNonWorkingAssets()) {
        builder.append(resp.getUrl()).append(",").append(resp.getReferer()).append(",")
                .append(StatusCode.toFriendlyName(resp.getResponseCode())).append("\n");
    }

    Writer out = null;
    try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName), "UTF-8"));
        out.write(builder.toString());
    } catch (Exception e) {
        // TODO Auto-generated catch block
        System.err.println(e);
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                System.err.println(e);
            }
    }

    crawler.shutdown();
    verifier.shutdown();
}

From source file:de.iteratec.iteraplan.presentation.tags.StringEscapeUtilsFunction.java

public static void unescapeJava(Writer out, String str) throws IOException {
    if (out == null) {
        throw new IllegalArgumentException("The Writer must not be null");
    }//from ww  w  .ja  v a2  s  .c o  m
    if (str == null) {
        return;
    }
    int sz = str.length();
    StrBuilder unicode = new StrBuilder(4);
    boolean hadSlash = false;
    boolean inUnicode = false;
    for (int i = 0; i < sz; i++) {
        char ch = str.charAt(i);
        if (inUnicode) {
            // if in unicode, then we're reading unicode
            // values in somehow
            unicode.append(ch);
            if (unicode.length() == 4) {
                // unicode now contains the four hex digits
                // which represents our unicode character
                try {
                    int value = Integer.parseInt(unicode.toString(), 16);
                    out.write((char) value);
                    unicode.setLength(0);
                    inUnicode = false;
                    hadSlash = false;
                } catch (NumberFormatException nfe) {
                    throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe);
                }
            }
            continue;
        }
        if (hadSlash) {
            hadSlash = false;
            switch (ch) {
            case '\\':
                out.write('\\');
                break;
            case '\'':
                out.write('\'');
                break;
            case '\"':
                out.write('"');
                break;
            case 'r':
                out.write('\r');
                break;
            case 'f':
                out.write('\f');
                break;
            case 't':
                out.write('\t');
                break;
            case 'n':
                out.write('\n');
                break;
            case 'b':
                out.write('\b');
                break;
            case 'u': {
                inUnicode = true;
                break;
            }
            default:
                out.write(ch);
                break;
            }
            continue;
        } else if (ch == '\\') {
            hadSlash = true;
            continue;
        }
        out.write(ch);
    }
    if (hadSlash) {
        out.write('\\');
    }
}

From source file:com.netxforge.oss2.config.ChartConfigFactory.java

/** {@inheritDoc} */
protected void saveXml(String xml) throws IOException {
    if (xml != null) {
        Writer fileWriter = new OutputStreamWriter(new FileOutputStream(m_chartConfigFile), "UTF-8");
        fileWriter.write(xml);
        fileWriter.flush();//ww  w  .  j a va 2  s.  c  o m
        fileWriter.close();
    }
}