Java Code Examples for java.io.StringWriter#write()

The following examples show how to use java.io.StringWriter#write() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: NamenodeAnalyticsMethods.java    From NNAnalytics with Apache License 2.0 6 votes vote down vote up
/**
 * FETCHNAMESPACE endpoint is an admin-level endpoint meant to fetch a fresh, up-to-date, FSImage
 * from the active cluster.
 */
@GET
@Path("/fetchNamespace")
@Produces({MediaType.TEXT_PLAIN})
public Response fetchNamespace() {
  final NameNodeLoader nnLoader = (NameNodeLoader) context.getAttribute(NNA_NN_LOADER);
  StringWriter writer = new StringWriter();
  try {
    before();
    writer.write("Attempting to bootstrap namespace.<br />");
    try {
      TransferFsImageWrapper transferFsImage = new TransferFsImageWrapper(nnLoader);
      transferFsImage.downloadMostRecentImage();
      writer.write(
          "Done.<br />Please reload by going to `/reloadNamespace` "
              + "or by `service nn-analytics restart` on command line.");
    } catch (Throwable e) {
      writer.write("Bootstrap failed: " + e);
    }
    return Response.ok(writer.toString(), MediaType.TEXT_PLAIN).build();
  } catch (Exception ex) {
    return handleException(ex);
  } finally {
    after();
  }
}
 
Example 2
Source File: PemJwksURLConnection.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
@Override
public void connect() throws IOException {
    InputStream is = getInputStream();
    if(is == null) {
        throw new FileNotFoundException(path);
    }
    content = new StringWriter();
    try(BufferedReader reader = new BufferedReader(new InputStreamReader(is))) {
        String line = reader.readLine();
        while(line != null) {
            content.write(line);
            content.write('\n');
            line = reader.readLine();
        }
    }
}
 
Example 3
Source File: Util.java    From letv with Apache License 2.0 6 votes vote down vote up
static String readFully(Reader reader) throws IOException {
    try {
        StringWriter writer = new StringWriter();
        char[] buffer = new char[1024];
        while (true) {
            int count = reader.read(buffer);
            if (count == -1) {
                break;
            }
            writer.write(buffer, 0, count);
        }
        String stringWriter = writer.toString();
        return stringWriter;
    } finally {
        reader.close();
    }
}
 
Example 4
Source File: AlipayMobilePublicMultiMediaClient.java    From pay with Apache License 2.0 6 votes vote down vote up
private static String getStreamAsString(InputStream stream, String charset) throws IOException {
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream, charset));
        StringWriter writer = new StringWriter();

        char[] chars = new char[256];
        int count = 0;
        while ((count = reader.read(chars)) > 0) {
            writer.write(chars, 0, count);
        }

        return writer.toString();
    } finally {
        if (stream != null) {
            stream.close();
        }
    }
}
 
Example 5
Source File: SimpleTokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 6 votes vote down vote up
/**
 * Read a classpath resource into a string and return it.
 * @param resName - classpath resource name
 * @return the resource content as a string
 * @throws IOException - on failure
 */
public static String readResource(String resName) throws IOException {
    // Strip any classpath: prefix
    if(resName.startsWith("classpath:")) {
        resName = resName.substring(10);
    }
    InputStream is = SimpleTokenUtils.class.getResourceAsStream(resName);
    StringWriter sw = new StringWriter();
    try(BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        String line = br.readLine();
        while(line != null) {
            sw.write(line);
            sw.write('\n');
            line = br.readLine();
        }
    }
    return sw.toString();
}
 
Example 6
Source File: PublicKeyAsJWKTest.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Create a CDI aware base web application archive that includes an embedded JWKS public key
 * that is included as the mp.jwt.verify.publickey property.
 * The root url is /jwks
 * @return the base base web application archive
 * @throws IOException - on resource failure
 */
@Deployment(name = "jwk")
public static WebArchive createDeploymentJWK() throws IOException {
    // Read in the JWKS
    URL publicKey = PublicKeyAsJWKTest.class.getResource("/signer-key4k.jwk");
    StringWriter jwksContents = new StringWriter();
    try (BufferedReader reader = new BufferedReader(new InputStreamReader(publicKey.openStream()))) {
        String line = reader.readLine();
        while (line != null) {
            jwksContents.write(line);
            line = reader.readLine();
        }
    }
    // Setup the microprofile-config.properties content
    Properties configProps = new Properties();
    System.out.printf("jwk: %s\n", jwksContents.toString());
    configProps.setProperty(VERIFIER_PUBLIC_KEY, jwksContents.toString());
    configProps.setProperty(ISSUER, TCKConstants.TEST_ISSUER);
    StringWriter configSW = new StringWriter();
    configProps.store(configSW, "PublicKeyAsJWKTest JWK microprofile-config.properties");
    StringAsset configAsset = new StringAsset(configSW.toString());

    WebArchive webArchive = ShrinkWrap
        .create(WebArchive.class, "PublicKeyAsJWKTest.war")
        .addAsManifestResource(new StringAsset(MpJwtTestVersion.MPJWT_V_1_1.name()), MpJwtTestVersion.MANIFEST_NAME)
        .addAsResource(publicKey, "/signer-keyset4k.jwk")
        .addClass(PublicKeyEndpoint.class)
        .addClass(JwksApplication.class)
        .addClass(SimpleTokenUtils.class)
        .addAsWebInfResource("beans.xml", "beans.xml")
        .addAsManifestResource(configAsset, "microprofile-config.properties")
        ;
    System.out.printf("WebArchive: %s\n", webArchive.toString(true));
    return webArchive;
}
 
