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

The following examples show how to use java.io.StringWriter#close() . 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: TestHyrax.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String ncdumpmetadata(NetcdfDataset ncfile, String datasetname) throws Exception {
  StringWriter sw = new StringWriter();

  StringBuilder args = new StringBuilder("-strict");
  if (datasetname != null) {
    args.append(" -datasetname ");
    args.append(datasetname);
  }
  // Print the meta-databuffer using these args to NcdumpW
  try {
    if (!ucar.nc2.NCdumpW.print(ncfile, args.toString(), sw, null))
      throw new Exception("NcdumpW failed");
  } catch (IOException ioe) {
    throw new Exception("NcdumpW failed", ioe);
  }
  sw.close();
  return sw.toString();
}
 
Example 2
Source File: TestCDMClient.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String dumpmetadata(NetcdfDataset ncfile, String datasetname) throws Exception {
  StringWriter sw = new StringWriter();
  StringBuilder args = new StringBuilder("-strict");
  if (datasetname != null) {
    args.append(" -datasetname ");
    args.append(datasetname);
  }
  // Print the meta-databuffer using these args to NcdumpW
  try {
    if (!ucar.nc2.NCdumpW.print(ncfile, args.toString(), sw, null))
      throw new Exception("NcdumpW failed");
  } catch (IOException ioe) {
    throw new Exception("NcdumpW failed", ioe);
  }
  sw.close();
  return sw.toString();
}
 
Example 3
Source File: TemplateCommentGenerator.java    From mybatis-generator-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 获取评论
 * @param map  模板参数
 * @param node 节点ID
 * @return
 */
private String[] getComments(Map<String, Object> map, EnumNode node) {
    // 1. 模板引擎解析
    try {
        StringWriter stringWriter = new StringWriter();
        Template template = templates.get(node);
        if (template != null) {
            template.process(map, stringWriter);

            String comment = stringWriter.toString();
            stringWriter.close();

            // 需要先清理字符串
            return comment.replaceFirst("^[\\s\\t\\r\\n]*", "").replaceFirst("[\\s\\t\\r\\n]*$", "").split("\n");
        }

    } catch (Exception e) {
        logger.error("freemarker 解析失败!", e);
    }

    return null;
}
 
Example 4
Source File: TestConstraints.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String ncdumpmetadata(NetcdfDataset ncfile, String datasetname) {
  boolean ok = false;
  String metadata = null;
  StringWriter sw = new StringWriter();
  StringBuilder args = new StringBuilder("-strict");
  if (datasetname != null) {
    args.append(" -datasetname ");
    args.append(datasetname);
  }
  // Print the meta-databuffer using these args to NcdumpW
  ok = false;
  try {
    ok = ucar.nc2.NCdumpW.print(ncfile, args.toString(), sw, null);
  } catch (IOException ioe) {
    ioe.printStackTrace();
    ok = false;
  }
  try {
    sw.close();
  } catch (IOException e) {
  } ;
  if (!ok) {
    System.err.println("NcdumpW failed");
  }
  return sw.toString();
}
 
Example 5
Source File: TdsErrorHandling.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@ExceptionHandler(Throwable.class)
public ResponseEntity<String> handle(Throwable ex) throws Throwable {
  // If the exception is annotated with @ResponseStatus rethrow it and let
  // the framework handle it - like the OrderNotFoundException example
  // at the start of this post.
  // AnnotationUtils is a Spring Framework utility class.
  // see https://spring.io/blog/2013/11/01/exception-handling-in-spring-mvc
  if (AnnotationUtils.findAnnotation(ex.getClass(), ResponseStatus.class) != null)
    throw ex;

  logger.error("uncaught exception", ex);
  // ex.printStackTrace(); // temporary - remove in production

  HttpHeaders responseHeaders = new HttpHeaders();
  responseHeaders.setContentType(MediaType.TEXT_PLAIN);
  String msg = ex.getMessage();
  StringWriter sw = new StringWriter();
  PrintWriter p = new PrintWriter(sw);
  ex.printStackTrace(p);
  p.close();
  sw.close();
  msg = sw.toString();
  return new ResponseEntity<>("Throwable exception handled : " + htmlEscape(msg), responseHeaders,
      HttpStatus.INTERNAL_SERVER_ERROR);
}
 
