List of usage examples for java.io StringWriter append
public StringWriter append(char c)
From source file:org.rascalmpl.library.experiments.Compiler.RVM.Interpreter.help.HelpManager.java
String reportHelp(String[] words, ScoreDoc[] hits) throws IOException { int nhits = hits.length; StringWriter w = new StringWriter(); if (nhits == 0) { stdout.println("No info found"); genPrelude(w);/*from ww w . j av a2 s. co m*/ w.append("<h1 class=\"search-sect0\">No help found for: "); genSearchTerms(words, w); w.append("</h1>\n"); w.append("<div class=\"search-ulist\">\n"); w.append( "<ul><li>Perhaps try <i>help</i>, <i>further reading</i> or <i>introduction</i> as search terms</li>"); w.append("</ul>\n"); w.append("</div>"); w.append("</body>\n"); return w.toString(); } else { genPrelude(w); w.append("<h1 class=\"search-sect0\">Help for: "); genSearchTerms(words, w); w.append("</h1>\n"); w.append("<ul>\n"); for (int i = 0; i < Math.min(hits.length, maxSearch); i++) { Document hitDoc = indexSearcher.doc(hits[i].doc); w.append("<div class=\"search-ulist\">\n"); w.append("<li> "); String name = hitDoc.get("name"); appendHyperlink(w, name); w.append(": <em>").append(escapeHtml(getField(hitDoc, "synopsis"))).append("</em>"); String signature = getField(hitDoc, "signature"); if (!signature.isEmpty()) { w.append("<br>").append("<code>").append(escapeHtml(signature)).append("</code>"); } } w.append("</ul>\n"); w.append("</div>"); w.append("</body>\n"); return w.toString(); } }
From source file:dk.statsbiblioteket.util.CachedCollator.java
/** * @return the cached chars in collator order. *///from w w w. j av a2 s . c om public String getCachedChars() { List<String> chars = new ArrayList<String>(5000); for (int i = 0; i < cachedPositions.length; i++) { if (cachedPositions[i] > 0) { chars.add(Character.toString((char) i)); } } Collections.sort(chars, this); StringWriter sw = new StringWriter(chars.size()); for (String c : chars) { sw.append(c); } return sw.toString(); }
From source file:eu.sisob.uma.restserver.services.gate.GateTask.java
public static boolean launch(String user, String pass, String task_code, String code_task_folder, String email, StringWriter message, boolean verbose, boolean split_by_keyword) { if (message == null) { return false; }//w w w . j a va2 s . c o m boolean success = false; message.getBuffer().setLength(0); File code_task_folder_dir = new File(code_task_folder); File documents_dir = code_task_folder_dir; File csv_data_source_file = FileSystemManager.getFileIfExists(code_task_folder_dir, input_data_source_filename_prefix_csv, input_data_source_filename_ext_csv); boolean validate = csv_data_source_file != null; if (!validate) { success = false; message.write("You have not uploaded any file like this '" + input_data_source_filename_prefix_csv + "*" + input_data_source_filename_ext_csv + "' file"); } else { String middle_data_folder = code_task_folder + File.separator + AuthorizationManager.middle_data_dirname; File middle_data_dir = null; try { middle_data_dir = FileSystemManager.createFileAndIfExistsDelete(middle_data_folder); } catch (Exception ex) { ProjectLogger.LOGGER.error(ex.toString(), ex); message.append("The file couldn't be created " + middle_data_dir.getName() + "\r\n"); } String results_data_folder = code_task_folder + File.separator + AuthorizationManager.results_dirname; File results_data_dir = null; try { results_data_dir = FileSystemManager.createFileAndIfExistsDelete(results_data_folder); } catch (Exception ex) { ProjectLogger.LOGGER.error(ex.toString(), ex); message.append("The file couldn't be created " + results_data_dir.getName() + "\r\n"); } File zip_file = new File(code_task_folder_dir, input_data_documents_in_zip); if (zip_file.exists()) { documents_dir = new File(code_task_folder_dir, AuthorizationManager.middle_data_dirname); if (!ZipUtil.unZipItToSameFolder(zip_file, documents_dir)) { success = false; message.write(input_data_documents_in_zip + " cannot bet unziped"); //FIXME return success; } else { } } RepositoryPreprocessDataMiddleData preprocessedRep = null; try { File verbose_dir = null; if (verbose) { verbose_dir = new File(code_task_folder_dir, AuthorizationManager.verbose_dirname); if (!verbose_dir.exists()) verbose_dir.mkdir(); } HashMap<String, String[]> blocks_and_keywords = null; if (split_by_keyword) { blocks_and_keywords = GateDataExtractorService.getInstance().getBlocksAndKeywords(); } preprocessedRep = GateDataExtractorSingle.createPreprocessRepositoryFromCSVFile( csv_data_source_file, ';', documents_dir, verbose, verbose_dir, split_by_keyword, blocks_and_keywords, middle_data_dir); } catch (Exception ex) { message.append("The format of '" + csv_data_source_file.getName() + "' does not seems be correct. Please check the headers of the csv file (read in the instructions which are optionals) and be sure that the field separators are ';'. Please read the intructions of the task. \r\nAlso check that you have uploaded all the documents referenced in the csv file (if you have upload all the documents compressed in " + input_data_documents_in_zip + " file, please, check that it has all the files referenced in the csv).<br>Message: " + ex.getMessage()); //FIXME ProjectLogger.LOGGER.error(message.toString(), ex); } if (preprocessedRep != null) { H2DBCredentials cred_resolver = GateDataExtractorService.getH2DBCredentials_Resolver(); H2DBCredentials cred_trad = GateDataExtractorService.getH2DBCredentials_Trad_Tables_Academic(); GateDataExtractorTaskInRest task = new GateDataExtractorTaskInRest(preprocessedRep, true, cred_trad, true, cred_resolver, user, pass, task_code, code_task_folder, email); try { GateDataExtractorService.getInstance() .addExecution((new CallbackableTaskExecutionWithResource(task))); success = true; message.write(TheResourceBundle.getString("Jsp Task Executed Msg")); } catch (Exception ex) { success = false; message.write(TheResourceBundle.getString("Jsp Task Executed Error Msg")); ProjectLogger.LOGGER.error(message.toString(), ex); validate = false; } } } return success; }
From source file:dk.statsbiblioteket.util.CachedCollator.java
protected String getBasicChars() { log.trace("geBasicChars called"); try {//from w w w . j ava2 s. c o m return Streams.getUTF8Resource(CHARSTATS); } catch (IOException e) { log.debug("Could not fetch the resource '" + CHARSTATS + "'. Defaulting to 0x20-0xFF"); } int START = 0x20; int END = 0xFF; StringWriter sw = new StringWriter(END - START + 1); for (int i = START; i <= END; i++) { sw.append((char) i); } return sw.toString(); }
From source file:com.espertech.esper.client.scopetest.EPAssertionUtil.java
/** * Compare the property values of events with the expected values, using exact-order semantics. * @param actual provides events/*from w w w. j a v a 2 s .c o m*/ * @param propertyNames array of property names * @param expected expected values * @param streamName an optional name for the stream for use in messages */ public static void assertPropsPerRow(EventBean[] actual, String[] propertyNames, Object[][] expected, String streamName) { if (compareArraySize(expected, actual)) { return; } for (int i = 0; i < expected.length; i++) { Object[] propertiesThisRow = expected[i]; for (int j = 0; j < propertiesThisRow.length; j++) { String name = propertyNames[j]; Object value = propertiesThisRow[j]; Object eventProp = actual[i].get(name); StringWriter writer = new StringWriter(); writer.append("Error asserting property named "); writer.append(name); writer.append(" for row "); writer.append(Integer.toString(i)); if (streamName != null && streamName.trim().length() != 0) { writer.append(" for stream "); writer.append(streamName); } assertEqualsAllowArray(writer.toString(), value, eventProp); } } }
From source file:org.apache.solr.handler.dataimport.PlainTextEntityProcessor.java
@Override public Map<String, Object> nextRow() { if (ended)// ww w.j a va 2s. c o m return null; DataSource<Reader> ds = context.getDataSource(); String url = context.replaceTokens(context.getEntityAttribute(URL)); Reader r = null; try { r = ds.getData(url); } catch (Exception e) { wrapAndThrow(SEVERE, e, "Exception reading url : " + url); } StringWriter sw = new StringWriter(); char[] buf = new char[1024]; while (true) { int len = 0; try { len = r.read(buf); } catch (IOException e) { IOUtils.closeQuietly(r); wrapAndThrow(SEVERE, e, "Exception reading url : " + url); } if (len <= 0) break; sw.append(new String(buf, 0, len)); } Map<String, Object> row = new HashMap<>(); row.put(PLAIN_TEXT, sw.toString()); ended = true; IOUtils.closeQuietly(r); return row; }
From source file:ro.nextreports.engine.util.QueryUtil.java
public List<NameType> executeQueryForDynamicColumn(String sql) throws Exception { StringWriter sw = new StringWriter(100); sw.append(sql); String sqlForHeader = sw.toString(); LOG.info("call for chart dynamic columns = " + sqlForHeader); ResultSet rs = null;//w w w . jav a 2s . co m Statement stmt = null; try { if (isProcedureCall(sqlForHeader)) { Dialect dialect = DialectUtil.getDialect(con); CallableStatement cs = con.prepareCall("{" + sqlForHeader + "}"); stmt = cs; if (dialect.hasProcedureWithCursor()) { cs.registerOutParameter(1, dialect.getCursorSqlType()); } rs = cs.executeQuery(); if (dialect.hasProcedureWithCursor()) { rs = (ResultSet) (cs.getObject(1)); } } else { stmt = con.createStatement(); rs = stmt.executeQuery(sqlForHeader); } ResultSetMetaData rsmd = rs.getMetaData(); int columnCount = rsmd.getColumnCount(); if (columnCount != 2) { throw new QueryException( "Column query must have two data columns : column name and column legend."); } List<NameType> columnNames = new ArrayList<NameType>(); while (rs.next()) { columnNames.add(new NameType(rs.getString(1), rs.getString(2))); } return columnNames; } finally { ConnectionUtil.closeResultSet(rs); ConnectionUtil.closeStatement(stmt); } }
From source file:org.codice.ddf.spatial.ogc.csw.catalog.converter.CswRecordConverter.java
@Override public BinaryContent transform(Metacard metacard, Map<String, Serializable> arguments) throws CatalogTransformerException { StringWriter stringWriter = new StringWriter(); Boolean omitXmlDec = (Boolean) arguments.get(CswConstants.OMIT_XML_DECLARATION); if (omitXmlDec == null || !omitXmlDec) { stringWriter.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n"); }/*from ww w . java2 s . c o m*/ PrettyPrintWriter writer = new PrettyPrintWriter(stringWriter); MarshallingContext context = new TreeMarshaller(writer, null, null); context.put(CswConstants.WRITE_NAMESPACES, true); copyArgumentsToContext(context, arguments); this.marshal(metacard, writer, context); BinaryContent transformedContent = null; ByteArrayInputStream bais = new ByteArrayInputStream( stringWriter.toString().getBytes(StandardCharsets.UTF_8)); transformedContent = new BinaryContentImpl(bais, new MimeType()); return transformedContent; }
From source file:eu.fusepool.p3.proxy.ProxyHandler.java
private void startTransformation(final String resourceUri, final String ldpcUri, final String transformerUri, final byte[] bytes, final Header[] requestHeaders) { (new Thread() { @Override/*from www . ja v a2s. c o m*/ public void run() { Transformer transformer = new TransformerClientImpl(transformerUri); Entity entity = new InputStreamEntity() { @Override public MimeType getType() { try { for (Header h : requestHeaders) { if (h.getName().equalsIgnoreCase("Content-Type")) { return new MimeType(h.getValue()); } } return new MimeType("application/octet-stream"); } catch (MimeTypeParseException ex) { throw new RuntimeException(ex); } } @Override public InputStream getData() throws IOException { return new ByteArrayInputStream(bytes); } @Override public URI getContentLocation() { try { return new URI(resourceUri); } catch (URISyntaxException ex) { throw new RuntimeException(ex); } } }; Entity transformationResult; try { transformationResult = transformer.transform(entity, new MimeType("*/*")); } catch (MimeTypeParseException ex) { throw new RuntimeException(ex); } //final HttpEntity httpEntity = response.getEntity(); //final Header contentTypeHeader = httpEntity.getContentType(); final String contentType = transformationResult.getType().toString(); try { if (isRdf(contentType)) { Graph transformationResultGraph = parser.parse(transformationResult.getData(), contentType); final ByteArrayOutputStream baos = new ByteArrayOutputStream(); serializer.serialize(baos, transformationResultGraph, SupportedFormat.TURTLE); final byte[] bytes = baos.toByteArray(); final StringWriter turtleString = new StringWriter(baos.size() + 2000); turtleString.append(new String(bytes, "UTF-8")); turtleString.append('\n'); turtleString.append("<> " + ELDP.transformedFrom + " <" + resourceUri + "> ."); post(ldpcUri, new ByteArrayEntity(turtleString.toString().getBytes("UTF-8")), "text/turtle", resourceUri, requestHeaders); } else { post(ldpcUri, new org.apache.http.entity.InputStreamEntity(transformationResult.getData()), contentType, resourceUri, requestHeaders); } } catch (IOException ex) { throw new RuntimeException(ex); } } }).start(); }
From source file:nl.knaw.dans.dccd.rest.AbstractProjectResource.java
/** * Construct search result list information as XML String * // w w w. ja v a2 s .c o m * @param searchResults * The results * @param offset * Number of results to skip * @param limit * Number of results in this list * @return The XML String */ protected String getProjectListSearchResultAsXml(SearchResult<? extends DccdSB> searchResults, int offset, int limit) { java.io.StringWriter sw = new StringWriter(); sw.append("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>"); // XML // instruction sw.append("<projects" + " total=\"" + searchResults.getTotalHits() + "\"" + " offset=\"" + offset + "\"" + " limit=\"" + limit + "\"" + ">"); for (SearchHit<? extends DccdSB> hit : searchResults.getHits()) { sw.append("<project>"); appendSearchResultDataAsXml(sw, hit.getData()); sw.append("</project>"); } sw.append("</projects>"); return sw.toString(); }