Example 7
Source File: TokenUtils.java    From microprofile-jwt-auth with Apache License 2.0 5 votes vote down vote up
/**
 * Read a classpath resource into a string and return it.
 * @param resName - classpath resource name
 * @return the resource content as a string
 * @throws IOException - on failure
 */
public static String readResource(String resName) throws IOException {
    InputStream is = TokenUtils.class.getResourceAsStream(resName);
    StringWriter sw = new StringWriter();
    try(BufferedReader br = new BufferedReader(new InputStreamReader(is))) {
        String line = br.readLine();
        while(line != null) {
            sw.write(line);
            sw.write('\n');
            line = br.readLine();
        }
    }
    return sw.toString();
}
 
Example 8
Source File: V8SuspendAndChangeTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private String readChangedContent() throws IOException {
    InputStream changedFileSource = V8DebugTest.class.getResourceAsStream(TEST_FILE_CHANGING2);
    BufferedReader br = new BufferedReader(new InputStreamReader(changedFileSource));
    StringWriter sw = new StringWriter();
    String line;
    while ((line = br.readLine()) != null) {
        sw.write(line);
    }
    sw.close();
    return sw.toString();
}
 
Example 9
Source File: InterOperableNamingImpl.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/** Encodes the string according to RFC 2396 IETF spec required by INS.
 */
private String encode( String stringToEncode ) {
    StringWriter theStringAfterEscape = new StringWriter();
    int byteCount = 0;
    for( int i = 0; i < stringToEncode.length(); i++ )
    {
        char c = stringToEncode.charAt( i ) ;
        if( Character.isLetterOrDigit( c ) ) {
            theStringAfterEscape.write( c );
        }
        // Do no Escape for characters in this list
        // RFC 2396
        else if((c == ';') || (c == '/') || (c == '?')
        || (c == ':') || (c == '@') || (c == '&') || (c == '=')
        || (c == '+') || (c == '$') || (c == ';') || (c == '-')
        || (c == '_') || (c == '.') || (c == '!') || (c == '~')
        || (c == '*') || (c == ' ') || (c == '(') || (c == ')') )
        {
            theStringAfterEscape.write( c );
        }
        else {
            // Add escape
            theStringAfterEscape.write( '%' );
            String hexString = Integer.toHexString( (int) c );
            theStringAfterEscape.write( hexString );
        }
    }
    return theStringAfterEscape.toString();
}
 
Example 10
Source File: ClassSelector.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Copies a schema fragment into the javadoc of the generated class.
 */
private void addSchemaFragmentJavadoc( CClassInfo bean, XSComponent sc ) {

    // first, pick it up from <documentation> if any.
    String doc = builder.getBindInfo(sc).getDocumentation();
    if(doc!=null)
        append(bean, doc);

    // then the description of where this component came from
    Locator loc = sc.getLocator();
    String fileName = null;
    if(loc!=null) {
        fileName = loc.getPublicId();
        if(fileName==null)
            fileName = loc.getSystemId();
    }
    if(fileName==null)  fileName="";

    String lineNumber=Messages.format( Messages.JAVADOC_LINE_UNKNOWN);
    if(loc!=null && loc.getLineNumber()!=-1)
        lineNumber = String.valueOf(loc.getLineNumber());

    String componentName = sc.apply( new ComponentNameFunction() );
    String jdoc = Messages.format( Messages.JAVADOC_HEADING, componentName, fileName, lineNumber );
    append(bean,jdoc);

    // then schema fragment
    StringWriter out = new StringWriter();
    out.write("<pre>\n");
    SchemaWriter sw = new SchemaWriter(new JavadocEscapeWriter(out));
    sc.visit(sw);
    out.write("</pre>");
    append(bean,out.toString());
}
 
Example 11
Source File: DiskLruCache.java    From graphics-samples with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the remainder of 'reader' as a string, closing it when done.
 */
public static String readFully(Reader reader) throws IOException {
    try {
        StringWriter writer = new StringWriter();
        char[] buffer = new char[1024];
        int count;
        while ((count = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, count);
        }
        return writer.toString();
    } finally {
        reader.close();
    }
}
 
