List of usage examples for java.io Writer append
public Writer append(char c) throws IOException
From source file:com.github.rvesse.airline.help.cli.bash.BashCompletionGenerator.java
private void writeCommandFunctionCall(Writer writer, GlobalMetadata<T> global, CommandGroupMetadata group, CommandMetadata command, int indent) throws IOException { // Just call the command function and pass its value back up indent(writer, indent);// w w w .j a v a 2s . c o m writer.append("COMPREPLY=( $("); writeCommandFunctionName(writer, global, group, command, false); writer.append(" \"${COMMANDS}\" ) )").append(NEWLINE); }
From source file:com.github.jsonj.JsonArray.java
@Override public void serialize(Writer w) throws IOException { w.append(JsonSerializer.OPEN_BRACKET); Iterator<JsonElement> it = iterator(); while (it.hasNext()) { JsonElement jsonElement = it.next(); jsonElement.serialize(w);/*from ww w . j av a 2 s . c o m*/ if (it.hasNext()) { w.append(JsonSerializer.COMMA); } } w.append(JsonSerializer.CLOSE_BRACKET); }
From source file:org.apache.commons.jci.examples.serverpages.JspGenerator.java
public byte[] generateJavaSource(final String pResourceName, final File pFile) { final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); final Writer output = new OutputStreamWriter(outputStream); try {/*from w w w.j a v a2 s . c om*/ final Reader input = new InputStreamReader(new FileInputStream(pFile)); final int p = pResourceName.lastIndexOf('/'); final String className; final String packageName; if (p < 0) { className = ConversionUtils.stripExtension(pResourceName); packageName = ""; } else { className = ConversionUtils.stripExtension(pResourceName.substring(p + 1)); packageName = pResourceName.substring(0, p).replace('/', '.'); output.append("package ").append(packageName).append(";").append('\n'); } output.append("import java.io.PrintWriter;").append('\n'); output.append("import java.io.IOException;").append('\n'); output.append("import javax.servlet.http.HttpServlet;").append('\n'); output.append("import javax.servlet.http.HttpServletRequest;").append('\n'); output.append("import javax.servlet.http.HttpServletResponse;").append('\n'); output.append("import javax.servlet.ServletException;").append('\n'); output.append("public class ").append(className).append(" extends HttpServlet {").append('\n'); output.append( " protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {") .append('\n'); output.append(" final PrintWriter out = response.getWriter();").append('\n'); final char[] open = "<?".toCharArray(); final char[] close = "?>".toCharArray(); StringBuilder sb = new StringBuilder(); char[] watch = open; int w = 0; while (true) { int c = input.read(); if (c < 0) { break; } if (c == watch[w]) { w++; if (watch.length == w) { if (watch == open) { // found open wrap(sb, output); sb = new StringBuilder(); watch = close; } else if (watch == close) { // found close // <? ... ?> is java output.append(sb.toString()); sb = new StringBuilder(); watch = open; } w = 0; } } else { if (w > 0) { sb.append(watch, 0, w); } sb.append((char) c); w = 0; } } if (watch == open) { wrap(sb, output); } output.append(" out.close();").append('\n'); output.append(" out.flush();").append('\n'); output.append(" }").append('\n'); output.append("}").append('\n'); return outputStream.toByteArray(); } catch (IOException e) { return null; } finally { try { output.close(); } catch (IOException e) { } } }
From source file:com.github.rvesse.airline.help.cli.bash.BashCompletionGenerator.java
private void generateGroupCompletionFunction(Writer writer, GlobalMetadata<T> global, CommandGroupMetadata group) throws IOException { // Start Function writeGroupFunctionName(writer, global, group, true); // Prepare variables writer.append(" # Get completion data").append(NEWLINE); writer.append(" COMPREPLY=()").append(NEWLINE); writer.append(" CURR_WORD=${COMP_WORDS[COMP_CWORD]}").append(NEWLINE); writer.append(" PREV_WORD=${COMP_WORDS[COMP_CWORD-1]}").append("\n"); writer.append(" CURR_CMD=").append(NEWLINE); writer.append(" if [[ ${COMP_CWORD} -ge 2 ]]; then").append(NEWLINE); writer.append(" CURR_CMD=${COMP_WORDS[2]}").append(NEWLINE); writer.append(" fi").append(DOUBLE_NEWLINE); // Prepare list of group commands Set<String> commandNames = new HashSet<>(); for (CommandMetadata command : group.getCommands()) { if (command.isHidden() && !this.includeHidden()) continue; commandNames.add(command.getName()); }// w w w .j a v a 2 s .c o m writeWordListVariable(writer, 2, "COMMANDS", commandNames.iterator()); // Check if we are completing a group writer.append(" if [[ ${COMP_CWORD} -eq 2 ]]; then").append(NEWLINE); // Include the default command directly if present if (group.getDefaultCommand() != null) { // Need to call the completion function and combine its output // with that of the list of available commands writeCommandFunctionCall(writer, global, group, group.getDefaultCommand(), 4); indent(writer, 4); writer.append("DEFAULT_GROUP_COMMAND_COMPLETIONS=(${COMPREPLY[@]})").append(NEWLINE); } if (global.getDefaultCommand() != null) { writeCompletionGeneration(writer, 4, true, null, "COMMANDS", "DEFAULT_GROUP_COMMAND_COMPLETIONS"); } else { writeCompletionGeneration(writer, 4, true, null, "COMMANDS"); } writer.append(" fi").append(DOUBLE_NEWLINE); // Otherwise we must be in a specific command // Use a switch statement to provide command specific completion writer.append(" case ${CURR_CMD} in").append(NEWLINE); for (CommandMetadata command : group.getCommands()) { if (command.isHidden() && !this.includeHidden()) continue; // Add case for the command writeCommandCase(writer, global, group, command, 4, true); } writer.append(" esac").append(NEWLINE); // End Function writer.append('}').append(DOUBLE_NEWLINE); }
From source file:org.apache.shindig.gadgets.parse.GadgetHtmlNode.java
/** * Render self as HTML. Rendering is relatively simple as no * additional validation is performed on content beyond what * the rest of the class provides, such as attribute key * validation. All whitespace and comments are maintained. Nodes * with zero children are rendered short-form (<foo/>) * unless tagName is "style" or "script" since many browsers dislike short-form * for those.//from w w w . j av a 2 s . co m * One space is provided between attributes. Attribute values are surrounded * in double-quotes. Null-valued attributes are rendered without ="value". * Attributes are rendered in no particular order. * @param w Writer to which to send content * @throws IOException If the writer throws an error on append(...) */ public void render(Writer w) throws IOException { if (isText()) { String rawText = getText(); int commentStart = 0; int curPos = 0; while ((commentStart = rawText.indexOf("<!--", curPos)) >= 0) { // Comment found. By definition there must be an end-comment marker // since if there wasn't, the comment would subsume all further text. // First append up to the current point, with proper escaping. w.append(StringEscapeUtils.escapeHtml(rawText.substring(curPos, commentStart))); // Then append the comment verbatim. int commentEnd = rawText.indexOf("-->", commentStart); if (commentEnd == -1) { // Should never happen, per above comment. But we know that the comment // has begun, so just append the rest of the string verbatim to be safe. w.append(rawText.substring(commentStart)); return; } int endPos = commentEnd + "-->".length(); w.append(rawText.substring(commentStart, endPos)); // Then set current position curPos = endPos; } // Append remaining (all, if no comment) text, escaped. w.append(StringEscapeUtils.escapeHtml(rawText.substring(curPos))); } else { w.append('<').append(tagName); for (String attrKey : getAttributeKeys()) { String attrValue = getAttributeValue(attrKey); w.append(' ').append(attrKey); if (attrValue != null) { w.append("=\"").append(attrValue.replaceAll("\"", """)).append('"'); } } if (children.size() == 0 && !tagName.equalsIgnoreCase("style") && !tagName.equalsIgnoreCase("script")) { w.append("/>"); } else { w.append('>'); for (GadgetHtmlNode child : children) { child.render(w); } w.append("</").append(tagName).append('>'); } } }
From source file:com.alta189.cyborg.api.util.config.ini.IniConfiguration.java
/** * Writes a single section of nodes to the specified Writer * The nodes passed to this method must not have children * @param writer The Writer to write data to * @param nodes The nodes to write//from w w w . j a v a 2s . c om * @throws ConfigurationException when a node cannot be correctly written */ protected void writeNodeSection(Writer writer, Collection<ConfigurationNode> nodes) throws ConfigurationException { try { for (ConfigurationNode node : nodes) { if (node.hasChildren()) { throw new ConfigurationException("Nodes passed to getChildlessNodes must not have children!"); } String[] comment = getComment(node); if (comment != null) { for (String line : comment) { writer.append(getPreferredCommentChar()).append(" ").append(line).append(LINE_SEPARATOR); } } writer.append(node.getPathElements()[node.getPathElements().length - 1]).append("=") .append(toStringValue(node.getValue())).append(LINE_SEPARATOR); } } catch (IOException e) { throw new ConfigurationException(e); } }
From source file:core.importmodule.parser.cisco.CiscoCommandSplitter.java
/** * Copies lines from the source file to a where lineNumber <= end && lineNumber * >= start/*from w w w . j ava 2s. c om*/ * * @param start First line to be copied. * @param end Last line to be copied. * @param source Source file from where to copy. * @return The newly creates and written temp file set to delete on JVM * exit. * @throws IOException Thrown is source fails to open, tempFile fails to * write, or other IO failures. */ private File copyLinesToTempFile(String prefix, int start, int end, File source) throws IOException { File f = getTempFile(prefix, CiscoCommandSplitter.deleteOnExit); Writer writer = getWriter(f); BufferedReader reader = getReader(source); String line; int skip = start - 1; // minus one to copy it before we actual count it while ((line = reader.readLine()) != null) { if (skip != 0) { skip--; } else if (start <= end) { if (debug) { System.out.println(String.format("Writing line %d: %s", start, line)); } writer.write(line); writer.append("\n"); start++; } else { break; } } writer.close(); reader.close(); return f; }
From source file:org.apache.unomi.web.ContextServlet.java
@Override public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { final Date timestamp = new Date(); if (request.getParameter("timestamp") != null) { timestamp.setTime(Long.parseLong(request.getParameter("timestamp"))); }//from w w w . j a v a2 s. c o m // first we must retrieve the context for the current visitor, and build a Javascript object to attach to the // script output. String profileId; HttpServletRequest httpServletRequest = (HttpServletRequest) request; String httpMethod = httpServletRequest.getMethod(); // logger.debug(HttpUtils.dumpRequestInfo(httpServletRequest)); // set up CORS headers as soon as possible so that errors are not misconstrued on the client for CORS errors HttpUtils.setupCORSHeaders(httpServletRequest, response); if ("options".equals(httpMethod.toLowerCase())) { response.flushBuffer(); return; } Profile profile = null; String cookieProfileId = null; Cookie[] cookies = httpServletRequest.getCookies(); for (Cookie cookie : cookies) { if (profileIdCookieName.equals(cookie.getName())) { cookieProfileId = cookie.getValue(); } } Session session = null; String personaId = request.getParameter("personaId"); if (personaId != null) { PersonaWithSessions personaWithSessions = profileService.loadPersonaWithSessions(personaId); if (personaWithSessions == null) { logger.error("Couldn't find persona with id=" + personaId); profile = null; } else { profile = personaWithSessions.getPersona(); session = personaWithSessions.getLastSession(); } } String sessionId = request.getParameter("sessionId"); if (cookieProfileId == null && sessionId == null && personaId == null) { ((HttpServletResponse) response).sendError(HttpServletResponse.SC_BAD_REQUEST); return; } boolean profileCreated = false; ContextRequest contextRequest = null; String scope = null; String stringPayload = HttpUtils.getPayload(httpServletRequest); if (stringPayload != null) { ObjectMapper mapper = CustomObjectMapper.getObjectMapper(); JsonFactory factory = mapper.getFactory(); try { contextRequest = mapper.readValue(factory.createParser(stringPayload), ContextRequest.class); } catch (Exception e) { logger.error("Cannot read payload " + stringPayload, e); return; } scope = contextRequest.getSource().getScope(); } int changes = EventService.NO_CHANGE; if (profile == null) { if (sessionId != null) { session = profileService.loadSession(sessionId, timestamp); if (session != null) { profileId = session.getProfileId(); profile = profileService.load(profileId); profile = checkMergedProfile(response, profile, session); } } if (profile == null) { // profile not stored in session if (cookieProfileId == null) { // no profileId cookie was found, we generate a new one and create the profile in the profile service profile = createNewProfile(null, response, timestamp); profileCreated = true; } else { profile = profileService.load(cookieProfileId); if (profile == null) { // this can happen if we have an old cookie but have reset the server, // or if we merged the profiles and somehow this cookie didn't get updated. profile = createNewProfile(null, response, timestamp); profileCreated = true; HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain); } else { profile = checkMergedProfile(response, profile, session); } } } else if ((cookieProfileId == null || !cookieProfileId.equals(profile.getItemId())) && !profile.isAnonymousProfile()) { // profile if stored in session but not in cookie HttpUtils.sendProfileCookie(profile, response, profileIdCookieName, profileIdCookieDomain); } // associate profile with session if (sessionId != null && session == null) { session = new Session(sessionId, profile, timestamp, scope); changes |= EventService.SESSION_UPDATED; Event event = new Event("sessionCreated", session, profile, scope, null, session, timestamp); event.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request); event.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response); logger.debug("Received event " + event.getEventType() + " for profile=" + profile.getItemId() + " session=" + session.getItemId() + " target=" + event.getTarget() + " timestamp=" + timestamp); changes |= eventService.send(event); } } if (profileCreated) { changes |= EventService.PROFILE_UPDATED; Event profileUpdated = new Event("profileUpdated", session, profile, scope, null, profile, timestamp); profileUpdated.setPersistent(false); profileUpdated.getAttributes().put(Event.HTTP_REQUEST_ATTRIBUTE, request); profileUpdated.getAttributes().put(Event.HTTP_RESPONSE_ATTRIBUTE, response); logger.debug("Received event {} for profile={} {} target={} timestamp={}", profileUpdated.getEventType(), profile.getItemId(), session != null ? " session=" + session.getItemId() : "", profileUpdated.getTarget(), timestamp); changes |= eventService.send(profileUpdated); } ContextResponse data = new ContextResponse(); data.setProfileId(profile.isAnonymousProfile() ? cookieProfileId : profile.getItemId()); if (privacyService.isRequireAnonymousBrowsing(profile.getItemId())) { profile = privacyService.getAnonymousProfile(); session.setProfile(profile); changes = EventService.SESSION_UPDATED; } if (contextRequest != null) { changes |= handleRequest(contextRequest, profile, session, data, request, response, timestamp); } if ((changes & EventService.PROFILE_UPDATED) == EventService.PROFILE_UPDATED && profile != null) { profileService.save(profile); } if ((changes & EventService.SESSION_UPDATED) == EventService.SESSION_UPDATED && session != null) { profileService.saveSession(session); } String extension = httpServletRequest.getRequestURI() .substring(httpServletRequest.getRequestURI().lastIndexOf(".") + 1); boolean noScript = "json".equals(extension); String contextAsJSONString = CustomObjectMapper.getObjectMapper().writeValueAsString(data); Writer responseWriter; if (noScript) { response.setCharacterEncoding("UTF-8"); responseWriter = response.getWriter(); response.setContentType("application/json"); IOUtils.write(contextAsJSONString, responseWriter); } else { responseWriter = response.getWriter(); responseWriter.append("window.digitalData = window.digitalData || {};\n").append("var cxs = ") .append(contextAsJSONString).append(";\n"); // now we copy the base script source code InputStream baseScriptStream = getServletContext().getResourceAsStream( profile instanceof Persona ? IMPERSONATE_BASE_SCRIPT_LOCATION : BASE_SCRIPT_LOCATION); IOUtils.copy(baseScriptStream, responseWriter); } responseWriter.flush(); }
From source file:pltag.corpus.TagCorpus.java
/** * Used for printing to other media (e.g. the lexicon) but appending the string to the * writer object. // w w w . j av a2 s . co m * * @param lexEntry * @throws IOException */ private void print(Writer writer, String entry) throws IOException { writer.append(entry + "\n"); writer.flush(); }
From source file:org.auraframework.integration.test.service.ServerServiceImplTest.java
/** * This is verification for W-2657282. The bug was when an IOException is thrown in try block, * a new exception may be thrown in finally block, so the new exception will hide the original * exception.//from w w w . j a va 2s . c o m * Verify the original (real) IO exception is thrown from method run. */ @Test public void testThrowsOriginalIOExceptionFromRun() throws Exception { String exceptionMessage = "Test exception"; contextService.startContext(Mode.UTEST, Format.JSON, Authentication.AUTHENTICATED); Writer writer = mock(Writer.class); when(writer.append('{')).thenThrow(new IOException(exceptionMessage)); Message message = new Message(new ArrayList<Action>()); ServerService ss = serverService; try { ss.run(message, contextService.getCurrentContext(), writer, null); fail("Exception should be thrown from method run()."); } catch (IOException e) { assertEquals(exceptionMessage, e.getMessage()); } }