List of usage examples for java.io Writer append
public Writer append(char c) throws IOException
From source file:com.github.rvesse.airline.help.html.HtmlCommandUsageGenerator.java
@Override public <T> void usage(String programName, String[] groupNames, String commandName, CommandMetadata command, ParserMetadata<T> parserConfig, OutputStream output) throws IOException { if (parserConfig == null) { parserConfig = MetadataLoader.loadParser(command.getType()); }//from ww w .jav a 2 s . c o m Writer writer = new OutputStreamWriter(output); // Header outputHtmlHeader(writer); writer.append("<body>\n"); // Page Header i.e. <h1> outputPageHeader(writer, programName, groupNames, command); // Name and description of command outputDescription(writer, programName, groupNames, command); // TODO Output pre help sections // Synopsis List<OptionMetadata> options = outputSynopsis(writer, programName, groupNames, command); // Options if (options.size() > 0 || command.getArguments() != null) { options = sortOptions(options); outputOptions(writer, options, command.getArguments(), parserConfig); } // TODO Output post help sections writer.append("</body>\n"); writer.append("</html>\n"); // Flush the output writer.flush(); output.flush(); }
From source file:org.structr.rest.servlet.GraphQLServlet.java
private void handleGraphQLRequest(final HttpServletRequest request, final HttpServletResponse response, final String query) throws IOException, FrameworkException { final SecurityContext securityContext; final Authenticator authenticator; try {/*from w w w . j a v a 2s . c om*/ // isolate request authentication in a transaction try (final Tx tx = StructrApp.getInstance().tx()) { authenticator = config.getAuthenticator(); securityContext = authenticator.initializeAndExamineRequest(request, response); tx.success(); } final App app = StructrApp.getInstance(securityContext); if (securityContext != null) { // isolate write output try (final Tx tx = app.tx()) { final Document doc = GraphQLRequest.parse(new Parser(), query); if (doc != null) { final List<ValidationError> errors = new Validator() .validateDocument(SchemaService.getGraphQLSchema(), doc); if (errors.isEmpty()) { // no validation errors in query, do request final GraphQLWriter graphQLWriter = new GraphQLWriter(true); // no trailing semicolon so we dont trip MimeTypes.getContentTypeWithoutCharset response.setContentType("application/json; charset=utf-8"); final Writer writer = response.getWriter(); graphQLWriter.stream(securityContext, writer, new GraphQLRequest(securityContext, doc, query)); writer.append("\n"); // useful newline } else { final Map<String, Object> map = new LinkedHashMap<>(); final Writer writer = response.getWriter(); final Gson gson = getGson(); map.put("errors", errors); gson.toJson(map, writer); writer.append("\n"); // useful newline // send 422 status response.setStatus(422); } } tx.success(); } } } catch (FrameworkException frameworkException) { // set status & write JSON output response.setStatus(frameworkException.getStatus()); getGson().toJson(frameworkException, response.getWriter()); response.getWriter().println(); } catch (IllegalStateException | IllegalArgumentException iex) { final Map<String, Object> map = new LinkedHashMap<>(); map.put("code", 422); map.put("message", iex.getMessage()); // set status & write JSON output response.setStatus(422); getGson().toJson(map, response.getWriter()); response.getWriter().println(); } catch (UnsupportedOperationException uoe) { logger.warn("POST not supported"); int code = HttpServletResponse.SC_BAD_REQUEST; response.setStatus(code); response.getWriter() .append(RestMethodResult.jsonError(code, "POST not supported: " + uoe.getMessage())); } catch (Throwable t) { logger.warn("Exception in POST", t); int code = HttpServletResponse.SC_INTERNAL_SERVER_ERROR; response.setStatus(code); response.getWriter() .append(RestMethodResult.jsonError(code, "JsonSyntaxException in POST: " + t.getMessage())); } finally { try { //response.getWriter().flush(); response.getWriter().close(); } catch (Throwable t) { logger.warn("Unable to flush and close response: {}", t.getMessage()); } } }
From source file:com.github.rvesse.airline.help.html.HtmlCommandUsageGenerator.java
/** * Outputs a documentation section with a synopsis of the command * //from ww w .ja v a 2s. c om * @param writer * Writer * @param programName * Program name * @param groupNames * Group name(s) * @param command * Command name * @return List of all the available options (Global, Group and Command) * @throws IOException */ protected List<OptionMetadata> outputSynopsis(Writer writer, String programName, String[] groupNames, CommandMetadata command) throws IOException { writer.append("<h1 class=\"text-info\">SYNOPSIS</h1>\n").append(NEWLINE); List<OptionMetadata> options = new ArrayList<>(); writer.append("<div class=\"row\">\n"); writer.append("<div class=\"span8 offset1\">\n"); if (programName != null) { writer.append(htmlize(programName)).append(" ").append( htmlize(StringUtils.join(toSynopsisUsage(sortOptions(command.getGlobalOptions())), ' '))); options.addAll(command.getGlobalOptions()); } if (groupNames != null) { for (int i = 0; i < groupNames.length; i++) { writer.append(htmlize(groupNames[i])).append(" "); } writer.append(htmlize(StringUtils.join(toSynopsisUsage(sortOptions(command.getGroupOptions())), ' '))); options.addAll(command.getGroupOptions()); } writer.append(htmlize(command.getName())).append(" ") .append(htmlize(StringUtils.join(toSynopsisUsage(sortOptions(command.getCommandOptions())), ' '))); options.addAll(command.getCommandOptions()); // command arguments (optional) ArgumentsMetadata arguments = command.getArguments(); if (arguments != null) { writer.append(" [--] ").append(htmlize(toUsage(arguments))); } writer.append("</div>\n"); writer.append("</div>\n"); return options; }
From source file:com.google.glassware.NotifyServlet.java
@Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Respond with OK and status 200 in a timely fashion to prevent redelivery response.setContentType("text/html"); Writer writer = response.getWriter(); writer.append("OK"); writer.close();/*from w w w .jav a 2 s .c om*/ // Get the notification object from the request body (into a string so we // can log it) BufferedReader notificationReader = new BufferedReader(new InputStreamReader(request.getInputStream())); String notificationString = ""; String responseStringForFaceDetection = null; // Count the lines as a very basic way to prevent Denial of Service attacks int lines = 0; String line; while ((line = notificationReader.readLine()) != null) { notificationString += line; lines++; // No notification would ever be this long. Something is very wrong. if (lines > 1000) { throw new IOException("Attempted to parse notification payload that was unexpectedly long."); } } notificationReader.close(); LOG.info("got raw notification " + notificationString); JsonFactory jsonFactory = new JacksonFactory(); // If logging the payload is not as important, use // jacksonFactory.fromInputStream instead. Notification notification = jsonFactory.fromString(notificationString, Notification.class); LOG.info("Got a notification with ID: " + notification.getItemId()); // Figure out the impacted user and get their credentials for API calls String userId = notification.getUserToken(); Credential credential = AuthUtil.getCredential(userId); Mirror mirrorClient = MirrorClient.getMirror(credential); if (notification.getCollection().equals("locations")) { LOG.info("Notification of updated location"); Mirror glass = MirrorClient.getMirror(credential); // item id is usually 'latest' Location location = glass.locations().get(notification.getItemId()).execute(); LOG.info("New location is " + location.getLatitude() + ", " + location.getLongitude()); MirrorClient.insertTimelineItem(credential, new TimelineItem() .setText("Java Quick Start says you are now at " + location.getLatitude() + " by " + location.getLongitude()) .setNotification(new NotificationConfig().setLevel("DEFAULT")).setLocation(location) .setMenuItems(Lists.newArrayList(new MenuItem().setAction("NAVIGATE")))); // This is a location notification. Ping the device with a timeline item // telling them where they are. } else if (notification.getCollection().equals("timeline")) { // Get the impacted timeline item TimelineItem timelineItem = mirrorClient.timeline().get(notification.getItemId()).execute(); LOG.info("Notification impacted timeline item with ID: " + timelineItem.getId()); // If it was a share, and contains a photo, update the photo's caption to // acknowledge that we got it. if (notification.getUserActions().contains(new UserAction().setType("SHARE")) && timelineItem.getAttachments() != null && timelineItem.getAttachments().size() > 0) { String finalresponseForCard = null; String questionString = timelineItem.getText(); if (!questionString.isEmpty()) { String[] questionStringArray = questionString.split(" "); LOG.info(timelineItem.getText() + " is the questions asked by the user"); LOG.info("A picture was taken"); if (questionString.toLowerCase().contains("search") || questionString.toLowerCase().contains("tag") || questionString.toLowerCase().contains("train") || questionString.toLowerCase().contains("mark") || questionString.toLowerCase().contains("recognize") || questionString.toLowerCase().contains("what is")) { //Fetching the image from the timeline InputStream inputStream = downloadAttachment(mirrorClient, notification.getItemId(), timelineItem.getAttachments().get(0)); //converting the image to Base64 Base64 base64Object = new Base64(false); String encodedImageToBase64 = base64Object.encodeToString(IOUtils.toByteArray(inputStream)); //byteArrayForOutputStream.toByteArray() // byteArrayForOutputStream.close(); encodedImageToBase64 = java.net.URLEncoder.encode(encodedImageToBase64, "ISO-8859-1"); //sending the API request LOG.info("Sending request to API"); //For initial protoype we're calling the Alchemy API for detecting the number of Faces using web API call try { String urlParameters = ""; String tag = ""; if (questionString.toLowerCase().contains("tag") || questionString.toLowerCase().contains("mark")) { tag = extractTagFromQuestion(questionString); urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_add&name_space=recognizeObject&user_id=user1&tag=" + tag + "&base64=" + encodedImageToBase64; } else if (questionString.toLowerCase().contains("train")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_train&name_space=recognizeObject&user_id=user1"; } else if (questionString.toLowerCase().contains("search")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_search&name_space=recognizeObject&user_id=user1&base64=" + encodedImageToBase64; } else if (questionString.toLowerCase().contains("recognize") || questionString.toLowerCase().contains("what is")) { urlParameters = "api_key=gE4P9Mze0ewOa976&api_secret=96JJ4G1bBLPaWLhf&jobs=object_recognize&name_space=recognizeObject&user_id=user1&base64=" + encodedImageToBase64; } byte[] postData = urlParameters.getBytes(Charset.forName("UTF-8")); int postDataLength = postData.length; String newrequest = "http://rekognition.com/func/api/"; URL url = new URL(newrequest); HttpURLConnection connectionFaceDetection = (HttpURLConnection) url.openConnection(); // Increase the timeout for reading the response connectionFaceDetection.setReadTimeout(15000); connectionFaceDetection.setDoOutput(true); connectionFaceDetection.setDoInput(true); connectionFaceDetection.setInstanceFollowRedirects(false); connectionFaceDetection.setRequestMethod("POST"); connectionFaceDetection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); connectionFaceDetection.setRequestProperty("X-Mashape-Key", "pzFbNRvNM4mshgWJvvdw0wpLp5N1p1X3AX9jsnOhjDUkn5Lvrp"); connectionFaceDetection.setRequestProperty("charset", "utf-8"); connectionFaceDetection.setRequestProperty("Accept", "application/json"); connectionFaceDetection.setRequestProperty("Content-Length", Integer.toString(postDataLength)); connectionFaceDetection.setUseCaches(false); DataOutputStream outputStreamForFaceDetection = new DataOutputStream( connectionFaceDetection.getOutputStream()); outputStreamForFaceDetection.write(postData); BufferedReader inputStreamForFaceDetection = new BufferedReader( new InputStreamReader((connectionFaceDetection.getInputStream()))); StringBuilder responseForFaceDetection = new StringBuilder(); while ((responseStringForFaceDetection = inputStreamForFaceDetection .readLine()) != null) { responseForFaceDetection.append(responseStringForFaceDetection); } //closing all the connections inputStreamForFaceDetection.close(); outputStreamForFaceDetection.close(); connectionFaceDetection.disconnect(); responseStringForFaceDetection = responseForFaceDetection.toString(); LOG.info(responseStringForFaceDetection); JSONObject responseJSONObjectForFaceDetection = new JSONObject( responseStringForFaceDetection); if (questionString.toLowerCase().contains("train") || questionString.contains("tag") || questionString.toLowerCase().contains("mark")) { JSONObject usageKeyFromResponse = responseJSONObjectForFaceDetection .getJSONObject("usage"); finalresponseForCard = usageKeyFromResponse.getString("status"); if (!tag.equals("")) finalresponseForCard = "Object is tagged as " + tag; } else { JSONObject sceneUnderstandingObject = responseJSONObjectForFaceDetection .getJSONObject("scene_understanding"); JSONArray matchesArray = sceneUnderstandingObject.getJSONArray("matches"); JSONObject firstResultFromArray = matchesArray.getJSONObject(0); double percentSureOfObject; //If an score has value 1, then the value type is Integer else the value type is double if (firstResultFromArray.get("score") instanceof Integer) { percentSureOfObject = (Integer) firstResultFromArray.get("score") * 100; } else percentSureOfObject = (Double) firstResultFromArray.get("score") * 100; finalresponseForCard = "The object is " + firstResultFromArray.getString("tag") + ". Match score is" + percentSureOfObject; } //section where if it doesn't contain anything about tag or train } catch (Exception e) { LOG.warning(e.getMessage()); } } else finalresponseForCard = "Could not understand your words"; } else finalresponseForCard = "Could not understand your words"; TimelineItem responseCardForSDKAlchemyAPI = new TimelineItem(); responseCardForSDKAlchemyAPI.setText(finalresponseForCard); responseCardForSDKAlchemyAPI .setMenuItems(Lists.newArrayList(new MenuItem().setAction("READ_ALOUD"))); responseCardForSDKAlchemyAPI.setSpeakableText(finalresponseForCard); responseCardForSDKAlchemyAPI.setSpeakableType("Results are as follows"); responseCardForSDKAlchemyAPI.setNotification(new NotificationConfig().setLevel("DEFAULT")); mirrorClient.timeline().insert(responseCardForSDKAlchemyAPI).execute(); LOG.info("New card added to the timeline"); } else if (notification.getUserActions().contains(new UserAction().setType("LAUNCH"))) { LOG.info("It was a note taken with the 'take a note' voice command. Processing it."); // Grab the spoken text from the timeline card and update the card with // an HTML response (deleting the text as well). String noteText = timelineItem.getText(); String utterance = CAT_UTTERANCES[new Random().nextInt(CAT_UTTERANCES.length)]; timelineItem.setText(null); timelineItem.setHtml(makeHtmlForCard( "<p class='text-auto-size'>" + "Oh, did you say " + noteText + "? " + utterance + "</p>")); timelineItem.setMenuItems(Lists.newArrayList(new MenuItem().setAction("DELETE"))); mirrorClient.timeline().update(timelineItem.getId(), timelineItem).execute(); } else { LOG.warning("I don't know what to do with this notification, so I'm ignoring it."); } } }
From source file:com.norconex.importer.parser.impl.xfdl.XFDLParser.java
private boolean writeValue(Writer out, String value, boolean isOuputEmpty) throws IOException { boolean stillEmpty = true; if (StringUtils.isNotBlank(value)) { if (isOuputEmpty) { // Add space at the beginning to avoid false // document type recognition like MILESTONE // for docs that start with MILES out.write(" "); stillEmpty = false;//from www.j a v a 2 s . c om } out.append(value).append("\n"); } return stillEmpty; }
From source file:com.redhat.rhn.frontend.taglibs.UnpagedListDisplayTag.java
@Override protected void renderHeadExtraAddons(Writer out) throws IOException { super.renderHeadExtraAddons(out); LocalizationService ls = LocalizationService.getInstance(); if (getType().equals("treeview")) { out.append("<div class=\"spacewalk-list-channel-show-hide\">" + "<a class=\"spacewalk-list-channel-show-all\"" + " href=\"javascript:showAllRows();\" style=\"cursor: pointer;\">" + ls.getMessage("channels.overview.showall") + "</a> | " + "<a class=\"spacewalk-list-channel-hide-all\"" + " href=\"javascript:hideAllRows();\" style=\"cursor: pointer;\">" + ls.getMessage("channels.overview.hideall") + "</a></div>"); }//from ww w. ja va 2s . co m }
From source file:org.openmrs.arden.MLMObjectElement.java
public boolean writeEvaluate(String key, Writer w) throws Exception { boolean retVal = true; String cn = conceptName;/*from w ww . j a v a 2 s.c o m*/ if (cn != null) { /*************************************************************************************** * **************************************************************************************/ if (this.datasource.equalsIgnoreCase(PARAMETERS_DATASOURCE)) { w.append("\n\t\t\tResult " + key + "=new Result((String) parameters.get(\"" + cn + "\")"); } else { w.append("\n\t\t\tResult " + key + "=context.read(\n\t\t\t\tpatient.getPatientId(),context.getLogicDataSource(\"" + this.datasource + "\"),\n\t\t\t\tnew LogicCriteriaImpl(\"" + cn.trim() + "\")"); } if (hasWhere) { if (whereType.equals("withinPreceding")) { w.append(".within(Duration." + durationOp + "(-" + durationVal + "))"); } } //right the read type if (readType != null && readType.length() > 0) { w.append(this.getReadTypeAsString()); } w.append(");"); w.append("\n\t\t\tresultLookup.put(\"" + key + "\"," + key + ");"); } return retVal; }
From source file:org.walkmod.writers.AbstractFileWriter.java
public void append(String content, Writer writer, char endLineChar) throws IOException { BufferedReader reader = new BufferedReader(new StringReader(content)); String line = reader.readLine(); String endLine = "\n"; if (endLineChar == '\r') { endLine = "\r\n"; }/*from ww w.j a va 2 s . co m*/ while (line != null) { writer.append(line + endLine); line = reader.readLine(); } }
From source file:fi.okm.mpass.shibboleth.profile.impl.AbstractAuthnFlowRestResponseAction.java
/** {@inheritDoc} */ @Override/*from w ww . java 2 s . c o m*/ @Nonnull public Event execute(@Nonnull final RequestContext springRequestContext) { ComponentSupport.ifNotInitializedThrowUninitializedComponentException(this); final HttpServletRequest httpRequest = getHttpServletRequest(); final String lang = (StringSupport.trimOrNull(httpRequest.getParameter("lang")) == null) ? supportedLocales.get(0) : StringSupport.trim(httpRequest.getParameter("lang")).toUpperCase(); pushHttpResponseProperties(); final HttpServletResponse httpResponse = getHttpServletResponse(); try { final Writer out = new OutputStreamWriter(httpResponse.getOutputStream(), "UTF-8"); if (!HttpMethod.GET.toString().equals(httpRequest.getMethod())) { log.warn("{}: Unsupported method attempted {}", getLogPrefix(), httpRequest.getMethod()); out.append(makeErrorResponse(HttpStatus.SC_METHOD_NOT_ALLOWED, httpRequest.getMethod() + " not allowed", "Only GET is allowed")); } else if (!getSupportedLocales().contains(lang)) { log.warn("{}: Unsupported language attempted {}", getLogPrefix(), lang); out.append(makeErrorResponse(HttpStatus.SC_BAD_REQUEST, "Language '" + lang + "' not supported", "Supported languages: " + supportedLocales)); } else { final Object response = getResponse(lang); if (response != null) { final Gson gson = new Gson(); final LocalizedResponse localizedResponse = new LocalizedResponse(); localizedResponse.setLang(lang); localizedResponse.setResponse(response); out.append(gson.toJson(localizedResponse)); httpResponse.setStatus(HttpStatus.SC_OK); } else { out.append(makeErrorResponse(HttpStatus.SC_NOT_IMPLEMENTED, "Not implemented on the server side", "")); } } out.flush(); } catch (IOException e) { log.error("{}: Could not encode the JSON response", getLogPrefix(), e); httpResponse.setStatus(HttpStatus.SC_SERVICE_UNAVAILABLE); return ActionSupport.buildEvent(this, EventIds.IO_ERROR); } return ActionSupport.buildProceedEvent(this); }
From source file:com.redhat.rhn.frontend.taglibs.ListDisplayTagBase.java
/** * Renders the title header if set./*from w ww. ja v a 2s.com*/ * @param out JspWriter * @throws IOException thrown if there's a problem writing to the JSP */ protected void renderTitle(Writer out) throws IOException { if (!StringUtils.isEmpty(title)) { HtmlTag h4 = new HtmlTag("h4"); h4.setAttribute("class", "panel-title"); h4.addBody(LocalizationService.getInstance().getMessage(title)); out.append(h4.render()); } }