List of usage examples for java.io PrintWriter append
public PrintWriter append(char c)
From source file:com.clank.launcher.swing.MessageLog.java
/** * Internal method to consume a stream.//from w ww.j a v a 2 s.c om * * @param from stream to consume * @param outputStream console stream to write to */ private void consume(InputStream from, ConsoleOutputStream outputStream) { final InputStream in = from; final PrintWriter out = new PrintWriter(outputStream, true); Thread thread = new Thread(new Runnable() { @Override public void run() { byte[] buffer = new byte[1024]; try { int len; while ((len = in.read(buffer)) != -1) { String s = new String(buffer, 0, len); System.out.print(s); out.append(s); out.flush(); } } catch (IOException e) { } finally { closeQuietly(in); closeQuietly(out); } } }); thread.setDaemon(true); thread.start(); }
From source file:org.kite9.diagram.server.AbstractKite9Controller.java
protected void handleException(Exception ee, OutputStream os) { StringBuilder out = new StringBuilder(); if (ee instanceof SAXParseException) { SAXParseException e = (SAXParseException) ee; out.append("<html><head><title>Validation Error</title></head><body>\n"); out.append("<h1>Validation Error</h1>\n"); out.append("<p>Line: " + e.getLineNumber() + "</p>\n"); out.append("<p>Column: " + e.getColumnNumber() + "</p>\n"); formatMessage(out, e.getMessage()); } else {/* ww w . j a v a2 s . c o m*/ out.append("<html><head><title>XML Error</title></head><body>\n"); out.append("<h1>Validation Error</h1>\n"); formatMessage(out, ee.getMessage()); } PrintWriter psw = new PrintWriter(os); psw.append(out.toString()); psw.append("<h2>Detail: </h2>\n"); psw.append("<pre>/n"); ee.printStackTrace(psw); psw.append("</pre></body></html>"); psw.close(); }
From source file:com.francelabs.datafari.servlets.admin.FieldWeight.java
/** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse * response) Checks if the files still exist Used to modify the weight of * a field// w w w . java 2 s . co m */ @Override protected void doPost(final HttpServletRequest request, final HttpServletResponse response) throws ServletException, IOException { try { if ((config == null) || !new File(env + File.separator + "solrconfig.xml").exists()) {// If // the // files // did // not // existed // when // the // constructor // was // runned if (!new File(env + File.separator + "solrconfig.xml").exists()) { LOGGER.error( "Error while opening the configuration file, solrconfig.xml, in FieldWeight doPost, please make sure this file exists at " + env + "conf/ . Error 69029"); // If // not // an // error // is // printed final PrintWriter out = response.getWriter(); out.append( "Error while opening the configuration file, please retry, if the problem persists contact your system administrator. Error Code : 69029"); out.close(); return; } else { config = new File(env + File.separator + "solrconfig.xml"); } } if (customSearchHandler == null) { if (new File( env + File.separator + "customs_solrconfig" + File.separator + "custom_search_handler.incl") .exists()) { customSearchHandler = new File(env + File.separator + "customs_solrconfig" + File.separator + "custom_search_handler.incl"); } } try { final String type = request.getParameter("type"); if (searchHandler == null) { findSearchHandler(); } if (!usingCustom) { // The custom search handler is not used. // That means that the current config must // be commented in the solrconfig.xml file // and the modifications must be saved in // the custom search handler file // Get the content of solrconfig.xml file as a string String configContent = FileUtils.getFileContent(config); // Retrieve the searchHandler from the configContent final Node originalSearchHandler = XMLUtils.getSearchHandlerNode(config); final String strSearchHandler = XMLUtils.nodeToString(originalSearchHandler); // Create a commented equivalent of the strSearchHandler final String commentedSearchHandler = "<!--" + strSearchHandler + "-->"; // Replace the searchHandler in the solrconfig.xml file by // the commented version configContent = configContent.replace(strSearchHandler, commentedSearchHandler); FileUtils.saveStringToFile(config, configContent); // create the new custom_search_handler document doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument(); // Import the search handler node from the solrconfig doc to // the custom search handler doc searchHandler = doc.importNode(searchHandler, true); // Make the new node an actual item in the target document searchHandler = doc.appendChild(searchHandler); final Node n = run(searchHandler.getChildNodes(), type); childList = n.getParentNode().getChildNodes(); // Save the custom_search_handler.incl file XMLUtils.docToFile(doc, customSearchHandler); } if (childList == null) { final Node n = run(searchHandler.getChildNodes(), type); childList = n.getParentNode().getChildNodes(); } for (int i = 0; i < childList.getLength(); i++) { // Get the str // node final Node n = childList.item(i); if (n.getNodeName().equals("str")) { String name = ""; // Get it's attributes final NamedNodeMap map = n.getAttributes(); for (int j = 0; j < map.getLength(); j++) { if (map.item(j).getNodeName().equals("name")) {// Get // the // name name = map.item(j).getNodeValue(); } } if (name.equals(type)) { // If it's pf or qf according // to what the user selected // Get the parameters final String field = request.getParameter("field").toString(); final String value = request.getParameter("value").toString(); final String text = n.getTextContent(); // Get the // value of // the node, // Search for the requested field, if it is there // return the weight, if not return 0 final int index = text.indexOf(field + "^"); if (index != -1) { // If the field is already // weighted final int pas = field.length() + 1; final String textCut = text.substring(index + pas); if (value.equals("0")) { // If the user entered // 0 if (textCut.indexOf(" ") == -1) { // field is // the last // one then // we just // cut the // end of // the text // content n.setTextContent((text.substring(0, index)).trim()); } else { // the field and the part after n.setTextContent((text.substring(0, index) + text.substring(index + pas + textCut.indexOf(" "))).trim()); } } else { // If the user typed any other values if (textCut.indexOf(" ") == -1) { n.setTextContent(text.substring(0, index + pas) + value); } else { n.setTextContent(text.substring(0, index + pas) + value + text.substring(index + pas + textCut.indexOf(" "))); } } } else { // If it's not weighted if (!value.equals("0")) { // append the field and // it's value n.setTextContent((n.getTextContent() + " " + field + "^" + value).trim()); } } break; } } } // Apply the modifications final TransformerFactory transformerFactory = TransformerFactory.newInstance(); final Transformer transformer = transformerFactory.newTransformer(); transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes"); transformer.setOutputProperty(OutputKeys.ENCODING, "UTF-8"); transformer.setOutputProperty(OutputKeys.INDENT, "yes"); final DOMSource source = new DOMSource(searchHandler); final StreamResult result = new StreamResult(customSearchHandler); transformer.transform(source, result); } catch (final TransformerException e) { LOGGER.error( "Error while modifying the solrconfig.xml, in FieldWeight doPost, pls make sure the file is valid. Error 69030", e); final PrintWriter out = response.getWriter(); out.append( "Error while modifying the config file, please retry, if the problem persists contact your system administrator. Error Code : 69030"); out.close(); return; } } catch (final Exception e) { final PrintWriter out = response.getWriter(); out.append( "Something bad happened, please retry, if the problem persists contact your system administrator. Error code : 69511"); out.close(); LOGGER.error("Unindentified error in FieldWeight doPost. Error 69511", e); } }
From source file:org.uberfire.server.UberfireServlet.java
private void loadApp(PrintWriter writer, Locale locale) { final Subject subject = SecurityFactory.getIdentity(); final String localeTag = locale.getLanguage() + "_" + locale.getCountry(); final Map<String, String> map = new HashMap<String, String>() { {/* w w w . jav a 2 s.c om*/ put("name", subject.getName()); put("roles", collectionAsString(subject.getRoles())); put("properties", mapAsString(subject.getProperties())); put("locale", localeTag); } }; final String content = TemplateRuntime.execute(appTemplate, map).toString(); writer.append(content); }
From source file:com.daidiansha.acarry.control.network.core.volley.toolbox.HurlStack.java
/** * Perform a multipart request on a connection * * @param connection The Connection to perform the multi part request * @param request The params to add to the Multi Part request * The files to upload * @throws ProtocolException/*from w ww. j ava2 s. com*/ */ private void setConnectionParametersForMultipartRequest(HttpURLConnection connection, MultiPartRequest request) throws IOException, ProtocolException { final String charset = request.getProtocolCharset(); final int curTime = (int) (System.currentTimeMillis() / 1000); final String boundary = BOUNDARY_PREFIX + curTime; connection.setRequestMethod("POST"); connection.setDoOutput(true); connection.setRequestProperty(HEADER_CONTENT_TYPE, String.format(CONTENT_TYPE_MULTIPART, charset, curTime)); Map<String, MultiPartParam> multipartParams = request.getMultipartParams(); Map<String, String> filesToUpload = request.getFilesToUpload(); if (request.isFixedStreamingMode()) { int contentLength = getContentLengthForMultipartRequest(boundary, multipartParams, filesToUpload); connection.setFixedLengthStreamingMode(contentLength); } else { connection.setChunkedStreamingMode(0); } // Modified end PrintWriter writer = null; try { OutputStream out = connection.getOutputStream(); writer = new PrintWriter(new OutputStreamWriter(out, charset), true); for (String key : multipartParams.keySet()) { MultiPartParam param = multipartParams.get(key); writer.append(boundary).append(CRLF) .append(String.format(HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA, key)) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + param.contentType).append(CRLF) .append(CRLF).append(param.value).append(CRLF).flush(); } long allFileSize = 0; long allUpLoadSize = 0; int fileLocation = 0; for (String key : filesToUpload.keySet()) { File file = new File(filesToUpload.get(key)); if (!file.exists() || file.isDirectory()) { continue; } allFileSize += file.length(); } for (String key : filesToUpload.keySet()) { File file = new File(filesToUpload.get(key)); if (!file.exists()) { throw new IOException(String.format("File not found: %s", file.getAbsolutePath())); } if (file.isDirectory()) { throw new IOException(String.format("File is a directory: %s", file.getAbsolutePath())); } writer.append(boundary).append(CRLF) .append(String.format( HEADER_CONTENT_DISPOSITION + COLON_SPACE + FORM_DATA + SEMICOLON_SPACE + FILENAME, key, file.getName())) .append(CRLF).append(HEADER_CONTENT_TYPE + COLON_SPACE + CONTENT_TYPE_OCTET_STREAM) .append(CRLF).append(HEADER_CONTENT_TRANSFER_ENCODING + COLON_SPACE + BINARY).append(CRLF) .append(CRLF).flush(); BufferedInputStream input = null; try { FileInputStream fis = new FileInputStream(file); int transferredBytes = 0; int totalSize = (int) file.length(); input = new BufferedInputStream(fis); int bufferLength = 0; byte[] buffer = new byte[1024]; int progress = 0; while ((bufferLength = input.read(buffer)) > 0) { out.write(buffer, 0, bufferLength); transferredBytes += bufferLength; allUpLoadSize += bufferLength; int p = transferredBytes * 100 / totalSize; if (p != progress) { progress = p; request.fileProgress(filesToUpload.get(key), fileLocation, transferredBytes, totalSize, allUpLoadSize, allFileSize); } } out.flush(); // Important! Output cannot be closed. Close of // writer will close // output as well. } finally { if (input != null) try { input.close(); } catch (IOException ex) { ex.printStackTrace(); } } writer.append(CRLF).flush(); // CRLF is important! It indicates fileLocation++; // end of binary // boundary. } // End of multipart/form-data. writer.append(boundary + BOUNDARY_PREFIX).append(CRLF).flush(); } catch (Exception e) { e.printStackTrace(); } finally { if (writer != null) { writer.close(); } } }
From source file:jp.gr.java_conf.piropiroping.bluetoothcommander.MainActivity.java
@Override public void onDialogPositiveClick(DialogFragment dialog, EditText commandName) { // User touched the dialog's positive button String name = commandName.getText().toString(); // ?? String data = mOutEditText.getText().toString(); // int viewNum = savedCommand.size(); // ? for (int i = 0; i < viewNum; i++) { String savedName = savedCommand.get(i).getText().toString(); if (savedName.equals(name)) { // ????????????return Toast.makeText(getApplicationContext(), "That command name has already been registered.", Toast.LENGTH_SHORT).show(); return; }/*from ww w .j a va 2 s. c o m*/ } /* ?? */ try { OutputStream out = openFileOutput(name, MODE_PRIVATE); PrintWriter writer = new PrintWriter(new OutputStreamWriter(out, "UTF-8")); writer.append(data); writer.close(); } catch (IOException e) { e.printStackTrace(); } setCommandButtonListener(name, viewNum); }
From source file:UploadTest.java
@Test public void put_parent_test() { try {//from w w w. ja v a 2 s .c o m URL url = new URL("http://localhost:9000/resource/frl:6376983"); HttpURLConnection con = (HttpURLConnection) url.openConnection(); con.setDoOutput(true); con.setRequestMethod("PUT"); con.setRequestProperty("Authorization", basicAuth); con.setRequestProperty("Content-Type", "application/json"); con.setRequestProperty("Accept", "application/json"); con.connect(); OutputStream outputStream = con.getOutputStream(); PrintWriter writer = new PrintWriter(new OutputStreamWriter(outputStream, "UTF-8"), true); writer.append( "{\"contentType\":\"file\",\"parentPid\":\"frl:6376984\",\"accessScheme\":\"public\",\"publishScheme\":\"public\"}"); writer.flush(); outputStream.close(); writer.close(); con.disconnect(); System.out.println(con.getResponseCode()); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.jboss.errai.marshalling.rebind.MarshallerGenerator.java
private void generateMarshaller(final GeneratorContext context, final MetaClass type, final String className, final String marshallerTypeName, final TreeLogger logger, final PrintWriter printWriter) { MarshallerOutputTarget target = MarshallerOutputTarget.GWT; final MappingStrategy strategy = MappingStrategyFactory.createStrategy(true, GeneratorMappingContextFactory.getFor(context, target), type); String gen = null;/* w w w . j a v a 2 s .c o m*/ if (type.isArray()) { BuildMetaClass marshallerClass = MarshallerGeneratorFactory.generateArrayMarshaller(type, marshallerTypeName, true); gen = marshallerClass.toJavaString(); } else { final ClassStructureBuilder<?> marshaller = strategy.getMapper().getMarshaller(marshallerTypeName); gen = marshaller.toJavaString(); } printWriter.append(gen); final File tmpFile = new File(RebindUtils.getErraiCacheDir().getAbsolutePath() + "/" + className + ".java"); RebindUtils.writeStringToFile(tmpFile, gen); context.commit(logger, printWriter); }
From source file:annis.CSVHelper.java
public static void exportCSVData(Iterator<AnnotatedMatch> matches, SortedMap<Integer, SortedSet<String>> columnsByNodePos, PrintWriter w) { int count = columnsByNodePos.keySet().size(); // print values while (matches.hasNext()) { AnnotatedMatch match = matches.next(); List<String> line = new ArrayList<>(); int k = 0; for (; k < match.size(); ++k) { AnnotatedSpan span = match.get(k); Map<String, String> valueByName = new HashMap<>(); if (span != null) { if (span.getAnnotations() != null) { for (Annotation annotation : span.getAnnotations()) { valueByName.put("anno_" + annotation.getQualifiedName(), annotation.getValue()); }// w w w . j a va 2s . com } if (span.getMetadata() != null) { for (Annotation meta : span.getMetadata()) { valueByName.put("meta_" + meta.getQualifiedName(), meta.getValue()); } } line.add("" + span.getId()); line.add(span.getCoveredText().replace("\t", "\\t")); } for (String name : columnsByNodePos.get(k)) { if (valueByName.containsKey(name)) { line.add(valueByName.get(name).replace("\t", "\\t")); } else { line.add("'NULL'"); } } } for (int l = k; l < count; ++l) { line.add("'NULL'"); for (int m = 0; m <= columnsByNodePos.get(l).size(); ++m) { line.add("'NULL'"); } } w.append(StringUtils.join(line, "\t")); w.append("\n"); } }
From source file:org.kalypso.model.hydrology.internal.preprocessing.NAControlConverter.java
private void writeFalstart(final PrintWriter writer) throws NAPreprocessorException { final String system = "we";// "sys"; //$NON-NLS-1$ final String zustand = "nat"; //$NON-NLS-1$ final DateFormat format = NATimeSettings.getInstance() .getTimeZonedDateFormat(new SimpleDateFormat("yyyy MM dd HH")); //$NON-NLS-1$ final Date simulationStart = m_metaControl.getSimulationStart(); final Date simulationEnd = m_metaControl.getSimulationEnd(); final String startDate = format.format(simulationStart); final String endDate = format.format(simulationEnd); writer.append("xxx\n"); //$NON-NLS-1$ writer.append("x einzugsgebiet\n"); //$NON-NLS-1$ final String pathStartFile = m_startDir.getName() + File.separator + FILENAME_START_FILE; if (m_metaControl.isUsePrecipitationForm()) { final String preFormText = m_metaControl.getPrecipitationForm(); final int preForm = convertPreform(preFormText); if (preForm == 0) throw new NAPreprocessorException( Messages.getString("org.kalypso.convert.namodel.NAControlConverter.49")); //$NON-NLS-1$ final double annuality = m_metaControl.getAnnuality(); if (Double.isNaN(annuality)) throw new NAPreprocessorException(Messages.getString("NAControlConverter.0")); //$NON-NLS-1$ final double duration = m_metaControl.getDurationHours(); if (Double.isNaN(duration)) throw new NAPreprocessorException(Messages.getString("NAControlConverter.1")); //$NON-NLS-1$ writer.append(//from w ww . jav a 2s . co m "x Niederschlagsform (2-nat; 1-syn); projektverzeichnis; System(XXXX); Zustand (YYY); Dateiname: Wahrscheinlichkeit [1/a]; Dauer [h]; Verteilung; Konfigurationsdatei mit Pfad\n"); //$NON-NLS-1$ writer.append("1 .. " + system + " " + zustand + " " + "synth.st" + " " //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$ + FortranFormatHelper.printf(annuality, "f6.3") + " " //$NON-NLS-1$//$NON-NLS-2$ + FortranFormatHelper.printf(duration, "f9.3") //$NON-NLS-1$ + " " + Integer.toString(preForm) + " " + pathStartFile + "\n"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$ //$NON-NLS-4$ } else { writer.append( "x Niederschlagsform (2-nat; 1-syn); projektverzeichnis; System(XXXX); Zustand (YYY); Simulationsbeginn(dat+Zeit); Simulationsende; Konfigurationsdatei mit Pfad\n"); //$NON-NLS-1$ writer.append("2 .. " + system + " " + zustand + " " + startDate + " " + endDate + " " + pathStartFile //$NON-NLS-1$//$NON-NLS-2$//$NON-NLS-3$//$NON-NLS-4$//$NON-NLS-5$ + "\n"); //$NON-NLS-1$ //$NON-NLS-7$ } }