Example 6
Source File: SecurityTest.java    From powsybl-core with Mozilla Public License 2.0 6 votes vote down vote up
@Test
public void printPostContingencyViolationsWithPreContingencyViolationsFiltering() throws Exception {
    StringWriter writer = new StringWriter();
    try {
        Security.printPostContingencyViolations(result, network, writer, formatterFactory, formatterConfig, null, true);
    } finally {
        writer.close();
    }
    assertEquals(String.join(System.lineSeparator(),
                             "Post-contingency limit violations",
                             "Contingency,Status,Action,Equipment (1),End,Country,Base voltage,Violation type,Violation name,Value,Limit,abs(value-limit),Loading rate %",
                             "contingency1,converge,,Equipment (1),,,,,,,,,",
                             ",,action2,,,,,,,,,,",
                             ",,,NHV1_NHV2_2,VLHV1,FR,380,CURRENT,Permanent limit,950.0000,855.0000,95.0000,105.56"),
                 writer.toString().trim());
}
 
Example 7
Source File: TestCDMClient.java    From tds with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
String dumpmetadata(NetcdfDataset ncfile, String datasetname) throws Exception {
  StringWriter sw = new StringWriter();
  StringBuilder args = new StringBuilder("-strict");
  if (datasetname != null) {
    args.append(" -datasetname ");
    args.append(datasetname);
  }
  // Print the meta-databuffer using these args to NcdumpW
  try {
    if (!ucar.nc2.NCdumpW.print(ncfile, args.toString(), sw, null))
      throw new Exception("NcdumpW failed");
  } catch (IOException ioe) {
    throw new Exception("NcdumpW failed", ioe);
  }
  sw.close();
  return sw.toString();
}
 
Example 8
Source File: StacktraceHelper.java    From litho with Apache License 2.0 6 votes vote down vote up
/**
 * Format a stack trace in a human-readable format.
 *
 * @param throwable The exception/throwable whose stack trace to format.
 */
@Nullable
public static String formatStacktrace(Throwable throwable) {
  final StringWriter stringWriter = new StringWriter();
  final PrintWriter printWriter = new PrintWriter(stringWriter);
  String output = null;
  try {
    throwable.printStackTrace(printWriter);
  } finally {
    printWriter.close();
    try {
      output = stringWriter.toString();
      stringWriter.close();
    } catch (final IOException ignored) {
      // This would mean that closing failed which doesn't concern us.
    }
  }

  return output;
}
 
Example 9
Source File: Generator.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public void generateDMR(DapDataset dmr) throws DapException {
  try {
    StringWriter sw = new StringWriter();
    PrintWriter pw = new PrintWriter(sw);
    DMRPrinter dp = new DMRPrinter(dmr, this.ce, pw, null);
    dp.print();
    pw.close();
    sw.close();
    String tmp = sw.toString();
    this.cw.cacheDMR(tmp);
    this.cw.flush();
  } catch (Exception e) {
    throw new DapException(e);
  }
}
 
Example 10
Source File: VelocityUtil.java    From java-tutorial with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static String getMergeOutput(VelocityContext context, String templateName) {
	Template template = velocityEngine.getTemplate(templateName);

	StringWriter sw = new StringWriter();
	template.merge(context, sw);
	String output = sw.toString();
	try {
		sw.close();
	} catch (IOException e) {
		e.printStackTrace();
	}
	return output;
}
 
Example 11
Source File: TestDSP.java    From tds with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
String dumpdata(DSP dsp) throws Exception {
  StringWriter sw = new StringWriter();
  PrintWriter pw = new PrintWriter(sw);
  // Print the meta-databuffer using these args to NcdumpW
  DSPPrinter p = new DSPPrinter(dsp, pw).flag(DSPPrinter.Flags.CONTROLCHAR);
  p.print();
  pw.close();
  sw.close();
  return sw.toString();
}
 
Example 12
Source File: ToolUtil.java    From MeetingFilm with Apache License 2.0 5 votes vote down vote up
/**
 * 获取异常的具体信息
 *
 * @author fengshuonan
 * @Date 2017/3/30 9:21
 * @version 2.0
 */