Example 12
Source File: ClassSelector.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Copies a schema fragment into the javadoc of the generated class.
 */
private void addSchemaFragmentJavadoc( CClassInfo bean, XSComponent sc ) {

    // first, pick it up from <documentation> if any.
    String doc = builder.getBindInfo(sc).getDocumentation();
    if(doc!=null)
        append(bean, doc);

    // then the description of where this component came from
    Locator loc = sc.getLocator();
    String fileName = null;
    if(loc!=null) {
        fileName = loc.getPublicId();
        if(fileName==null)
            fileName = loc.getSystemId();
    }
    if(fileName==null)  fileName="";

    String lineNumber=Messages.format( Messages.JAVADOC_LINE_UNKNOWN);
    if(loc!=null && loc.getLineNumber()!=-1)
        lineNumber = String.valueOf(loc.getLineNumber());

    String componentName = sc.apply( new ComponentNameFunction() );
    String jdoc = Messages.format( Messages.JAVADOC_HEADING, componentName, fileName, lineNumber );
    append(bean,jdoc);

    // then schema fragment
    StringWriter out = new StringWriter();
    out.write("<pre>\n");
    SchemaWriter sw = new SchemaWriter(new JavadocEscapeWriter(out));
    sc.visit(sw);
    out.write("</pre>");
    append(bean,out.toString());
}
 
Example 13
Source File: Streams.java    From FireFiles with Apache License 2.0 5 votes vote down vote up
/**
 * Returns the remainder of 'reader' as a string, closing it when done.
 */
public static String readFully(Reader reader) throws IOException {
    try {
        StringWriter writer = new StringWriter();
        char[] buffer = new char[1024];
        int count;
        while ((count = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, count);
        }
        return writer.toString();
    } finally {
        reader.close();
    }
}
 
Example 14
Source File: DiskLruCache.java    From android-source-codes with Creative Commons Attribution 4.0 International 5 votes vote down vote up
/**
 * Returns the remainder of 'reader' as a string, closing it when done.
 */
public static String readFully(Reader reader) throws IOException {
    try {
        StringWriter writer = new StringWriter();
        char[] buffer = new char[1024];
        int count;
        while ((count = reader.read(buffer)) != -1) {
            writer.write(buffer, 0, count);
        }
        return writer.toString();
    } finally {
        reader.close();
    }
}
 
Example 15
Source File: ProductInformationPanel.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private static String getCopyrightText () {
    
    String copyrighttext = NbBundle.getMessage(ProductInformationPanel.class, "LBL_Copyright", FONT_SIZE); // NOI18N
    
    FileObject licenseFolder = FileUtil.getConfigFile("About/Licenses");   // NOI18N
    if (licenseFolder != null) {
        FileObject[] foArray = licenseFolder.getChildren();
        if (foArray.length > 0) {
            String curLicense;
            boolean isSomeLicense = false;
            StringWriter sw = new StringWriter();
            for (int i = 0; i < foArray.length; i++) {
                curLicense = loadLicenseText(foArray[i]);
                if (curLicense != null) {
                    sw.write("<br>" + MessageFormat.format( // NOI18N
                        NbBundle.getBundle(ProductInformationPanel.class).getString("LBL_AddOnCopyright"), // NOI18N
                        new Object[] { curLicense, FONT_SIZE }));
                    isSomeLicense = true;
                }
            }
            if (isSomeLicense) {
                copyrighttext += sw.toString();
            }
        }
    }
    
    return copyrighttext;
}
 
Example 16
Source File: ConfigurationExporterTest.java    From apm-agent-java with Apache License 2.0 5 votes vote down vote up
static String renderDocumentation(ConfigurationRegistry configurationRegistry) throws IOException, TemplateException {
    Configuration cfg = new Configuration(Configuration.VERSION_2_3_27);
    cfg.setClassLoaderForTemplateLoading(ConfigurationExporterTest.class.getClassLoader(), "/");
    cfg.setDefaultEncoding("UTF-8");
    cfg.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
    cfg.setLogTemplateExceptions(false);

    Template temp = cfg.getTemplate("configuration.asciidoc.ftl");
    StringWriter tempRenderedFile = new StringWriter();
    tempRenderedFile.write("////\n" +
        "This file is auto generated\n" +
        "\n" +
        "Please only make changes in configuration.asciidoc.ftl\n" +
        "////\n");
    final List<ConfigurationOption<?>> nonInternalOptions = configurationRegistry.getConfigurationOptionsByCategory()
        .values()
        .stream()
        .flatMap(List::stream)
        .filter(option -> !option.getTags().contains("internal"))
        .collect(Collectors.toList());
    final Map<String, List<ConfigurationOption<?>>> optionsByCategory = nonInternalOptions.stream()
        .collect(Collectors.groupingBy(ConfigurationOption::getConfigurationCategory, TreeMap::new, Collectors.toList()));
    temp.process(Map.of(
        "config", optionsByCategory,
        "keys", nonInternalOptions.stream().map(ConfigurationOption::getKey).sorted().collect(Collectors.toList())
    ), tempRenderedFile);

    // re-process the rendered template to resolve the ${allInstrumentationGroupNames} placeholder
    StringWriter out = new StringWriter();
    new Template("", tempRenderedFile.toString(), cfg)
        .process(Map.of("allInstrumentationGroupNames", getAllInstrumentationGroupNames()), out);

    return out.toString();
}
 