public static String getExceptionMsg(Exception e) {
    StringWriter sw = new StringWriter();
    try {
        e.printStackTrace(new PrintWriter(sw));
    } finally {
        try {
            sw.close();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
    return sw.getBuffer().toString().replaceAll("\\$", "T");
}
 
Example 13
Source File: PaymentFactory.java    From MicroCommunity with Apache License 2.0 5 votes vote down vote up
/**
     * Map转换为 Xml
     *
     * @return Xml
     * @throws Exception
     */
    public static String mapToXml(SortedMap<String, String> map) throws Exception {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
//防止XXE攻击
        documentBuilderFactory.setXIncludeAware(false);
        documentBuilderFactory.setExpandEntityReferences(false);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        org.w3c.dom.Document document = documentBuilder.newDocument();
        org.w3c.dom.Element root = document.createElement("xml");
        document.appendChild(root);
        for (String key : map.keySet()) {
            String value = map.get(key);
            if (value == null) {
                value = "";
            }
            value = value.trim();
            org.w3c.dom.Element filed = document.createElement(key);
            filed.appendChild(document.createTextNode(value));
            root.appendChild(filed);
        }
        TransformerFactory tf = TransformerFactory.newInstance();
        Transformer transformer = tf.newTransformer();
        DOMSource source = new DOMSource(document);
        transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
        transformer.setOutputProperty(OutputKeys.INDENT, "yes");
        StringWriter writer = new StringWriter();
        StreamResult result = new StreamResult(writer);
        transformer.transform(source, result);
        String output = writer.getBuffer().toString();
        try {
            writer.close();
        } catch (Exception ex) {
        }
        return output;
    }
 
Example 14
Source File: JSON.java    From dubbox with Apache License 2.0 5 votes vote down vote up
/**
 * json string.
 * 
 * @param obj object.
 * @return json string.
 * @throws IOException.
 */
public static String json(Object obj) throws IOException
{
	if( obj == null ) return NULL;
	StringWriter sw = new StringWriter();
	try
	{
		json(obj, sw);
		return sw.getBuffer().toString();
	}
	finally{ sw.close(); }
}
 
Example 15
Source File: JSON.java    From dubbo-2.6.5 with Apache License 2.0 5 votes vote down vote up
/**
 * json string.
 *
 * @param obj        object.
 * @param properties property name array.
 * @return json string.
 * @throws IOException
 */
public static String json(Object obj, String[] properties) throws IOException {
    if (obj == null) return NULL;
    StringWriter sw = new StringWriter();
    try {
        json(obj, properties, sw);
        return sw.getBuffer().toString();
    } finally {
        sw.close();
    }
}
 
Example 16
Source File: TestH5Iosp.java    From netcdf-java with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
String ncdumpmetadata(NetcdfDataset ncfile, String datasetname) {
  boolean ok = false;
  String metadata = null;
  StringWriter sw = new StringWriter();

  StringBuilder args = new StringBuilder("-strict");
  if (datasetname != null) {
    args.append(" -datasetname ");
    args.append(datasetname);
  }

  // Print the meta-databuffer using these args to NcdumpW
  ok = false;
  try {
    ok = ucar.nc2.NCdumpW.print(ncfile, args.toString(), sw, null);
  } catch (IOException ioe) {
    ioe.printStackTrace();
    ok = false;
  }
  try {
    sw.close();
  } catch (IOException e) {
  }
  if (!ok) {
    System.err.println("NcdumpW failed");
    System.exit(1);
  }
  return shortenFileName(sw.toString(), ncfile.getLocation());
}
 
Example 17
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 18
Source File: FreemarkerTemplate.java    From extentreports-java with Apache License 2.0 5 votes vote down vote up
private String processTemplate(Template template, Map<String, Object> templateMap)
        throws TemplateException, IOException {
    StringWriter out = new StringWriter();
    template.process(templateMap, out);
    String source = out.toString();
    out.close();
    return source;
}
 
Example 19
Source File: GenerateRaw.java    From tds with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
protected void doOne(TestCase tc) throws Exception {
  String inputpath = tc.inputpath();
  String dappath;
  String dmrpath;
  if (USEDAPDMR) {
    dappath = tc.generatepath(DAPDIR) + ".dap";
    dmrpath = tc.generatepath(DMRDIR) + ".dmr";
  } else {
    dappath = tc.generatepath(RAWDIR) + ".dap";
    dmrpath = tc.generatepath(RAWDIR) + ".dmr";
  }

  String url = tc.makeurl();

  String ce = tc.makequery();

  System.err.println("Input: " + inputpath);
  System.err.println("Generated (DMR):" + dmrpath);
  System.err.println("Generated (DAP):" + dappath);
  System.err.println("URL: " + url);
  if (ce != null)
    System.err.println("CE: " + ce);

  if (CEPARSEDEBUG)
    CEParserImpl.setGlobalDebugLevel(1);

  String little = tc.bigendian ? "0" : "1";
  String nocsum = tc.nochecksum ? "1" : "0";
  MvcResult result;
  if (ce == null) {
    result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.ORDERTAG, little, DapTestCommon.NOCSUMTAG, nocsum,
        DapTestCommon.TRANSLATETAG, "nc4");
  } else {
    result = perform(url, this.mockMvc, RESOURCEPATH, DapTestCommon.CONSTRAINTTAG, ce, DapTestCommon.ORDERTAG, little,
        DapTestCommon.NOCSUMTAG, nocsum, DapTestCommon.TRANSLATETAG, "nc4");
  }

  // Collect the output
  MockHttpServletResponse res = result.getResponse();
  byte[] byteresult = res.getContentAsByteArray();

  if (prop_debug || DEBUGDATA) {
    DapDump.dumpbytestream(byteresult, ByteOrder.nativeOrder(), "GenerateRaw");
  }

  // Dump the dap serialization into a file
  if (prop_generate || GENERATE)
    writefile(dappath, byteresult);

  // Dump the dmr into a file by extracting from the dap serialization
  ByteArrayInputStream bytestream = new ByteArrayInputStream(byteresult);
  ChunkInputStream reader = new ChunkInputStream(bytestream, RequestMode.DAP, ByteOrder.nativeOrder());
  String sdmr = reader.readDMR(); // Read the DMR
  if (prop_generate || GENERATE)
    writefile(dmrpath, sdmr);

  if (prop_visual) {
    visual(tc.dataset + ".dmr", sdmr);
    FileDSP src = new FileDSP();
    src.open(byteresult);
    StringWriter writer = new StringWriter();
    DSPPrinter printer = new DSPPrinter(src, writer);
    printer.print();
    printer.close();
    writer.close();
    String sdata = writer.toString();
    visual(tc.dataset + ".dap", sdata);
  }
}
 
Example 20
Source File: SeaRouteWS.java    From searoute with European Union Public License 1.2 4 votes vote down vote up
private void returnRoute(PrintWriter out, double oLon, double oLat, double dLon, double dLat, boolean distP, boolean geomP, SeaRouting sr, boolean allowSuez, boolean allowPanama) {
	try {
		if(oLon==Double.NaN || oLat==Double.NaN){
			out.print("{\"status\":\"error\",\"message\":\"Unknown origin location\"");
			out.print("}");
			return;
		}
		if(dLon==Double.NaN || dLat==Double.NaN){
			out.print("{\"status\":\"error\",\"message\":\"Unknown destination location\"");
			out.print("}");
			return;
		}
		if(oLon==dLon && oLat==dLat){
			out.print("{\"status\":\"empty\"");
			out.print("}");
			return;
		}

		/*/try to find in cache
		st = getFromCache(oLocid, dLocid);
		if(st != null){
			out.print(st);
			return;
		}*/

		//get origin node/positions
		Coordinate oPos = new Coordinate(oLon,oLat);
		Node oN = sr.getNode(oPos);
		//get destination node/positions
		Coordinate dPos = new Coordinate(dLon,dLat);
		Node dN = sr.getNode(dPos);

		if(oN == null || dN == null){
			out.print( "{\"status\":\"error\",\"message\":\"Could not find start/end node\"}" );
			//setInCache(oLocid, dLocid, st);
			return;
		}


		//build the maritime route geometry
		Feature f = sr.getRoute(oPos, oN, dPos, dN, allowSuez, allowPanama);
		Geometry ls = f.getGeometry();
		f = null;


		if(ls==null){
			out.print( "{\"status\":\"error\",\"message\":\"Shortest path not found\"}" );
			//setInCache(oLocid, dLocid, st);
			return;
		}

		String st;
		st = "{\"status\":\"ok\"";
		if(distP){
			double d = GeoDistanceUtil.getLengthGeoKM(ls);
			d = Util.round(d, 2);
			st += ",\"dist\":"+d;
		}
		if(geomP){
			//export as geojson
			st += ",\"geom\":";
			StringWriter writer = new StringWriter();
			new GeometryJSON().write(ls, writer);
			st += writer.toString();
			writer.close();
		}
		st += "}";

		out.print(st);
		//setInCache(oLocid, dLocid, st);

		//improve network / add inland transport / take into account impedance

	} catch (Exception e) {
		out.print("{\"status\":\"error\",\"message\":\"Unknown error\"}");
		//response.setContentType("text/"+ENC_CT);
		//e.printStackTrace();
		//e.printStackTrace(out);
		//out.print(e.getMessage());
		//setInCache(oLocid, dLocid, st);
		e.printStackTrace();
	}
}