Example 17
Source File: ClassSelector.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Copies a schema fragment into the javadoc of the generated class.
 */
private void addSchemaFragmentJavadoc( CClassInfo bean, XSComponent sc ) {

    // first, pick it up from <documentation> if any.
    String doc = builder.getBindInfo(sc).getDocumentation();
    if(doc!=null)
        append(bean, doc);

    // then the description of where this component came from
    Locator loc = sc.getLocator();
    String fileName = null;
    if(loc!=null) {
        fileName = loc.getPublicId();
        if(fileName==null)
            fileName = loc.getSystemId();
    }
    if(fileName==null)  fileName="";

    String lineNumber=Messages.format( Messages.JAVADOC_LINE_UNKNOWN);
    if(loc!=null && loc.getLineNumber()!=-1)
        lineNumber = String.valueOf(loc.getLineNumber());

    String componentName = sc.apply( new ComponentNameFunction() );
    String jdoc = Messages.format( Messages.JAVADOC_HEADING, componentName, fileName, lineNumber );
    append(bean,jdoc);

    // then schema fragment
    StringWriter out = new StringWriter();
    out.write("<pre>\n");
    SchemaWriter sw = new SchemaWriter(new JavadocEscapeWriter(out));
    sc.visit(sw);
    out.write("</pre>");
    append(bean,out.toString());
}
 
Example 18
Source File: KullaTesting.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public String diagnosticsToString(List<Diag> diagnostics) {
    StringWriter writer = new StringWriter();
    for (Diag diag : diagnostics) {
        writer.write("Error --\n");
        for (String line : diag.getMessage(null).split("\\r?\\n")) {
            writer.write(String.format("%s\n", line));
        }
    }
    return writer.toString().replace("\n", System.lineSeparator());
}
 
Example 19
Source File: CssLinkResourceTransformer.java    From lams with GNU General Public License v2.0 4 votes vote down vote up
@Override
public Resource transform(HttpServletRequest request, Resource resource, ResourceTransformerChain transformerChain)
		throws IOException {

	resource = transformerChain.transform(request, resource);

	String filename = resource.getFilename();
	if (!"css".equals(StringUtils.getFilenameExtension(filename))) {
		return resource;
	}

	if (logger.isTraceEnabled()) {
		logger.trace("Transforming resource: " + resource);
	}

	byte[] bytes = FileCopyUtils.copyToByteArray(resource.getInputStream());
	String content = new String(bytes, DEFAULT_CHARSET);

	Set<CssLinkInfo> infos = new HashSet<CssLinkInfo>(8);
	for (CssLinkParser parser : this.linkParsers) {
		parser.parseLink(content, infos);
	}

	if (infos.isEmpty()) {
		if (logger.isTraceEnabled()) {
			logger.trace("No links found.");
		}
		return resource;
	}

	List<CssLinkInfo> sortedInfos = new ArrayList<CssLinkInfo>(infos);
	Collections.sort(sortedInfos);

	int index = 0;
	StringWriter writer = new StringWriter();
	for (CssLinkInfo info : sortedInfos) {
		writer.write(content.substring(index, info.getStart()));
		String link = content.substring(info.getStart(), info.getEnd());
		String newLink = null;
		if (!hasScheme(link)) {
			newLink = resolveUrlPath(link, request, resource, transformerChain);
		}
		if (logger.isTraceEnabled()) {
			if (newLink != null && !link.equals(newLink)) {
				logger.trace("Link modified: " + newLink + " (original: " + link + ")");
			}
			else {
				logger.trace("Link not modified: " + link);
			}
		}
		writer.write(newLink != null ? newLink : link);
		index = info.getEnd();
	}
	writer.write(content.substring(index));

	return new TransformedResource(resource, writer.toString().getBytes(DEFAULT_CHARSET));
}
 
Example 20
Source File: GalleryData.java    From NClientV2 with Apache License 2.0 4 votes vote down vote up
private void writeInterval(StringWriter writer,int intervalLen,ImageExt referencePage){
    writer.write(Integer.toString(intervalLen));
    writer.write(Page.extToChar(referencePage));
}